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

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.141.  .6(raebu    4:20): # $Id: loncommon.pm,v 1.1075.2.141.2.5 2020/07/19 21:33:46 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.1075.2.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.1075.2.141.  .1(raebu   86:20): use String::CRC32();
                     87:20): use Short::URL();
1.117     www        88: 
1.517     raeburn    89: # ---------------------------------------------- Designs
                     90: use vars qw(%defaultdesign);
                     91: 
1.22      www        92: my $readit;
                     93: 
1.517     raeburn    94: 
1.157     matthew    95: ##
                     96: ## Global Variables
                     97: ##
1.46      matthew    98: 
1.643     foxr       99: 
                    100: # ----------------------------------------------- SSI with retries:
                    101: #
                    102: 
                    103: =pod
                    104: 
1.648     raeburn   105: =head1 Server Side include with retries:
1.643     foxr      106: 
                    107: =over 4
                    108: 
1.648     raeburn   109: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      110: 
                    111: Performs an ssi with some number of retries.  Retries continue either
                    112: until the result is ok or until the retry count supplied by the
                    113: caller is exhausted.  
                    114: 
                    115: Inputs:
1.648     raeburn   116: 
                    117: =over 4
                    118: 
1.643     foxr      119: resource   - Identifies the resource to insert.
1.648     raeburn   120: 
1.643     foxr      121: retries    - Count of the number of retries allowed.
1.648     raeburn   122: 
1.643     foxr      123: form       - Hash that identifies the rendering options.
                    124: 
1.648     raeburn   125: =back
                    126: 
                    127: Returns:
                    128: 
                    129: =over 4
                    130: 
1.643     foxr      131: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   132: 
1.643     foxr      133: response   - The response from the last attempt (which may or may not have been successful.
                    134: 
1.648     raeburn   135: =back
                    136: 
                    137: =back
                    138: 
1.643     foxr      139: =cut
                    140: 
                    141: sub ssi_with_retries {
                    142:     my ($resource, $retries, %form) = @_;
                    143: 
                    144: 
                    145:     my $ok = 0;			# True if we got a good response.
                    146:     my $content;
                    147:     my $response;
                    148: 
                    149:     # Try to get the ssi done. within the retries count:
                    150: 
                    151:     do {
                    152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    153: 	$ok      = $response->is_success;
1.650     www       154:         if (!$ok) {
                    155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    156:         }
1.643     foxr      157: 	$retries--;
                    158:     } while (!$ok && ($retries > 0));
                    159: 
                    160:     if (!$ok) {
                    161: 	$content = '';		# On error return an empty content.
                    162:     }
                    163:     return ($content, $response);
                    164: 
                    165: }
                    166: 
                    167: 
                    168: 
1.20      www       169: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  170: my %language;
1.124     www       171: my %supported_language;
1.1048    foxr      172: my %latex_language;		# For choosing hyphenation in <transl..>
                    173: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  174: my %cprtag;
1.192     taceyjo1  175: my %scprtag;
1.351     www       176: my %fe; my %fd; my %fm;
1.41      ng        177: my %category_extensions;
1.12      harris41  178: 
1.46      matthew   179: # ---------------------------------------------- Thesaurus variables
1.144     matthew   180: #
                    181: # %Keywords:
                    182: #      A hash used by &keyword to determine if a word is considered a keyword.
                    183: # $thesaurus_db_file 
                    184: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   185: 
                    186: my %Keywords;
                    187: my $thesaurus_db_file;
                    188: 
1.144     matthew   189: #
                    190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    191: # thesaurus.tab, and filecategories.tab.
                    192: #
1.18      www       193: BEGIN {
1.46      matthew   194:     # Variable initialization
                    195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    196:     #
1.22      www       197:     unless ($readit) {
1.12      harris41  198: # ------------------------------------------------------------------- languages
                    199:     {
1.158     raeburn   200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    201:                                    '/language.tab';
1.1075.2.128  raeburn   202:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
1.1048    foxr      206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   207:                 $language{$key}=$val.' - '.$enc;
                    208:                 if ($sup) {
                    209:                     $supported_language{$key}=$sup;
                    210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
                    213: 		    $latex_language{$two} = $latex;
                    214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
1.1075.2.128  raeburn   223:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   251:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
1.1075.2.128  raeburn   265:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   270:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
1.1075.2.128  raeburn   280:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.1075.2.141.  .3(raebu  433:20):     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.141.  .3(raebu  448:20):         if (courseadv == 'condition') {
                    449:20):             if (document.getElementById('courseadv')) {
                    450:20):                 courseadv = document.getElementById('courseadv').value;
                    451:20):             }
                    452:20):         }
                    453:20):         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       454:         var title = 'Student_Browser';
1.74      www       455:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    456:         options += ',width=700,height=600';
                    457:         stdeditbrowser = open(url,title,options,'1');
                    458:         stdeditbrowser.focus();
                    459:     }
1.824     bisitz    460: // ]]>
1.74      www       461: </script>
                    462: ENDSTDBRW
                    463: }
1.42      matthew   464: 
1.1003    www       465: sub resourcebrowser_javascript {
                    466:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       467:    return (<<'ENDRESBRW');
1.1003    www       468: <script type="text/javascript" language="Javascript">
                    469: // <![CDATA[
                    470:     var reseditbrowser;
1.1004    www       471:     function openresbrowser(formname,reslink) {
1.1005    www       472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       473:         var title = 'Resource_Browser';
                    474:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       475:         options += ',width=700,height=500';
1.1004    www       476:         reseditbrowser = open(url,title,options,'1');
                    477:         reseditbrowser.focus();
1.1003    www       478:     }
                    479: // ]]>
                    480: </script>
1.1004    www       481: ENDRESBRW
1.1003    www       482: }
                    483: 
1.74      www       484: sub selectstudent_link {
1.1075.2.141.  .3(raebu  485:20):    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  489:    if ($env{'request.course.id'}) {  
1.302     albertel  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    492: 					'/'.$env{'request.course.sec'})) {
1.111     www       493: 	   return '';
                    494:        }
1.999     www       495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.141.  .3(raebu  496:20):        if ($courseadv eq 'only') {
                    497:20):            $callargs .= ",'',1,'$courseadv'";
                    498:20):        } elsif ($courseadv eq 'none') {
                    499:20):            $callargs .= ",'','','$courseadv'";
                    500:20):        } elsif ($courseadv eq 'condition') {
                    501:20):            $callargs .= ",'','','$courseadv'";
1.793     raeburn   502:        }
                    503:        return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    505:               &mt('Select User').'</a></span>';
1.74      www       506:    }
1.258     albertel  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       508:        $callargs .= ",'',1"; 
1.793     raeburn   509:        return '<span class="LC_nobreak">'.
                    510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    511:               &mt('Select User').'</a></span>';
1.111     www       512:    }
                    513:    return '';
1.91      www       514: }
                    515: 
1.1004    www       516: sub selectresource_link {
                    517:    my ($form,$reslink,$arg)=@_;
                    518:    
                    519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    521:    unless ($env{'request.course.id'}) { return $arg; }
                    522:    return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    524:               $arg.'</a></span>';
                    525: }
                    526: 
                    527: 
                    528: 
1.653     raeburn   529: sub authorbrowser_javascript {
                    530:     return <<"ENDAUTHORBRW";
1.776     bisitz    531: <script type="text/javascript" language="JavaScript">
1.824     bisitz    532: // <![CDATA[
1.653     raeburn   533: var stdeditbrowser;
                    534: 
                    535: function openauthorbrowser(formname,udom) {
                    536:     var url = '/adm/pickauthor?';
                    537:     url += 'form='+formname+'&roledom='+udom;
                    538:     var title = 'Author_Browser';
                    539:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    540:     options += ',width=700,height=600';
                    541:     stdeditbrowser = open(url,title,options,'1');
                    542:     stdeditbrowser.focus();
                    543: }
                    544: 
1.824     bisitz    545: // ]]>
1.653     raeburn   546: </script>
                    547: ENDAUTHORBRW
                    548: }
                    549: 
1.91      www       550: sub coursebrowser_javascript {
1.1075.2.31  raeburn   551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   552:         $credits_element,$instcode) = @_;
1.932     raeburn   553:     my $wintitle = 'Course_Browser';
1.931     raeburn   554:     if ($crstype eq 'Community') {
1.932     raeburn   555:         $wintitle = 'Community_Browser';
1.909     raeburn   556:     }
1.876     raeburn   557:     my $id_functions = &javascript_index_functions();
                    558:     my $output = '
1.776     bisitz    559: <script type="text/javascript" language="JavaScript">
1.824     bisitz    560: // <![CDATA[
1.468     raeburn   561:     var stdeditbrowser;'."\n";
1.876     raeburn   562: 
                    563:     $output .= <<"ENDSTDBRW";
1.909     raeburn   564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       565:         var url = '/adm/pickcourse?';
1.895     raeburn   566:         var formid = getFormIdByName(formname);
1.876     raeburn   567:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  568:         if (domainfilter != null) {
                    569:            if (domainfilter != '') {
                    570:                url += 'domainfilter='+domainfilter+'&';
                    571: 	   }
                    572:         }
1.91      www       573:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  574: 	                            '&cdomelement='+udom+
                    575:                                     '&cnameelement='+desc;
1.468     raeburn   576:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   577:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   578:                 url += '&roleelement='+extra_element;
                    579:                 if (domainfilter == null || domainfilter == '') {
                    580:                     url += '&domainfilter='+extra_element;
                    581:                 }
1.234     raeburn   582:             }
1.468     raeburn   583:             else {
                    584:                 if (formname == 'portform') {
                    585:                     url += '&setroles='+extra_element;
1.800     raeburn   586:                 } else {
                    587:                     if (formname == 'rules') {
                    588:                         url += '&fixeddom='+extra_element; 
                    589:                     }
1.468     raeburn   590:                 }
                    591:             }     
1.230     raeburn   592:         }
1.909     raeburn   593:         if (type != null && type != '') {
                    594:             url += '&type='+type;
                    595:         }
                    596:         if (type_elem != null && type_elem != '') {
                    597:             url += '&typeelement='+type_elem;
                    598:         }
1.872     raeburn   599:         if (formname == 'ccrs') {
                    600:             var ownername = document.forms[formid].ccuname.value;
                    601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   602:             url += '&cloner='+ownername+':'+ownerdom;
                    603:             if (type == 'Course') {
                    604:                 url += '&crscode='+document.forms[formid].crscode.value;
                    605:             }
1.1075.2.95  raeburn   606:         }
                    607:         if (formname == 'requestcrs') {
                    608:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   609:         }
1.293     raeburn   610:         if (multflag !=null && multflag != '') {
                    611:             url += '&multiple='+multflag;
                    612:         }
1.909     raeburn   613:         var title = '$wintitle';
1.91      www       614:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    615:         options += ',width=700,height=600';
                    616:         stdeditbrowser = open(url,title,options,'1');
                    617:         stdeditbrowser.focus();
                    618:     }
1.876     raeburn   619: $id_functions
                    620: ENDSTDBRW
1.1075.2.31  raeburn   621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    623:                                       $credits_element);
1.876     raeburn   624:     }
                    625:     $output .= '
                    626: // ]]>
                    627: </script>';
                    628:     return $output;
                    629: }
                    630: 
                    631: sub javascript_index_functions {
                    632:     return <<"ENDJS";
                    633: 
                    634: function getFormIdByName(formname) {
                    635:     for (var i=0;i<document.forms.length;i++) {
                    636:         if (document.forms[i].name == formname) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
                    642: 
                    643: function getIndexByName(formid,item) {
                    644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    645:         if (document.forms[formid].elements[i].name == item) {
                    646:             return i;
                    647:         }
                    648:     }
                    649:     return -1;
                    650: }
1.468     raeburn   651: 
1.876     raeburn   652: function getDomainFromSelectbox(formname,udom) {
                    653:     var userdom;
                    654:     var formid = getFormIdByName(formname);
                    655:     if (formid > -1) {
                    656:         var domid = getIndexByName(formid,udom);
                    657:         if (domid > -1) {
                    658:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    660:             }
                    661:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    662:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   663:             }
                    664:         }
                    665:     }
1.876     raeburn   666:     return userdom;
                    667: }
                    668: 
                    669: ENDJS
1.468     raeburn   670: 
1.876     raeburn   671: }
                    672: 
1.1017    raeburn   673: sub javascript_array_indexof {
1.1018    raeburn   674:     return <<ENDJS;
1.1017    raeburn   675: <script type="text/javascript" language="JavaScript">
                    676: // <![CDATA[
                    677: 
                    678: if (!Array.prototype.indexOf) {
                    679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    680:         "use strict";
                    681:         if (this === void 0 || this === null) {
                    682:             throw new TypeError();
                    683:         }
                    684:         var t = Object(this);
                    685:         var len = t.length >>> 0;
                    686:         if (len === 0) {
                    687:             return -1;
                    688:         }
                    689:         var n = 0;
                    690:         if (arguments.length > 0) {
                    691:             n = Number(arguments[1]);
                    692:             if (n !== n) { // shortcut for verifying if it's NaN
                    693:                 n = 0;
                    694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    696:             }
                    697:         }
                    698:         if (n >= len) {
                    699:             return -1;
                    700:         }
                    701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    702:         for (; k < len; k++) {
                    703:             if (k in t && t[k] === searchElement) {
                    704:                 return k;
                    705:             }
                    706:         }
                    707:         return -1;
                    708:     }
                    709: }
                    710: 
                    711: // ]]>
                    712: </script>
                    713: 
                    714: ENDJS
                    715: 
                    716: }
                    717: 
1.876     raeburn   718: sub userbrowser_javascript {
                    719:     my $id_functions = &javascript_index_functions();
                    720:     return <<"ENDUSERBRW";
                    721: 
1.888     raeburn   722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   723:     var url = '/adm/pickuser?';
                    724:     var userdom = getDomainFromSelectbox(formname,udom);
                    725:     if (userdom != null) {
                    726:        if (userdom != '') {
                    727:            url += 'srchdom='+userdom+'&';
                    728:        }
                    729:     }
                    730:     url += 'form=' + formname + '&unameelement='+uname+
                    731:                                 '&udomelement='+udom+
                    732:                                 '&ulastelement='+ulast+
                    733:                                 '&ufirstelement='+ufirst+
                    734:                                 '&uemailelement='+uemail+
1.881     raeburn   735:                                 '&hideudomelement='+hideudom+
                    736:                                 '&coursedom='+crsdom;
1.888     raeburn   737:     if ((caller != null) && (caller != undefined)) {
                    738:         url += '&caller='+caller;
                    739:     }
1.876     raeburn   740:     var title = 'User_Browser';
                    741:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    742:     options += ',width=700,height=600';
                    743:     var stdeditbrowser = open(url,title,options,'1');
                    744:     stdeditbrowser.focus();
                    745: }
                    746: 
1.888     raeburn   747: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   748:     var formid = getFormIdByName(formname);
                    749:     if (formid > -1) {
1.888     raeburn   750:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   751:         var domid = getIndexByName(formid,udom);
                    752:         var hidedomid = getIndexByName(formid,origdom);
                    753:         if (hidedomid > -1) {
                    754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   755:             var unameval = document.forms[formid].elements[unameid].value;
                    756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    757:                 if (domid > -1) {
                    758:                     var slct = document.forms[formid].elements[domid];
                    759:                     if (slct.type == 'select-one') {
                    760:                         var i;
                    761:                         for (i=0;i<slct.length;i++) {
                    762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    763:                         }
                    764:                     }
                    765:                     if (slct.type == 'hidden') {
                    766:                         slct.value = fixeddom;
1.876     raeburn   767:                     }
                    768:                 }
1.468     raeburn   769:             }
                    770:         }
                    771:     }
1.876     raeburn   772:     return;
                    773: }
                    774: 
                    775: $id_functions
                    776: ENDUSERBRW
1.468     raeburn   777: }
                    778: 
                    779: sub setsec_javascript {
1.1075.2.31  raeburn   780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    782:         $communityrolestr);
                    783:     if ($role_element ne '') {
                    784:         my @allroles = ('st','ta','ep','in','ad');
                    785:         foreach my $crstype ('Course','Community') {
                    786:             if ($crstype eq 'Community') {
                    787:                 foreach my $role (@allroles) {
                    788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    789:                 }
                    790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    791:             } else {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    796:             }
                    797:         }
                    798:         $rolestr = '"'.join('","',@allroles).'"';
                    799:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    801:     }
1.468     raeburn   802:     my $setsections = qq|
                    803: function setSect(sectionlist) {
1.629     raeburn   804:     var sectionsArray = new Array();
                    805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    806:         sectionsArray = sectionlist.split(",");
                    807:     }
1.468     raeburn   808:     var numSections = sectionsArray.length;
                    809:     document.$formname.$sec_element.length = 0;
                    810:     if (numSections == 0) {
                    811:         document.$formname.$sec_element.multiple=false;
                    812:         document.$formname.$sec_element.size=1;
                    813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    814:     } else {
                    815:         if (numSections == 1) {
                    816:             document.$formname.$sec_element.multiple=false;
                    817:             document.$formname.$sec_element.size=1;
                    818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    821:         } else {
                    822:             for (var i=0; i<numSections; i++) {
                    823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    824:             }
                    825:             document.$formname.$sec_element.multiple=true
                    826:             if (numSections < 3) {
                    827:                 document.$formname.$sec_element.size=numSections;
                    828:             } else {
                    829:                 document.$formname.$sec_element.size=3;
                    830:             }
                    831:             document.$formname.$sec_element.options[0].selected = false
                    832:         }
                    833:     }
1.91      www       834: }
1.905     raeburn   835: 
                    836: function setRole(crstype) {
1.468     raeburn   837: |;
1.905     raeburn   838:     if ($role_element eq '') {
                    839:         $setsections .= '    return;
                    840: }
                    841: ';
                    842:     } else {
                    843:         $setsections .= qq|
                    844:     var elementLength = document.$formname.$role_element.length;
                    845:     var allroles = Array($rolestr);
                    846:     var courserolenames = Array($courserolestr);
                    847:     var communityrolenames = Array($communityrolestr);
                    848:     if (elementLength != undefined) {
                    849:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    850:             if (crstype == 'Course') {
                    851:                 return;
                    852:             } else {
                    853:                 allroles[5] = 'co';
                    854:                 for (var i=0; i<6; i++) {
                    855:                     document.$formname.$role_element.options[i].value = allroles[i];
                    856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    857:                 }
                    858:             }
                    859:         } else {
                    860:             if (crstype == 'Community') {
                    861:                 return;
                    862:             } else {
                    863:                 allroles[5] = 'cc';
                    864:                 for (var i=0; i<6; i++) {
                    865:                     document.$formname.$role_element.options[i].value = allroles[i];
                    866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    867:                 }
                    868:             }
                    869:         }
                    870:     }
                    871:     return;
                    872: }
                    873: |;
                    874:     }
1.1075.2.31  raeburn   875:     if ($credits_element) {
                    876:         $setsections .= qq|
                    877: function setCredits(defaultcredits) {
                    878:     document.$formname.$credits_element.value = defaultcredits;
                    879:     return;
                    880: }
                    881: |;
                    882:     }
1.468     raeburn   883:     return $setsections;
                    884: }
                    885: 
1.91      www       886: sub selectcourse_link {
1.909     raeburn   887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    888:        $typeelement) = @_;
                    889:    my $type = $selecttype;
1.871     raeburn   890:    my $linktext = &mt('Select Course');
                    891:    if ($selecttype eq 'Community') {
1.909     raeburn   892:        $linktext = &mt('Select Community');
1.906     raeburn   893:    } elsif ($selecttype eq 'Course/Community') {
                    894:        $linktext = &mt('Select Course/Community');
1.909     raeburn   895:        $type = '';
1.1019    raeburn   896:    } elsif ($selecttype eq 'Select') {
                    897:        $linktext = &mt('Select');
                    898:        $type = '';
1.871     raeburn   899:    }
1.787     bisitz    900:    return '<span class="LC_nobreak">'
                    901:          ."<a href='"
                    902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   905:          ."'>".$linktext.'</a>'
1.787     bisitz    906:          .'</span>';
1.74      www       907: }
1.42      matthew   908: 
1.653     raeburn   909: sub selectauthor_link {
                    910:    my ($form,$udom)=@_;
                    911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    912:           &mt('Select Author').'</a>';
                    913: }
                    914: 
1.876     raeburn   915: sub selectuser_link {
1.881     raeburn   916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   917:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   920:            ');">'.$linktext.'</a>';
1.876     raeburn   921: }
                    922: 
1.273     raeburn   923: sub check_uncheck_jscript {
                    924:     my $jscript = <<"ENDSCRT";
                    925: function checkAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   928:             if (!field[i].disabled) {
                    929:                 field[i].checked = true;
                    930:             }
1.273     raeburn   931:         }
                    932:     } else {
1.1075.2.14  raeburn   933:         if (!field.disabled) {
                    934:             field.checked = true;
                    935:         }
1.273     raeburn   936:     }
                    937: }
                    938:  
                    939: function uncheckAll(field) {
                    940:     if (field.length > 0) {
                    941:         for (i = 0; i < field.length; i++) {
                    942:             field[i].checked = false ;
1.543     albertel  943:         }
                    944:     } else {
1.273     raeburn   945:         field.checked = false ;
                    946:     }
                    947: }
                    948: ENDSCRT
                    949:     return $jscript;
                    950: }
                    951: 
1.656     www       952: sub select_timezone {
1.1075.2.115  raeburn   953:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    954:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   955:    if ($includeempty) {
                    956:        $output .= '<option value=""';
                    957:        if (($selected eq '') || ($selected eq 'local')) {
                    958:            $output .= ' selected="selected" ';
                    959:        }
                    960:        $output .= '> </option>';
                    961:    }
1.657     raeburn   962:    my @timezones = DateTime::TimeZone->all_names;
                    963:    foreach my $tzone (@timezones) {
                    964:        $output.= '<option value="'.$tzone.'"';
                    965:        if ($tzone eq $selected) {
                    966:            $output.=' selected="selected"';
                    967:        }
                    968:        $output.=">$tzone</option>\n";
1.656     www       969:    }
                    970:    $output.="</select>";
                    971:    return $output;
                    972: }
1.273     raeburn   973: 
1.687     raeburn   974: sub select_datelocale {
1.1075.2.115  raeburn   975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   977:     if ($includeempty) {
                    978:         $output .= '<option value=""';
                    979:         if ($selected eq '') {
                    980:             $output .= ' selected="selected" ';
                    981:         }
                    982:         $output .= '> </option>';
                    983:     }
1.1075.2.102  raeburn   984:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   985:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   986:     my @locales = DateTime::Locale->ids();
                    987:     foreach my $id (@locales) {
                    988:         if ($id ne '') {
                    989:             my ($en_terr,$native_terr);
                    990:             my $loc = DateTime::Locale->load($id);
                    991:             if (ref($loc)) {
                    992:                 $en_terr = $loc->name();
                    993:                 $native_terr = $loc->native_name();
1.687     raeburn   994:                 if (grep(/^en$/,@languages) || !@languages) {
                    995:                     if ($en_terr ne '') {
                    996:                         $locale_names{$id} = '('.$en_terr.')';
                    997:                     } elsif ($native_terr ne '') {
                    998:                         $locale_names{$id} = $native_terr;
                    999:                     }
                   1000:                 } else {
                   1001:                     if ($native_terr ne '') {
                   1002:                         $locale_names{$id} = $native_terr.' ';
                   1003:                     } elsif ($en_terr ne '') {
                   1004:                         $locale_names{$id} = '('.$en_terr.')';
                   1005:                     }
                   1006:                 }
1.1075.2.94  raeburn  1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1008:                 push(@possibles,$id);
1.687     raeburn  1009:             }
                   1010:         }
                   1011:     }
                   1012:     foreach my $item (sort(@possibles)) {
                   1013:         $output.= '<option value="'.$item.'"';
                   1014:         if ($item eq $selected) {
                   1015:             $output.=' selected="selected"';
                   1016:         }
                   1017:         $output.=">$item";
                   1018:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1019:             $output.='  '.$locale_names{$item};
1.687     raeburn  1020:         }
                   1021:         $output.="</option>\n";
                   1022:     }
                   1023:     $output.="</select>";
                   1024:     return $output;
                   1025: }
                   1026: 
1.792     raeburn  1027: sub select_language {
1.1075.2.115  raeburn  1028:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1029:     my %langchoices;
                   1030:     if ($includeempty) {
1.1075.2.32  raeburn  1031:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1032:     }
                   1033:     foreach my $id (&languageids()) {
                   1034:         my $code = &supportedlanguagecode($id);
                   1035:         if ($code) {
                   1036:             $langchoices{$code} = &plainlanguagedescription($id);
                   1037:         }
                   1038:     }
1.1075.2.32  raeburn  1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1041: }
                   1042: 
1.42      matthew  1043: =pod
1.36      matthew  1044: 
1.648     raeburn  1045: =item * &linked_select_forms(...)
1.36      matthew  1046: 
                   1047: linked_select_forms returns a string containing a <script></script> block
                   1048: and html for two <select> menus.  The select menus will be linked in that
                   1049: changing the value of the first menu will result in new values being placed
                   1050: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1051: order unless a defined order is provided.
1.36      matthew  1052: 
                   1053: linked_select_forms takes the following ordered inputs:
                   1054: 
                   1055: =over 4
                   1056: 
1.112     bowersj2 1057: =item * $formname, the name of the <form> tag
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstdefault, the default value for the first menu
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1066: 
1.112     bowersj2 1067: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1068: 
1.609     raeburn  1069: =item * $menuorder, the order of values in the first menu
                   1070: 
1.1075.2.31  raeburn  1071: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1072:         event for the first <select> tag
                   1073: 
                   1074: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1075:         event for the second <select> tag
                   1076: 
1.41      ng       1077: =back 
                   1078: 
1.36      matthew  1079: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1081: values for the first select menu.  The text that coincides with the 
1.41      ng       1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1083: and text for the second menu are given in the hash pointed to by 
                   1084: $menu{$choice1}->{'select2'}.  
                   1085: 
1.112     bowersj2 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1087:                        default => "B3",
                   1088:                        select2 => { 
                   1089:                            B1 => "Choice B1",
                   1090:                            B2 => "Choice B2",
                   1091:                            B3 => "Choice B3",
                   1092:                            B4 => "Choice B4"
1.609     raeburn  1093:                            },
                   1094:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1095:                    },
                   1096:                A2 => { text =>"Choice A2" ,
                   1097:                        default => "C2",
                   1098:                        select2 => { 
                   1099:                            C1 => "Choice C1",
                   1100:                            C2 => "Choice C2",
                   1101:                            C3 => "Choice C3"
1.609     raeburn  1102:                            },
                   1103:                        order => ['C2','C1','C3'],
1.112     bowersj2 1104:                    },
                   1105:                A3 => { text =>"Choice A3" ,
                   1106:                        default => "D6",
                   1107:                        select2 => { 
                   1108:                            D1 => "Choice D1",
                   1109:                            D2 => "Choice D2",
                   1110:                            D3 => "Choice D3",
                   1111:                            D4 => "Choice D4",
                   1112:                            D5 => "Choice D5",
                   1113:                            D6 => "Choice D6",
                   1114:                            D7 => "Choice D7"
1.609     raeburn  1115:                            },
                   1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1117:                    }
                   1118:                );
1.36      matthew  1119: 
                   1120: =cut
                   1121: 
                   1122: sub linked_select_forms {
                   1123:     my ($formname,
                   1124:         $middletext,
                   1125:         $firstdefault,
                   1126:         $firstselectname,
                   1127:         $secondselectname, 
1.609     raeburn  1128:         $hashref,
                   1129:         $menuorder,
1.1075.2.31  raeburn  1130:         $onchangefirst,
                   1131:         $onchangesecond
1.36      matthew  1132:         ) = @_;
                   1133:     my $second = "document.$formname.$secondselectname";
                   1134:     my $first = "document.$formname.$firstselectname";
                   1135:     # output the javascript to do the changing
                   1136:     my $result = '';
1.776     bisitz   1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1138:     $result.="// <![CDATA[\n";
1.36      matthew  1139:     $result.="var select2data = new Object();\n";
                   1140:     $" = '","';
                   1141:     my $debug = '';
                   1142:     foreach my $s1 (sort(keys(%$hashref))) {
                   1143:         $result.="select2data.d_$s1 = new Object();\n";        
                   1144:         $result.="select2data.d_$s1.def = new String('".
                   1145:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1146:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1149:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1150:         }
1.36      matthew  1151:         $result.="\"@s2values\");\n";
                   1152:         $result.="select2data.d_$s1.texts = new Array(";        
                   1153:         my @s2texts;
                   1154:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1156:         }
                   1157:         $result.="\"@s2texts\");\n";
                   1158:     }
                   1159:     $"=' ';
                   1160:     $result.= <<"END";
                   1161: 
                   1162: function select1_changed() {
                   1163:     // Determine new choice
                   1164:     var newvalue = "d_" + $first.value;
                   1165:     // update select2
                   1166:     var values     = select2data[newvalue].values;
                   1167:     var texts      = select2data[newvalue].texts;
                   1168:     var select2def = select2data[newvalue].def;
                   1169:     var i;
                   1170:     // out with the old
                   1171:     for (i = 0; i < $second.options.length; i++) {
                   1172:         $second.options[i] = null;
                   1173:     }
                   1174:     // in with the nuclear
                   1175:     for (i=0;i<values.length; i++) {
                   1176:         $second.options[i] = new Option(values[i]);
1.143     matthew  1177:         $second.options[i].value = values[i];
1.36      matthew  1178:         $second.options[i].text = texts[i];
                   1179:         if (values[i] == select2def) {
                   1180:             $second.options[i].selected = true;
                   1181:         }
                   1182:     }
                   1183: }
1.824     bisitz   1184: // ]]>
1.36      matthew  1185: </script>
                   1186: END
                   1187:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1189:     my @order = sort(keys(%{$hashref}));
                   1190:     if (ref($menuorder) eq 'ARRAY') {
                   1191:         @order = @{$menuorder};
                   1192:     }
                   1193:     foreach my $value (@order) {
1.36      matthew  1194:         $result.="    <option value=\"$value\" ";
1.253     albertel 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1197:     }
                   1198:     $result .= "</select>\n";
                   1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1200:     $result .= $middletext;
1.1075.2.31  raeburn  1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1202:     if ($onchangesecond) {
                   1203:         $result .= ' onchange="'.$onchangesecond.'"';
                   1204:     }
                   1205:     $result .= ">\n";
1.36      matthew  1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1207:     
                   1208:     my @secondorder = sort(keys(%select2));
                   1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1211:     }
                   1212:     foreach my $value (@secondorder) {
1.36      matthew  1213:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1215:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1216:     }
                   1217:     $result .= "</select>\n";
                   1218:     #    return $debug;
                   1219:     return $result;
                   1220: }   #  end of sub linked_select_forms {
                   1221: 
1.45      matthew  1222: =pod
1.44      bowersj2 1223: 
1.973     raeburn  1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1225: 
1.112     bowersj2 1226: Returns a string corresponding to an HTML link to the given help
                   1227: $topic, where $topic corresponds to the name of a .tex file in
                   1228: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1229: spaces. 
                   1230: 
                   1231: $text will optionally be linked to the same topic, allowing you to
                   1232: link text in addition to the graphic. If you do not want to link
                   1233: text, but wish to specify one of the later parameters, pass an
                   1234: empty string. 
                   1235: 
                   1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1237: the link will not open a new window. If false, the link will open
                   1238: a new window using Javascript. (Default is false.) 
                   1239: 
                   1240: $width and $height are optional numerical parameters that will
                   1241: override the width and height of the popped up window, which may
1.973     raeburn  1242: be useful for certain help topics with big pictures included.
                   1243: 
                   1244: $imgid is the id of the img tag used for the help icon. This may be
                   1245: used in a javascript call to switch the image src.  See 
                   1246: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1247: 
                   1248: =cut
                   1249: 
                   1250: sub help_open_topic {
1.973     raeburn  1251:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1252:     $text = "" if (not defined $text);
1.44      bowersj2 1253:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1254:     $width = 500 if (not defined $width);
1.44      bowersj2 1255:     $height = 400 if (not defined $height);
                   1256:     my $filename = $topic;
                   1257:     $filename =~ s/ /_/g;
                   1258: 
1.48      bowersj2 1259:     my $template = "";
                   1260:     my $link;
1.572     banghart 1261:     
1.159     www      1262:     $topic=~s/\W/\_/g;
1.44      bowersj2 1263: 
1.572     banghart 1264:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1265:         if ($env{'browser.mobile'}) {
                   1266: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1267:         } else {
                   1268:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1269:         }
1.1037    www      1270:     } elsif ($stayOnPage eq 'popup') {
                   1271:         $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 1272:     } else {
1.48      bowersj2 1273: 	$link = "/adm/help/${filename}.hlp";
                   1274:     }
                   1275: 
                   1276:     # Add the text
1.755     neumanie 1277:     if ($text ne "") {	
1.763     bisitz   1278: 	$template.='<span class="LC_help_open_topic">'
                   1279:                   .'<a target="_top" href="'.$link.'">'
                   1280:                   .$text.'</a>';
1.48      bowersj2 1281:     }
                   1282: 
1.763     bisitz   1283:     # (Always) Add the graphic
1.179     matthew  1284:     my $title = &mt('Online Help');
1.667     raeburn  1285:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1286:     if ($imgid ne '') {
                   1287:         $imgid = ' id="'.$imgid.'"';
                   1288:     }
1.763     bisitz   1289:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1290:               .'<img src="'.$helpicon.'" border="0"'
                   1291:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1292:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1293:               .' /></a>';
                   1294:     if ($text ne "") {	
                   1295:         $template.='</span>';
                   1296:     }
1.44      bowersj2 1297:     return $template;
                   1298: 
1.106     bowersj2 1299: }
                   1300: 
                   1301: # This is a quicky function for Latex cheatsheet editing, since it 
                   1302: # appears in at least four places
                   1303: sub helpLatexCheatsheet {
1.1037    www      1304:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1305:     my $out;
1.106     bowersj2 1306:     my $addOther = '';
1.732     raeburn  1307:     if ($topic) {
1.1037    www      1308: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1309:     }
                   1310:     $out = '<span>' # Start cheatsheet
                   1311: 	  .$addOther
                   1312:           .'<span>'
1.1037    www      1313: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span> <span>'
1.1037    www      1315: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1316: 	  .'</span>';
1.732     raeburn  1317:     unless ($not_author) {
1.763     bisitz   1318:         $out .= ' <span>'
1.1037    www      1319: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320: 	       .'</span> <span>'
1.1075.2.78  raeburn  1321:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1322:                .'</span>';
1.732     raeburn  1323:     }
1.763     bisitz   1324:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1325:     return $out;
1.172     www      1326: }
                   1327: 
1.430     albertel 1328: sub general_help {
                   1329:     my $helptopic='Student_Intro';
                   1330:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1331: 	$helptopic='Authoring_Intro';
1.907     raeburn  1332:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1333: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1334:     } elsif ($env{'request.role'}=~/^dc/) {
                   1335:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1336:     }
                   1337:     return $helptopic;
                   1338: }
                   1339: 
                   1340: sub update_help_link {
                   1341:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1342:     my $origurl = $ENV{'REQUEST_URI'};
                   1343:     $origurl=~s|^/~|/priv/|;
                   1344:     my $timestamp = time;
                   1345:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1346:         $$datum = &escape($$datum);
                   1347:     }
                   1348: 
                   1349:     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";
                   1350:     my $output .= <<"ENDOUTPUT";
                   1351: <script type="text/javascript">
1.824     bisitz   1352: // <![CDATA[
1.430     albertel 1353: banner_link = '$banner_link';
1.824     bisitz   1354: // ]]>
1.430     albertel 1355: </script>
                   1356: ENDOUTPUT
                   1357:     return $output;
                   1358: }
                   1359: 
                   1360: # now just updates the help link and generates a blue icon
1.193     raeburn  1361: sub help_open_menu {
1.430     albertel 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1363: 	= @_;    
1.949     droeschl 1364:     $stayOnPage = 1;
1.430     albertel 1365:     my $output;
                   1366:     if ($component_help) {
                   1367: 	if (!$text) {
                   1368: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1369: 				       $width,$height);
                   1370: 	} else {
                   1371: 	    my $help_text;
                   1372: 	    $help_text=&unescape($topic);
                   1373: 	    $output='<table><tr><td>'.
                   1374: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1375: 				 $width,$height).'</td></tr></table>';
                   1376: 	}
                   1377:     }
                   1378:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1379:     return $output.$banner_link;
                   1380: }
                   1381: 
                   1382: sub top_nav_help {
                   1383:     my ($text) = @_;
1.436     albertel 1384:     $text = &mt($text);
1.1075.2.60  raeburn  1385:     my $stay_on_page;
                   1386:     unless ($env{'environment.remote'} eq 'on') {
                   1387:         $stay_on_page = 1;
                   1388:     }
1.1075.2.61  raeburn  1389:     my ($link,$banner_link);
                   1390:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1391:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1392: 	                         : "javascript:helpMenu('open')";
                   1393:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1394:     }
1.201     raeburn  1395:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1396:     if ($link) {
                   1397:         return <<"END";
1.436     albertel 1398: $banner_link
1.1075.2.56  raeburn  1399: <a href="$link" title="$title">$text</a>
1.436     albertel 1400: END
1.1075.2.61  raeburn  1401:     } else {
                   1402:         return '&nbsp;'.$text.'&nbsp;';
                   1403:     }
1.436     albertel 1404: }
                   1405: 
                   1406: sub help_menu_js {
1.1075.2.52  raeburn  1407:     my ($httphost) = @_;
1.949     droeschl 1408:     my $stayOnPage = 1;
1.436     albertel 1409:     my $width = 620;
                   1410:     my $height = 600;
1.430     albertel 1411:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1412:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1413:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1414:     my $start_page =
                   1415:         &Apache::loncommon::start_page('Help Menu', undef,
                   1416: 				       {'frameset'    => 1,
                   1417: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1418:                                         'use_absolute' => $httphost,
1.331     albertel 1419: 					'add_entries' => {
                   1420: 					    'border' => '0',
1.579     raeburn  1421: 					    'rows'   => "110,*",},});
1.331     albertel 1422:     my $end_page =
                   1423:         &Apache::loncommon::end_page({'frameset' => 1,
                   1424: 				      'js_ready' => 1,});
                   1425: 
1.436     albertel 1426:     my $template .= <<"ENDTEMPLATE";
                   1427: <script type="text/javascript">
1.877     bisitz   1428: // <![CDATA[
1.253     albertel 1429: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1430: var banner_link = '';
1.243     raeburn  1431: function helpMenu(target) {
                   1432:     var caller = this;
                   1433:     if (target == 'open') {
                   1434:         var newWindow = null;
                   1435:         try {
1.262     albertel 1436:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1437:         }
                   1438:         catch(error) {
                   1439:             writeHelp(caller);
                   1440:             return;
                   1441:         }
                   1442:         if (newWindow) {
                   1443:             caller = newWindow;
                   1444:         }
1.193     raeburn  1445:     }
1.243     raeburn  1446:     writeHelp(caller);
                   1447:     return;
                   1448: }
                   1449: function writeHelp(caller) {
1.1075.2.61  raeburn  1450:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1451:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1452:     caller.document.close();
                   1453:     caller.focus();
1.193     raeburn  1454: }
1.877     bisitz   1455: // END LON-CAPA Internal -->
1.253     albertel 1456: // ]]>
1.436     albertel 1457: </script>
1.193     raeburn  1458: ENDTEMPLATE
                   1459:     return $template;
                   1460: }
                   1461: 
1.172     www      1462: sub help_open_bug {
                   1463:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1464:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1465:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1466:     $text = "" if (not defined $text);
                   1467: 	$stayOnPage=1;
1.184     albertel 1468:     $width = 600 if (not defined $width);
                   1469:     $height = 600 if (not defined $height);
1.172     www      1470: 
                   1471:     $topic=~s/\W+/\+/g;
                   1472:     my $link='';
                   1473:     my $template='';
1.379     albertel 1474:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1475: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1476:     if (!$stayOnPage)
                   1477:     {
                   1478: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1479:     }
                   1480:     else
                   1481:     {
                   1482: 	$link = $url;
                   1483:     }
                   1484:     # Add the text
                   1485:     if ($text ne "")
                   1486:     {
                   1487: 	$template .= 
                   1488:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1489:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1490:     }
                   1491: 
                   1492:     # Add the graphic
1.179     matthew  1493:     my $title = &mt('Report a Bug');
1.215     albertel 1494:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1495:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1496:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1497: ENDTEMPLATE
                   1498:     if ($text ne '') { $template.='</td></tr></table>' };
                   1499:     return $template;
                   1500: 
                   1501: }
                   1502: 
                   1503: sub help_open_faq {
                   1504:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1505:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1506:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1507:     $text = "" if (not defined $text);
                   1508: 	$stayOnPage=1;
                   1509:     $width = 350 if (not defined $width);
                   1510:     $height = 400 if (not defined $height);
                   1511: 
                   1512:     $topic=~s/\W+/\+/g;
                   1513:     my $link='';
                   1514:     my $template='';
                   1515:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1516:     if (!$stayOnPage)
                   1517:     {
                   1518: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1519:     }
                   1520:     else
                   1521:     {
                   1522: 	$link = $url;
                   1523:     }
                   1524: 
                   1525:     # Add the text
                   1526:     if ($text ne "")
                   1527:     {
                   1528: 	$template .= 
1.173     www      1529:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1530:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1531:     }
                   1532: 
                   1533:     # Add the graphic
1.179     matthew  1534:     my $title = &mt('View the FAQ');
1.215     albertel 1535:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1536:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1537:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1538: ENDTEMPLATE
                   1539:     if ($text ne '') { $template.='</td></tr></table>' };
                   1540:     return $template;
                   1541: 
1.44      bowersj2 1542: }
1.37      matthew  1543: 
1.180     matthew  1544: ###############################################################
                   1545: ###############################################################
                   1546: 
1.45      matthew  1547: =pod
                   1548: 
1.648     raeburn  1549: =item * &change_content_javascript():
1.256     matthew  1550: 
                   1551: This and the next function allow you to create small sections of an
                   1552: otherwise static HTML page that you can update on the fly with
                   1553: Javascript, even in Netscape 4.
                   1554: 
                   1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1556: must be written to the HTML page once. It will prove the Javascript
                   1557: function "change(name, content)". Calling the change function with the
                   1558: name of the section 
                   1559: you want to update, matching the name passed to C<changable_area>, and
                   1560: the new content you want to put in there, will put the content into
                   1561: that area.
                   1562: 
                   1563: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1564: to contain room for the original contents. You need to "make space"
                   1565: for whatever changes you wish to make, and be B<sure> to check your
                   1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1567: it's adequate for updating a one-line status display, but little more.
                   1568: This script will set the space to 100% width, so you only need to
                   1569: worry about height in Netscape 4.
                   1570: 
                   1571: Modern browsers are much less limiting, and if you can commit to the
                   1572: user not using Netscape 4, this feature may be used freely with
                   1573: pretty much any HTML.
                   1574: 
                   1575: =cut
                   1576: 
                   1577: sub change_content_javascript {
                   1578:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1579:     if ($env{'browser.type'} eq 'netscape' &&
                   1580: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1581: 	return (<<NETSCAPE4);
                   1582: 	function change(name, content) {
                   1583: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1584: 	    doc.open();
                   1585: 	    doc.write(content);
                   1586: 	    doc.close();
                   1587: 	}
                   1588: NETSCAPE4
                   1589:     } else {
                   1590: 	# Otherwise, we need to use semi-standards-compliant code
                   1591: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1592: 	# is really scary, and every useful browser supports it
                   1593: 	return (<<DOMBASED);
                   1594: 	function change(name, content) {
                   1595: 	    element = document.getElementById(name);
                   1596: 	    element.innerHTML = content;
                   1597: 	}
                   1598: DOMBASED
                   1599:     }
                   1600: }
                   1601: 
                   1602: =pod
                   1603: 
1.648     raeburn  1604: =item * &changable_area($name,$origContent):
1.256     matthew  1605: 
                   1606: This provides a "changable area" that can be modified on the fly via
                   1607: the Javascript code provided in C<change_content_javascript>. $name is
                   1608: the name you will use to reference the area later; do not repeat the
                   1609: same name on a given HTML page more then once. $origContent is what
                   1610: the area will originally contain, which can be left blank.
                   1611: 
                   1612: =cut
                   1613: 
                   1614: sub changable_area {
                   1615:     my ($name, $origContent) = @_;
                   1616: 
1.258     albertel 1617:     if ($env{'browser.type'} eq 'netscape' &&
                   1618: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1619: 	# If this is netscape 4, we need to use the Layer tag
                   1620: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1621:     } else {
                   1622: 	return "<span id='$name'>$origContent</span>";
                   1623:     }
                   1624: }
                   1625: 
                   1626: =pod
                   1627: 
1.648     raeburn  1628: =item * &viewport_geometry_js 
1.590     raeburn  1629: 
                   1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1631: 
                   1632: =cut
                   1633: 
                   1634: 
                   1635: sub viewport_geometry_js { 
                   1636:     return <<"GEOMETRY";
                   1637: var Geometry = {};
                   1638: function init_geometry() {
                   1639:     if (Geometry.init) { return };
                   1640:     Geometry.init=1;
                   1641:     if (window.innerHeight) {
                   1642:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1643:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1644:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1645:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1646:     }
                   1647:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1648:         Geometry.getViewportHeight =
                   1649:             function() { return document.documentElement.clientHeight; };
                   1650:         Geometry.getViewportWidth =
                   1651:             function() { return document.documentElement.clientWidth; };
                   1652: 
                   1653:         Geometry.getHorizontalScroll =
                   1654:             function() { return document.documentElement.scrollLeft; };
                   1655:         Geometry.getVerticalScroll =
                   1656:             function() { return document.documentElement.scrollTop; };
                   1657:     }
                   1658:     else if (document.body.clientHeight) {
                   1659:         Geometry.getViewportHeight =
                   1660:             function() { return document.body.clientHeight; };
                   1661:         Geometry.getViewportWidth =
                   1662:             function() { return document.body.clientWidth; };
                   1663:         Geometry.getHorizontalScroll =
                   1664:             function() { return document.body.scrollLeft; };
                   1665:         Geometry.getVerticalScroll =
                   1666:             function() { return document.body.scrollTop; };
                   1667:     }
                   1668: }
                   1669: 
                   1670: GEOMETRY
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_size_js()
1.590     raeburn  1676: 
                   1677: 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. 
                   1678: 
                   1679: =cut
                   1680: 
                   1681: sub viewport_size_js {
                   1682:     my $geometry = &viewport_geometry_js();
                   1683:     return <<"DIMS";
                   1684: 
                   1685: $geometry
                   1686: 
                   1687: function getViewportDims(width,height) {
                   1688:     init_geometry();
                   1689:     width.value = Geometry.getViewportWidth();
                   1690:     height.value = Geometry.getViewportHeight();
                   1691:     return;
                   1692: }
                   1693: 
                   1694: DIMS
                   1695: }
                   1696: 
                   1697: =pod
                   1698: 
1.648     raeburn  1699: =item * &resize_textarea_js()
1.565     albertel 1700: 
                   1701: emits the needed javascript to resize a textarea to be as big as possible
                   1702: 
                   1703: creates a function resize_textrea that takes two IDs first should be
                   1704: the id of the element to resize, second should be the id of a div that
                   1705: surrounds everything that comes after the textarea, this routine needs
                   1706: to be attached to the <body> for the onload and onresize events.
                   1707: 
1.648     raeburn  1708: =back
1.565     albertel 1709: 
                   1710: =cut
                   1711: 
                   1712: sub resize_textarea_js {
1.590     raeburn  1713:     my $geometry = &viewport_geometry_js();
1.565     albertel 1714:     return <<"RESIZE";
                   1715:     <script type="text/javascript">
1.824     bisitz   1716: // <![CDATA[
1.590     raeburn  1717: $geometry
1.565     albertel 1718: 
1.588     albertel 1719: function getX(element) {
                   1720:     var x = 0;
                   1721:     while (element) {
                   1722: 	x += element.offsetLeft;
                   1723: 	element = element.offsetParent;
                   1724:     }
                   1725:     return x;
                   1726: }
                   1727: function getY(element) {
                   1728:     var y = 0;
                   1729:     while (element) {
                   1730: 	y += element.offsetTop;
                   1731: 	element = element.offsetParent;
                   1732:     }
                   1733:     return y;
                   1734: }
                   1735: 
                   1736: 
1.565     albertel 1737: function resize_textarea(textarea_id,bottom_id) {
                   1738:     init_geometry();
                   1739:     var textarea        = document.getElementById(textarea_id);
                   1740:     //alert(textarea);
                   1741: 
1.588     albertel 1742:     var textarea_top    = getY(textarea);
1.565     albertel 1743:     var textarea_height = textarea.offsetHeight;
                   1744:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1745:     var bottom_top      = getY(bottom);
1.565     albertel 1746:     var bottom_height   = bottom.offsetHeight;
                   1747:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1748:     var fudge           = 23;
1.565     albertel 1749:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1750:     if (new_height < 300) {
                   1751: 	new_height = 300;
                   1752:     }
                   1753:     textarea.style.height=new_height+'px';
                   1754: }
1.824     bisitz   1755: // ]]>
1.565     albertel 1756: </script>
                   1757: RESIZE
                   1758: 
                   1759: }
                   1760: 
1.1075.2.112  raeburn  1761: sub colorfuleditor_js {
                   1762:     return <<"COLORFULEDIT"
                   1763: <script type="text/javascript">
                   1764: // <![CDATA[>
                   1765:     function fold_box(curDepth, lastresource){
                   1766: 
                   1767:     // we need a list because there can be several blocks you need to fold in one tag
                   1768:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1769:     // but there is only one folding button per tag
                   1770:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1771: 
                   1772:         if(block.item(0).style.display == 'none'){
                   1773: 
                   1774:             foldbutton.value = '@{[&mt("Hide")]}';
                   1775:             for (i = 0; i < block.length; i++){
                   1776:                 block.item(i).style.display = '';
                   1777:             }
                   1778:         }else{
                   1779: 
                   1780:             foldbutton.value = '@{[&mt("Show")]}';
                   1781:             for (i = 0; i < block.length; i++){
                   1782:                 // block.item(i).style.visibility = 'collapse';
                   1783:                 block.item(i).style.display = 'none';
                   1784:             }
                   1785:         };
                   1786:         saveState(lastresource);
                   1787:     }
                   1788: 
                   1789:     function saveState (lastresource) {
                   1790: 
                   1791:         var tag_list = getTagList();
                   1792:         if(tag_list != null){
                   1793:             var timestamp = new Date().getTime();
                   1794:             var key = lastresource;
                   1795: 
                   1796:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1797:             // starting with timestamp
                   1798:             var value = timestamp+';';
                   1799: 
                   1800:             // building the list of key-value pairs
                   1801:             for(var i = 0; i < tag_list.length; i++){
                   1802:                 value += tag_list[i]+',';
                   1803:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1804:             }
                   1805: 
                   1806:             // only iterate whole storage if nothing to override
                   1807:             if(localStorage.getItem(key) == null){
                   1808: 
                   1809:                 // prevent storage from growing large
                   1810:                 if(localStorage.length > 50){
                   1811:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1812:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1813:                     var oldest_key;
                   1814: 
                   1815:                     for(var i = 1; i < localStorage.length; i++){
                   1816:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1817:                             oldest_key = localStorage.key(i);
                   1818:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1819:                         }
                   1820:                     }
                   1821:                     localStorage.removeItem(oldest_key);
                   1822:                 }
                   1823:             }
                   1824:             localStorage.setItem(key,value);
                   1825:         }
                   1826:     }
                   1827: 
                   1828:     // restore folding status of blocks (on page load)
                   1829:     function restoreState (lastresource) {
                   1830:         if(localStorage.getItem(lastresource) != null){
                   1831:             var key = lastresource;
                   1832:             var value = localStorage.getItem(key);
                   1833:             var regex_delTimestamp = /^\d+;/;
                   1834: 
                   1835:             value.replace(regex_delTimestamp, '');
                   1836: 
                   1837:             var valueArr = value.split(';');
                   1838:             var pairs;
                   1839:             var elements;
                   1840:             for (var i = 0; i < valueArr.length; i++){
                   1841:                 pairs = valueArr[i].split(',');
                   1842:                 elements = document.getElementsByName(pairs[0]);
                   1843: 
                   1844:                 for (var j = 0; j < elements.length; j++){
                   1845:                     elements[j].style.display = pairs[1];
                   1846:                     if (pairs[1] == "none"){
                   1847:                         var regex_id = /([_\\d]+)\$/;
                   1848:                         regex_id.exec(pairs[0]);
                   1849:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1850:                     }
                   1851:                 }
                   1852:             }
                   1853:         }
                   1854:     }
                   1855: 
                   1856:     function getTagList () {
                   1857: 
                   1858:         var stringToSearch = document.lonhomework.innerHTML;
                   1859: 
                   1860:         var ret = new Array();
                   1861:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1862:         var tag_list = stringToSearch.match(regex_findBlock);
                   1863: 
                   1864:         if(tag_list != null){
                   1865:             for(var i = 0; i < tag_list.length; i++){
                   1866:                 ret.push(tag_list[i].replace(/"/, ''));
                   1867:             }
                   1868:         }
                   1869:         return ret;
                   1870:     }
                   1871: 
                   1872:     function saveScrollPosition (resource) {
                   1873:         var tag_list = getTagList();
                   1874: 
                   1875:         // we dont always want to jump to the first block
                   1876:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1877:         if(\$(window).scrollTop() > 170){
                   1878:             if(tag_list != null){
                   1879:                 var result;
                   1880:                 for(var i = 0; i < tag_list.length; i++){
                   1881:                     if(isElementInViewport(tag_list[i])){
                   1882:                         result += tag_list[i]+';';
                   1883:                     }
                   1884:                 }
                   1885:                 sessionStorage.setItem('anchor_'+resource, result);
                   1886:             }
                   1887:         } else {
                   1888:             // we dont need to save zero, just delete the item to leave everything tidy
                   1889:             sessionStorage.removeItem('anchor_'+resource);
                   1890:         }
                   1891:     }
                   1892: 
                   1893:     function restoreScrollPosition(resource){
                   1894: 
                   1895:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1896:         if(elem != null){
                   1897:             var tag_list = elem.split(';');
                   1898:             var elem_list;
                   1899: 
                   1900:             for(var i = 0; i < tag_list.length; i++){
                   1901:                 elem_list = document.getElementsByName(tag_list[i]);
                   1902: 
                   1903:                 if(elem_list.length > 0){
                   1904:                     elem = elem_list[0];
                   1905:                     break;
                   1906:                 }
                   1907:             }
                   1908:             elem.scrollIntoView();
                   1909:         }
                   1910:     }
                   1911: 
                   1912:     function isElementInViewport(el) {
                   1913: 
                   1914:         // change to last element instead of first
                   1915:         var elem = document.getElementsByName(el);
                   1916:         var rect = elem[0].getBoundingClientRect();
                   1917: 
                   1918:         return (
                   1919:             rect.top >= 0 &&
                   1920:             rect.left >= 0 &&
                   1921:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1922:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1923:         );
                   1924:     }
                   1925: 
                   1926:     function autosize(depth){
                   1927:         var cmInst = window['cm'+depth];
                   1928:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1929: 
                   1930:         // is fixed size, switching to dynamic
                   1931:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1932:             cmInst.setSize("","auto");
                   1933:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1934:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1935: 
                   1936:         // is dynamic size, switching to fixed
                   1937:         } else {
                   1938:             cmInst.setSize("","300px");
                   1939:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1940:             sessionStorage.removeItem("autosized_"+depth);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: 
                   1945: 
                   1946: // ]]>
                   1947: </script>
                   1948: COLORFULEDIT
                   1949: }
                   1950: 
                   1951: sub xmleditor_js {
                   1952:     return <<XMLEDIT
                   1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1954: <script type="text/javascript">
                   1955: // <![CDATA[>
                   1956: 
                   1957:     function saveScrollPosition (resource) {
                   1958: 
                   1959:         var scrollPos = \$(window).scrollTop();
                   1960:         sessionStorage.setItem(resource,scrollPos);
                   1961:     }
                   1962: 
                   1963:     function restoreScrollPosition(resource){
                   1964: 
                   1965:         var scrollPos = sessionStorage.getItem(resource);
                   1966:         \$(window).scrollTop(scrollPos);
                   1967:     }
                   1968: 
                   1969:     // unless internet explorer
                   1970:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1971: 
                   1972:         \$(document).ready(function() {
                   1973:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1974:         });
                   1975:     }
                   1976: 
                   1977:     // inserts text at cursor position into codemirror (xml editor only)
                   1978:     function insertText(text){
                   1979:         cm.focus();
                   1980:         var curPos = cm.getCursor();
                   1981:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1982:     }
                   1983: // ]]>
                   1984: </script>
                   1985: XMLEDIT
                   1986: }
                   1987: 
                   1988: sub insert_folding_button {
                   1989:     my $curDepth = $Apache::lonxml::curdepth;
                   1990:     my $lastresource = $env{'request.ambiguous'};
                   1991: 
                   1992:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1993:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1994: }
                   1995: 
                   1996: 
1.565     albertel 1997: =pod
                   1998: 
1.256     matthew  1999: =head1 Excel and CSV file utility routines
                   2000: 
                   2001: =cut
                   2002: 
                   2003: ###############################################################
                   2004: ###############################################################
                   2005: 
                   2006: =pod
                   2007: 
1.1075.2.56  raeburn  2008: =over 4
                   2009: 
1.648     raeburn  2010: =item * &csv_translate($text) 
1.37      matthew  2011: 
1.185     www      2012: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2013: format.
                   2014: 
                   2015: =cut
                   2016: 
1.180     matthew  2017: ###############################################################
                   2018: ###############################################################
1.37      matthew  2019: sub csv_translate {
                   2020:     my $text = shift;
                   2021:     $text =~ s/\"/\"\"/g;
1.209     albertel 2022:     $text =~ s/\n/ /g;
1.37      matthew  2023:     return $text;
                   2024: }
1.180     matthew  2025: 
                   2026: ###############################################################
                   2027: ###############################################################
                   2028: 
                   2029: =pod
                   2030: 
1.648     raeburn  2031: =item * &define_excel_formats()
1.180     matthew  2032: 
                   2033: Define some commonly used Excel cell formats.
                   2034: 
                   2035: Currently supported formats:
                   2036: 
                   2037: =over 4
                   2038: 
                   2039: =item header
                   2040: 
                   2041: =item bold
                   2042: 
                   2043: =item h1
                   2044: 
                   2045: =item h2
                   2046: 
                   2047: =item h3
                   2048: 
1.256     matthew  2049: =item h4
                   2050: 
                   2051: =item i
                   2052: 
1.180     matthew  2053: =item date
                   2054: 
                   2055: =back
                   2056: 
                   2057: Inputs: $workbook
                   2058: 
                   2059: Returns: $format, a hash reference.
                   2060: 
1.1057    foxr     2061: 
1.180     matthew  2062: =cut
                   2063: 
                   2064: ###############################################################
                   2065: ###############################################################
                   2066: sub define_excel_formats {
                   2067:     my ($workbook) = @_;
                   2068:     my $format;
                   2069:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2070:                                                 bottom    => 1,
                   2071:                                                 align     => 'center');
                   2072:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2073:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2074:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2075:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2076:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2077:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2078:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2079:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2080:     return $format;
                   2081: }
                   2082: 
                   2083: ###############################################################
                   2084: ###############################################################
1.113     bowersj2 2085: 
                   2086: =pod
                   2087: 
1.648     raeburn  2088: =item * &create_workbook()
1.255     matthew  2089: 
                   2090: Create an Excel worksheet.  If it fails, output message on the
                   2091: request object and return undefs.
                   2092: 
                   2093: Inputs: Apache request object
                   2094: 
                   2095: Returns (undef) on failure, 
                   2096:     Excel worksheet object, scalar with filename, and formats 
                   2097:     from &Apache::loncommon::define_excel_formats on success
                   2098: 
                   2099: =cut
                   2100: 
                   2101: ###############################################################
                   2102: ###############################################################
                   2103: sub create_workbook {
                   2104:     my ($r) = @_;
                   2105:         #
                   2106:     # Create the excel spreadsheet
                   2107:     my $filename = '/prtspool/'.
1.258     albertel 2108:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2109:         time.'_'.rand(1000000000).'.xls';
                   2110:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2111:     if (! defined($workbook)) {
                   2112:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2113:         $r->print(
                   2114:             '<p class="LC_error">'
                   2115:            .&mt('Problems occurred in creating the new Excel file.')
                   2116:            .' '.&mt('This error has been logged.')
                   2117:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2118:            .'</p>'
                   2119:         );
1.255     matthew  2120:         return (undef);
                   2121:     }
                   2122:     #
1.1014    foxr     2123:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2124:     #
                   2125:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2126:     return ($workbook,$filename,$format);
                   2127: }
                   2128: 
                   2129: ###############################################################
                   2130: ###############################################################
                   2131: 
                   2132: =pod
                   2133: 
1.648     raeburn  2134: =item * &create_text_file()
1.113     bowersj2 2135: 
1.542     raeburn  2136: Create a file to write to and eventually make available to the user.
1.256     matthew  2137: If file creation fails, outputs an error message on the request object and 
                   2138: return undefs.
1.113     bowersj2 2139: 
1.256     matthew  2140: Inputs: Apache request object, and file suffix
1.113     bowersj2 2141: 
1.256     matthew  2142: Returns (undef) on failure, 
                   2143:     Filehandle and filename on success.
1.113     bowersj2 2144: 
                   2145: =cut
                   2146: 
1.256     matthew  2147: ###############################################################
                   2148: ###############################################################
                   2149: sub create_text_file {
                   2150:     my ($r,$suffix) = @_;
                   2151:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2152:     my $fh;
                   2153:     my $filename = '/prtspool/'.
1.258     albertel 2154:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2155:         time.'_'.rand(1000000000).'.'.$suffix;
                   2156:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2157:     if (! defined($fh)) {
                   2158:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2159:         $r->print(
                   2160:             '<p class="LC_error">'
                   2161:            .&mt('Problems occurred in creating the output file.')
                   2162:            .' '.&mt('This error has been logged.')
                   2163:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2164:            .'</p>'
                   2165:         );
1.113     bowersj2 2166:     }
1.256     matthew  2167:     return ($fh,$filename)
1.113     bowersj2 2168: }
                   2169: 
                   2170: 
1.256     matthew  2171: =pod 
1.113     bowersj2 2172: 
                   2173: =back
                   2174: 
                   2175: =cut
1.37      matthew  2176: 
                   2177: ###############################################################
1.33      matthew  2178: ##        Home server <option> list generating code          ##
                   2179: ###############################################################
1.35      matthew  2180: 
1.169     www      2181: # ------------------------------------------
                   2182: 
                   2183: sub domain_select {
                   2184:     my ($name,$value,$multiple)=@_;
                   2185:     my %domains=map { 
1.514     albertel 2186: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2187:     } &Apache::lonnet::all_domains();
1.169     www      2188:     if ($multiple) {
                   2189: 	$domains{''}=&mt('Any domain');
1.550     albertel 2190: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2191: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2192:     } else {
1.550     albertel 2193: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2194: 	return &select_form($name,$value,\%domains);
1.169     www      2195:     }
                   2196: }
                   2197: 
1.282     albertel 2198: #-------------------------------------------
                   2199: 
                   2200: =pod
                   2201: 
1.519     raeburn  2202: =head1 Routines for form select boxes
                   2203: 
                   2204: =over 4
                   2205: 
1.648     raeburn  2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2207: 
                   2208: Returns a string containing a <select> element int multiple mode
                   2209: 
                   2210: 
                   2211: Args:
                   2212:   $name - name of the <select> element
1.506     raeburn  2213:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2214:   $size - number of rows long the select element is
1.283     albertel 2215:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2216:           (shown text should already have been &mt())
1.506     raeburn  2217:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2218: 
1.282     albertel 2219: =cut
                   2220: 
                   2221: #-------------------------------------------
1.169     www      2222: sub multiple_select_form {
1.284     albertel 2223:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2224:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2225:     my $output='';
1.191     matthew  2226:     if (! defined($size)) {
                   2227:         $size = 4;
1.283     albertel 2228:         if (scalar(keys(%$hash))<4) {
                   2229:             $size = scalar(keys(%$hash));
1.191     matthew  2230:         }
                   2231:     }
1.734     bisitz   2232:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2233:     my @order;
1.506     raeburn  2234:     if (ref($order) eq 'ARRAY')  {
                   2235:         @order = @{$order};
                   2236:     } else {
                   2237:         @order = sort(keys(%$hash));
1.501     banghart 2238:     }
                   2239:     if (exists($$hash{'select_form_order'})) {
                   2240:         @order = @{$$hash{'select_form_order'}};
                   2241:     }
                   2242:         
1.284     albertel 2243:     foreach my $key (@order) {
1.356     albertel 2244:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2245:         $output.='selected="selected" ' if ($selected{$key});
                   2246:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2247:     }
                   2248:     $output.="</select>\n";
                   2249:     return $output;
                   2250: }
                   2251: 
1.88      www      2252: #-------------------------------------------
                   2253: 
                   2254: =pod
                   2255: 
1.1075.2.115  raeburn  2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2257: 
                   2258: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2259: allow a user to select options from a ref to a hash containing:
                   2260: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2261: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2262: An optional arg -- $readonly -- if true will cause the select form
                   2263: to be disabled, e.g., for the case where an instructor has a section-
                   2264: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2265: 
1.88      www      2266: See lonrights.pm for an example invocation and use.
                   2267: 
                   2268: =cut
                   2269: 
                   2270: #-------------------------------------------
                   2271: sub select_form {
1.1075.2.115  raeburn  2272:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2273:     return unless (ref($hashref) eq 'HASH');
                   2274:     if ($onchange) {
                   2275:         $onchange = ' onchange="'.$onchange.'"';
                   2276:     }
1.1075.2.129  raeburn  2277:     my $disabled;
                   2278:     if ($readonly) {
                   2279:         $disabled = ' disabled="disabled"';
                   2280:     }
                   2281:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2282:     my @keys;
1.970     raeburn  2283:     if (exists($hashref->{'select_form_order'})) {
                   2284: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2285:     } else {
1.970     raeburn  2286: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2287:     }
1.356     albertel 2288:     foreach my $key (@keys) {
                   2289:         $selectform.=
                   2290: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2291:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2292:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2293:     }
                   2294:     $selectform.="</select>";
                   2295:     return $selectform;
                   2296: }
                   2297: 
1.475     www      2298: # For display filters
                   2299: 
                   2300: sub display_filter {
1.1074    raeburn  2301:     my ($context) = @_;
1.475     www      2302:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2303:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2304:     my $phraseinput = 'hidden';
                   2305:     my $includeinput = 'hidden';
                   2306:     my ($checked,$includetypestext);
                   2307:     if ($env{'form.displayfilter'} eq 'containing') {
                   2308:         $phraseinput = 'text'; 
                   2309:         if ($context eq 'parmslog') {
                   2310:             $includeinput = 'checkbox';
                   2311:             if ($env{'form.includetypes'}) {
                   2312:                 $checked = ' checked="checked"';
                   2313:             }
                   2314:             $includetypestext = &mt('Include parameter types');
                   2315:         }
                   2316:     } else {
                   2317:         $includetypestext = '&nbsp;';
                   2318:     }
                   2319:     my ($additional,$secondid,$thirdid);
                   2320:     if ($context eq 'parmslog') {
                   2321:         $additional = 
                   2322:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2323:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2324:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2325:             '</label>';
                   2326:         $secondid = 'includetypes';
                   2327:         $thirdid = 'includetypestext';
                   2328:     }
                   2329:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2330:                                                     '$secondid','$thirdid')";
                   2331:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2332: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2333: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2334: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2335:            &mt('Filter: [_1]',
1.477     www      2336: 	   &select_form($env{'form.displayfilter'},
                   2337: 			'displayfilter',
1.970     raeburn  2338: 			{'currentfolder' => 'Current folder/page',
1.477     www      2339: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2340: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2341: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2342:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2343:                          '" />'.$additional;
                   2344: }
                   2345: 
                   2346: sub display_filter_js {
                   2347:     my $includetext = &mt('Include parameter types');
                   2348:     return <<"ENDJS";
                   2349:   
                   2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2351:     var firstType = 'hidden';
                   2352:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2353:         firstType = 'text';
                   2354:     }
                   2355:     firstObject = document.getElementById(firstid);
                   2356:     if (typeof(firstObject) == 'object') {
                   2357:         if (firstObject.type != firstType) {
                   2358:             changeInputType(firstObject,firstType);
                   2359:         }
                   2360:     }
                   2361:     if (context == 'parmslog') {
                   2362:         var secondType = 'hidden';
                   2363:         if (firstType == 'text') {
                   2364:             secondType = 'checkbox';
                   2365:         }
                   2366:         secondObject = document.getElementById(secondid);  
                   2367:         if (typeof(secondObject) == 'object') {
                   2368:             if (secondObject.type != secondType) {
                   2369:                 changeInputType(secondObject,secondType);
                   2370:             }
                   2371:         }
                   2372:         var textItem = document.getElementById(thirdid);
                   2373:         var currtext = textItem.innerHTML;
                   2374:         var newtext;
                   2375:         if (firstType == 'text') {
                   2376:             newtext = '$includetext';
                   2377:         } else {
                   2378:             newtext = '&nbsp;';
                   2379:         }
                   2380:         if (currtext != newtext) {
                   2381:             textItem.innerHTML = newtext;
                   2382:         }
                   2383:     }
                   2384:     return;
                   2385: }
                   2386: 
                   2387: function changeInputType(oldObject,newType) {
                   2388:     var newObject = document.createElement('input');
                   2389:     newObject.type = newType;
                   2390:     if (oldObject.size) {
                   2391:         newObject.size = oldObject.size;
                   2392:     }
                   2393:     if (oldObject.value) {
                   2394:         newObject.value = oldObject.value;
                   2395:     }
                   2396:     if (oldObject.name) {
                   2397:         newObject.name = oldObject.name;
                   2398:     }
                   2399:     if (oldObject.id) {
                   2400:         newObject.id = oldObject.id;
                   2401:     }
                   2402:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2403:     return;
                   2404: }
                   2405: 
                   2406: ENDJS
1.475     www      2407: }
                   2408: 
1.167     www      2409: sub gradeleveldescription {
                   2410:     my $gradelevel=shift;
                   2411:     my %gradelevels=(0 => 'Not specified',
                   2412: 		     1 => 'Grade 1',
                   2413: 		     2 => 'Grade 2',
                   2414: 		     3 => 'Grade 3',
                   2415: 		     4 => 'Grade 4',
                   2416: 		     5 => 'Grade 5',
                   2417: 		     6 => 'Grade 6',
                   2418: 		     7 => 'Grade 7',
                   2419: 		     8 => 'Grade 8',
                   2420: 		     9 => 'Grade 9',
                   2421: 		     10 => 'Grade 10',
                   2422: 		     11 => 'Grade 11',
                   2423: 		     12 => 'Grade 12',
                   2424: 		     13 => 'Grade 13',
                   2425: 		     14 => '100 Level',
                   2426: 		     15 => '200 Level',
                   2427: 		     16 => '300 Level',
                   2428: 		     17 => '400 Level',
                   2429: 		     18 => 'Graduate Level');
                   2430:     return &mt($gradelevels{$gradelevel});
                   2431: }
                   2432: 
1.163     www      2433: sub select_level_form {
                   2434:     my ($deflevel,$name)=@_;
                   2435:     unless ($deflevel) { $deflevel=0; }
1.167     www      2436:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2437:     for (my $i=0; $i<=18; $i++) {
                   2438:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2439:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2440:                 ">".&gradeleveldescription($i)."</option>\n";
                   2441:     }
                   2442:     $selectform.="</select>";
                   2443:     return $selectform;
1.163     www      2444: }
1.167     www      2445: 
1.35      matthew  2446: #-------------------------------------------
                   2447: 
1.45      matthew  2448: =pod
                   2449: 
1.1075.2.115  raeburn  2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2451: 
                   2452: Returns a string containing a <select name='$name' size='1'> form to 
                   2453: allow a user to select the domain to preform an operation in.  
                   2454: See loncreateuser.pm for an example invocation and use.
                   2455: 
1.90      www      2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2457: selected");
                   2458: 
1.743     raeburn  2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2460: 
1.910     raeburn  2461: 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.
                   2462: 
1.1075.2.36  raeburn  2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2464: 
1.1075.2.115  raeburn  2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2466: 
                   2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2468: 
1.35      matthew  2469: =cut
                   2470: 
                   2471: #-------------------------------------------
1.34      matthew  2472: sub select_dom_form {
1.1075.2.115  raeburn  2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2474:     if ($onchange) {
1.874     raeburn  2475:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2476:     }
1.1075.2.115  raeburn  2477:     if ($disabled) {
                   2478:         $disabled = ' disabled="disabled"';
                   2479:     }
1.1075.2.36  raeburn  2480:     my (@domains,%exclude);
1.910     raeburn  2481:     if (ref($incdoms) eq 'ARRAY') {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2483:     } else {
                   2484:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2485:     }
1.90      www      2486:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2487:     if (ref($excdoms) eq 'ARRAY') {
                   2488:         map { $exclude{$_} = 1; } @{$excdoms};
                   2489:     }
1.1075.2.115  raeburn  2490:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2491:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2492:         next if ($exclude{$dom});
1.356     albertel 2493:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2494:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2495:         if ($showdomdesc) {
                   2496:             if ($dom ne '') {
                   2497:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2498:                 if ($domdesc ne '') {
                   2499:                     $selectdomain .= ' ('.$domdesc.')';
                   2500:                 }
                   2501:             } 
                   2502:         }
                   2503:         $selectdomain .= "</option>\n";
1.34      matthew  2504:     }
                   2505:     $selectdomain.="</select>";
                   2506:     return $selectdomain;
                   2507: }
                   2508: 
1.35      matthew  2509: #-------------------------------------------
                   2510: 
1.45      matthew  2511: =pod
                   2512: 
1.648     raeburn  2513: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2514: 
1.586     raeburn  2515: input: 4 arguments (two required, two optional) - 
                   2516:     $domain - domain of new user
                   2517:     $name - name of form element
                   2518:     $default - Value of 'default' causes a default item to be first 
                   2519:                             option, and selected by default. 
                   2520:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2521:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2522: output: returns 2 items: 
1.586     raeburn  2523: (a) form element which contains either:
                   2524:    (i) <select name="$name">
                   2525:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2526:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2527:        </select>
                   2528:        form item if there are multiple library servers in $domain, or
                   2529:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2530:        if there is only one library server in $domain.
                   2531: 
                   2532: (b) number of library servers found.
                   2533: 
                   2534: See loncreateuser.pm for example of use.
1.35      matthew  2535: 
                   2536: =cut
                   2537: 
                   2538: #-------------------------------------------
1.586     raeburn  2539: sub home_server_form_item {
                   2540:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2541:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2542:     my $result;
                   2543:     my $numlib = keys(%servers);
                   2544:     if ($numlib > 1) {
                   2545:         $result .= '<select name="'.$name.'" />'."\n";
                   2546:         if ($default) {
1.804     bisitz   2547:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2548:                        '</option>'."\n";
                   2549:         }
                   2550:         foreach my $hostid (sort(keys(%servers))) {
                   2551:             $result.= '<option value="'.$hostid.'">'.
                   2552: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2553:         }
                   2554:         $result .= '</select>'."\n";
                   2555:     } elsif ($numlib == 1) {
                   2556:         my $hostid;
                   2557:         foreach my $item (keys(%servers)) {
                   2558:             $hostid = $item;
                   2559:         }
                   2560:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2561:                    $hostid.'" />';
                   2562:                    if (!$hide) {
                   2563:                        $result .= $hostid.' '.$servers{$hostid};
                   2564:                    }
                   2565:                    $result .= "\n";
                   2566:     } elsif ($default) {
                   2567:         $result .= '<input type="hidden" name="'.$name.
                   2568:                    '" value="default" />';
                   2569:                    if (!$hide) {
                   2570:                        $result .= &mt('default');
                   2571:                    }
                   2572:                    $result .= "\n";
1.33      matthew  2573:     }
1.586     raeburn  2574:     return ($result,$numlib);
1.33      matthew  2575: }
1.112     bowersj2 2576: 
                   2577: =pod
                   2578: 
1.534     albertel 2579: =back 
                   2580: 
1.112     bowersj2 2581: =cut
1.87      matthew  2582: 
                   2583: ###############################################################
1.112     bowersj2 2584: ##                  Decoding User Agent                      ##
1.87      matthew  2585: ###############################################################
                   2586: 
                   2587: =pod
                   2588: 
1.112     bowersj2 2589: =head1 Decoding the User Agent
                   2590: 
                   2591: =over 4
                   2592: 
                   2593: =item * &decode_user_agent()
1.87      matthew  2594: 
                   2595: Inputs: $r
                   2596: 
                   2597: Outputs:
                   2598: 
                   2599: =over 4
                   2600: 
1.112     bowersj2 2601: =item * $httpbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientbrowser
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientversion
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientmathml
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientunicode
1.87      matthew  2610: 
1.112     bowersj2 2611: =item * $clientos
1.87      matthew  2612: 
1.1075.2.42  raeburn  2613: =item * $clientmobile
                   2614: 
                   2615: =item * $clientinfo
                   2616: 
1.1075.2.77  raeburn  2617: =item * $clientosversion
                   2618: 
1.87      matthew  2619: =back
                   2620: 
1.157     matthew  2621: =back 
                   2622: 
1.87      matthew  2623: =cut
                   2624: 
                   2625: ###############################################################
                   2626: ###############################################################
                   2627: sub decode_user_agent {
1.247     albertel 2628:     my ($r)=@_;
1.87      matthew  2629:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2630:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2631:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2632:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2633:     my $clientbrowser='unknown';
                   2634:     my $clientversion='0';
                   2635:     my $clientmathml='';
                   2636:     my $clientunicode='0';
1.1075.2.42  raeburn  2637:     my $clientmobile=0;
1.1075.2.77  raeburn  2638:     my $clientosversion='';
1.87      matthew  2639:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2640:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2641: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2642: 	    $clientbrowser=$bname;
                   2643:             $httpbrowser=~/$vreg/i;
                   2644: 	    $clientversion=$1;
                   2645:             $clientmathml=($clientversion>=$minv);
                   2646:             $clientunicode=($clientversion>=$univ);
                   2647: 	}
                   2648:     }
                   2649:     my $clientos='unknown';
1.1075.2.42  raeburn  2650:     my $clientinfo;
1.87      matthew  2651:     if (($httpbrowser=~/linux/i) ||
                   2652:         ($httpbrowser=~/unix/i) ||
                   2653:         ($httpbrowser=~/ux/i) ||
                   2654:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2655:     if (($httpbrowser=~/vax/i) ||
                   2656:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2657:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2658:     if (($httpbrowser=~/mac/i) ||
                   2659:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2660:     if ($httpbrowser=~/win/i) {
                   2661:         $clientos='win';
                   2662:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2663:             $clientosversion = $1;
                   2664:         }
                   2665:     }
1.87      matthew  2666:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2667:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2668:         $clientmobile=lc($1);
                   2669:     }
                   2670:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2671:         $clientinfo = 'firefox-'.$1;
                   2672:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2673:         $clientinfo = 'chromeframe-'.$1;
                   2674:     }
1.87      matthew  2675:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2676:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2677:             $clientosversion);
1.87      matthew  2678: }
                   2679: 
1.32      matthew  2680: ###############################################################
                   2681: ##    Authentication changing form generation subroutines    ##
                   2682: ###############################################################
                   2683: ##
                   2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2685: ## hash, and have reasonable default values.
                   2686: ##
                   2687: ##    formname = the name given in the <form> tag.
1.35      matthew  2688: #-------------------------------------------
                   2689: 
1.45      matthew  2690: =pod
                   2691: 
1.112     bowersj2 2692: =head1 Authentication Routines
                   2693: 
                   2694: =over 4
                   2695: 
1.648     raeburn  2696: =item * &authform_xxxxxx()
1.35      matthew  2697: 
                   2698: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2699: handle some of the conveniences required for authentication forms.  
                   2700: This is not an optimal method, but it works.  
                   2701: 
                   2702: =over 4
                   2703: 
1.112     bowersj2 2704: =item * authform_header
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_authorwarning
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_nochange
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_kerberos
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_internal
1.35      matthew  2713: 
1.112     bowersj2 2714: =item * authform_filesystem
1.35      matthew  2715: 
                   2716: =back
                   2717: 
1.648     raeburn  2718: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2719: 
1.35      matthew  2720: =cut
                   2721: 
                   2722: #-------------------------------------------
1.32      matthew  2723: sub authform_header{  
                   2724:     my %in = (
                   2725:         formname => 'cu',
1.80      albertel 2726:         kerb_def_dom => '',
1.32      matthew  2727:         @_,
                   2728:     );
                   2729:     $in{'formname'} = 'document.' . $in{'formname'};
                   2730:     my $result='';
1.80      albertel 2731: 
                   2732: #---------------------------------------------- Code for upper case translation
                   2733:     my $Javascript_toUpperCase;
                   2734:     unless ($in{kerb_def_dom}) {
                   2735:         $Javascript_toUpperCase =<<"END";
                   2736:         switch (choice) {
                   2737:            case 'krb': currentform.elements[choicearg].value =
                   2738:                currentform.elements[choicearg].value.toUpperCase();
                   2739:                break;
                   2740:            default:
                   2741:         }
                   2742: END
                   2743:     } else {
                   2744:         $Javascript_toUpperCase = "";
                   2745:     }
                   2746: 
1.165     raeburn  2747:     my $radioval = "'nochange'";
1.591     raeburn  2748:     if (defined($in{'curr_authtype'})) {
                   2749:         if ($in{'curr_authtype'} ne '') {
                   2750:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2751:         }
1.174     matthew  2752:     }
1.165     raeburn  2753:     my $argfield = 'null';
1.591     raeburn  2754:     if (defined($in{'mode'})) {
1.165     raeburn  2755:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2756:             if (defined($in{'curr_autharg'})) {
                   2757:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2758:                     $argfield = "'$in{'curr_autharg'}'";
                   2759:                 }
                   2760:             }
                   2761:         }
                   2762:     }
                   2763: 
1.32      matthew  2764:     $result.=<<"END";
                   2765: var current = new Object();
1.165     raeburn  2766: current.radiovalue = $radioval;
                   2767: current.argfield = $argfield;
1.32      matthew  2768: 
                   2769: function changed_radio(choice,currentform) {
                   2770:     var choicearg = choice + 'arg';
                   2771:     // If a radio button in changed, we need to change the argfield
                   2772:     if (current.radiovalue != choice) {
                   2773:         current.radiovalue = choice;
                   2774:         if (current.argfield != null) {
                   2775:             currentform.elements[current.argfield].value = '';
                   2776:         }
                   2777:         if (choice == 'nochange') {
                   2778:             current.argfield = null;
                   2779:         } else {
                   2780:             current.argfield = choicearg;
                   2781:             switch(choice) {
                   2782:                 case 'krb': 
                   2783:                     currentform.elements[current.argfield].value = 
                   2784:                         "$in{'kerb_def_dom'}";
                   2785:                 break;
                   2786:               default:
                   2787:                 break;
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return;
                   2792: }
1.22      www      2793: 
1.32      matthew  2794: function changed_text(choice,currentform) {
                   2795:     var choicearg = choice + 'arg';
                   2796:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2797:         $Javascript_toUpperCase
1.32      matthew  2798:         // clear old field
                   2799:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2800:             currentform.elements[current.argfield].value = '';
                   2801:         }
                   2802:         current.argfield = choicearg;
                   2803:     }
                   2804:     set_auth_radio_buttons(choice,currentform);
                   2805:     return;
1.20      www      2806: }
1.32      matthew  2807: 
                   2808: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2809:     var numauthchoices = currentform.login.length;
                   2810:     if (typeof numauthchoices  == "undefined") {
                   2811:         return;
                   2812:     } 
1.32      matthew  2813:     var i=0;
1.986     raeburn  2814:     while (i < numauthchoices) {
1.32      matthew  2815:         if (currentform.login[i].value == newvalue) { break; }
                   2816:         i++;
                   2817:     }
1.986     raeburn  2818:     if (i == numauthchoices) {
1.32      matthew  2819:         return;
                   2820:     }
                   2821:     current.radiovalue = newvalue;
                   2822:     currentform.login[i].checked = true;
                   2823:     return;
                   2824: }
                   2825: END
                   2826:     return $result;
                   2827: }
                   2828: 
1.1075.2.20  raeburn  2829: sub authform_authorwarning {
1.32      matthew  2830:     my $result='';
1.144     matthew  2831:     $result='<i>'.
                   2832:         &mt('As a general rule, only authors or co-authors should be '.
                   2833:             'filesystem authenticated '.
                   2834:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2835:     return $result;
                   2836: }
                   2837: 
1.1075.2.20  raeburn  2838: sub authform_nochange {
1.32      matthew  2839:     my %in = (
                   2840:               formname => 'document.cu',
                   2841:               kerb_def_dom => 'MSU.EDU',
                   2842:               @_,
                   2843:           );
1.1075.2.20  raeburn  2844:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2845:     my $result;
1.1075.2.20  raeburn  2846:     if (!$authnum) {
                   2847:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2848:     } else {
                   2849:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2850:                   '<input type="radio" name="login" value="nochange" '.
                   2851:                   'checked="checked" onclick="'.
1.281     albertel 2852:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2853: 	    '</label>';
1.586     raeburn  2854:     }
1.32      matthew  2855:     return $result;
                   2856: }
                   2857: 
1.591     raeburn  2858: sub authform_kerberos {
1.32      matthew  2859:     my %in = (
                   2860:               formname => 'document.cu',
                   2861:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2862:               kerb_def_auth => 'krb4',
1.32      matthew  2863:               @_,
                   2864:               );
1.586     raeburn  2865:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2866:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2867:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2868:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2869:        $check5 = ' checked="checked"';
1.80      albertel 2870:     } else {
1.772     bisitz   2871:        $check4 = ' checked="checked"';
1.80      albertel 2872:     }
1.1075.2.117  raeburn  2873:     if ($in{'readonly'}) {
                   2874:         $disabled = ' disabled="disabled"';
                   2875:     }
1.165     raeburn  2876:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2877:     if (defined($in{'curr_authtype'})) {
                   2878:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2879:             $krbcheck = ' checked="checked"';
1.623     raeburn  2880:             if (defined($in{'mode'})) {
                   2881:                 if ($in{'mode'} eq 'modifyuser') {
                   2882:                     $krbcheck = '';
                   2883:                 }
                   2884:             }
1.591     raeburn  2885:             if (defined($in{'curr_kerb_ver'})) {
                   2886:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2887:                     $check5 = ' checked="checked"';
1.591     raeburn  2888:                     $check4 = '';
                   2889:                 } else {
1.772     bisitz   2890:                     $check4 = ' checked="checked"';
1.591     raeburn  2891:                     $check5 = '';
                   2892:                 }
1.586     raeburn  2893:             }
1.591     raeburn  2894:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2895:                 $krbarg = $in{'curr_autharg'};
                   2896:             }
1.586     raeburn  2897:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2898:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2899:                     $result = 
                   2900:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2901:         $in{'curr_autharg'},$krbver);
                   2902:                 } else {
                   2903:                     $result =
                   2904:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2905:                 }
                   2906:                 return $result; 
                   2907:             }
                   2908:         }
                   2909:     } else {
                   2910:         if ($authnum == 1) {
1.784     bisitz   2911:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2912:         }
                   2913:     }
1.586     raeburn  2914:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2915:         return;
1.587     raeburn  2916:     } elsif ($authtype eq '') {
1.591     raeburn  2917:         if (defined($in{'mode'})) {
1.587     raeburn  2918:             if ($in{'mode'} eq 'modifycourse') {
                   2919:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2920:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2921:                 }
                   2922:             }
                   2923:         }
1.586     raeburn  2924:     }
                   2925:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2926:     if ($authtype eq '') {
                   2927:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2928:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2929:                     $krbcheck.$disabled.' />';
1.586     raeburn  2930:     }
                   2931:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2932:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2934:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2935:          $in{'curr_authtype'} eq 'krb4')) {
                   2936:         $result .= &mt
1.144     matthew  2937:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2938:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2939:          '<label>'.$authtype,
1.281     albertel 2940:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2941:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2942:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2943:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2944:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2945: 	 '</label>');
1.586     raeburn  2946:     } elsif ($can_assign{'krb4'}) {
                   2947:         $result .= &mt
                   2948:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2949:          '[_3] Version 4 [_4]',
                   2950:          '<label>'.$authtype,
                   2951:          '</label><input type="text" size="10" name="krbarg" '.
                   2952:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2953:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2954:          '<label><input type="hidden" name="krbver" value="4" />',
                   2955:          '</label>');
                   2956:     } elsif ($can_assign{'krb5'}) {
                   2957:         $result .= &mt
                   2958:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2959:          '[_3] Version 5 [_4]',
                   2960:          '<label>'.$authtype,
                   2961:          '</label><input type="text" size="10" name="krbarg" '.
                   2962:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2963:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2964:          '<label><input type="hidden" name="krbver" value="5" />',
                   2965:          '</label>');
                   2966:     }
1.32      matthew  2967:     return $result;
                   2968: }
                   2969: 
1.1075.2.20  raeburn  2970: sub authform_internal {
1.586     raeburn  2971:     my %in = (
1.32      matthew  2972:                 formname => 'document.cu',
                   2973:                 kerb_def_dom => 'MSU.EDU',
                   2974:                 @_,
                   2975:                 );
1.1075.2.117  raeburn  2976:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2977:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2978:     if ($in{'readonly'}) {
                   2979:         $disabled = ' disabled="disabled"';
                   2980:     }
1.591     raeburn  2981:     if (defined($in{'curr_authtype'})) {
                   2982:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2983:             if ($can_assign{'int'}) {
1.772     bisitz   2984:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2985:                 if (defined($in{'mode'})) {
                   2986:                     if ($in{'mode'} eq 'modifyuser') {
                   2987:                         $intcheck = '';
                   2988:                     }
                   2989:                 }
1.591     raeburn  2990:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2991:                     $intarg = $in{'curr_autharg'};
                   2992:                 }
                   2993:             } else {
                   2994:                 $result = &mt('Currently internally authenticated.');
                   2995:                 return $result;
1.165     raeburn  2996:             }
                   2997:         }
1.586     raeburn  2998:     } else {
                   2999:         if ($authnum == 1) {
1.784     bisitz   3000:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3001:         }
                   3002:     }
                   3003:     if (!$can_assign{'int'}) {
                   3004:         return;
1.587     raeburn  3005:     } elsif ($authtype eq '') {
1.591     raeburn  3006:         if (defined($in{'mode'})) {
1.587     raeburn  3007:             if ($in{'mode'} eq 'modifycourse') {
                   3008:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3009:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3010:                 }
                   3011:             }
                   3012:         }
1.165     raeburn  3013:     }
1.586     raeburn  3014:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3015:     if ($authtype eq '') {
                   3016:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3017:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3018:     }
1.605     bisitz   3019:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3020:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3021:     $result = &mt
1.144     matthew  3022:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3023:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3024:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3025:     return $result;
                   3026: }
                   3027: 
1.1075.2.20  raeburn  3028: sub authform_local {
1.32      matthew  3029:     my %in = (
                   3030:               formname => 'document.cu',
                   3031:               kerb_def_dom => 'MSU.EDU',
                   3032:               @_,
                   3033:               );
1.1075.2.117  raeburn  3034:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3035:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3036:     if ($in{'readonly'}) {
                   3037:         $disabled = ' disabled="disabled"';
                   3038:     }
1.591     raeburn  3039:     if (defined($in{'curr_authtype'})) {
                   3040:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3041:             if ($can_assign{'loc'}) {
1.772     bisitz   3042:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3043:                 if (defined($in{'mode'})) {
                   3044:                     if ($in{'mode'} eq 'modifyuser') {
                   3045:                         $loccheck = '';
                   3046:                     }
                   3047:                 }
1.591     raeburn  3048:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3049:                     $locarg = $in{'curr_autharg'};
                   3050:                 }
                   3051:             } else {
                   3052:                 $result = &mt('Currently using local (institutional) authentication.');
                   3053:                 return $result;
1.165     raeburn  3054:             }
                   3055:         }
1.586     raeburn  3056:     } else {
                   3057:         if ($authnum == 1) {
1.784     bisitz   3058:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3059:         }
                   3060:     }
                   3061:     if (!$can_assign{'loc'}) {
                   3062:         return;
1.587     raeburn  3063:     } elsif ($authtype eq '') {
1.591     raeburn  3064:         if (defined($in{'mode'})) {
1.587     raeburn  3065:             if ($in{'mode'} eq 'modifycourse') {
                   3066:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3067:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3068:                 }
                   3069:             }
                   3070:         }
1.165     raeburn  3071:     }
1.586     raeburn  3072:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3073:     if ($authtype eq '') {
                   3074:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3075:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3076:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3077:     }
                   3078:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3079:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3080:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3081:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3082:     return $result;
                   3083: }
                   3084: 
1.1075.2.20  raeburn  3085: sub authform_filesystem {
1.32      matthew  3086:     my %in = (
                   3087:               formname => 'document.cu',
                   3088:               kerb_def_dom => 'MSU.EDU',
                   3089:               @_,
                   3090:               );
1.1075.2.117  raeburn  3091:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3092:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3093:     if ($in{'readonly'}) {
                   3094:         $disabled = ' disabled="disabled"';
                   3095:     }
1.591     raeburn  3096:     if (defined($in{'curr_authtype'})) {
                   3097:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3098:             if ($can_assign{'fsys'}) {
1.772     bisitz   3099:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3100:                 if (defined($in{'mode'})) {
                   3101:                     if ($in{'mode'} eq 'modifyuser') {
                   3102:                         $fsyscheck = '';
                   3103:                     }
                   3104:                 }
1.586     raeburn  3105:             } else {
                   3106:                 $result = &mt('Currently Filesystem Authenticated.');
                   3107:                 return $result;
                   3108:             }           
                   3109:         }
                   3110:     } else {
                   3111:         if ($authnum == 1) {
1.784     bisitz   3112:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3113:         }
                   3114:     }
                   3115:     if (!$can_assign{'fsys'}) {
                   3116:         return;
1.587     raeburn  3117:     } elsif ($authtype eq '') {
1.591     raeburn  3118:         if (defined($in{'mode'})) {
1.587     raeburn  3119:             if ($in{'mode'} eq 'modifycourse') {
                   3120:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3121:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3122:                 }
                   3123:             }
                   3124:         }
1.586     raeburn  3125:     }
                   3126:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3127:     if ($authtype eq '') {
                   3128:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3129:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3130:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3131:     }
                   3132:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3133:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3134:     $result = &mt
1.144     matthew  3135:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3136:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3137:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3138:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3139:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3140:     return $result;
                   3141: }
                   3142: 
1.586     raeburn  3143: sub get_assignable_auth {
                   3144:     my ($dom) = @_;
                   3145:     if ($dom eq '') {
                   3146:         $dom = $env{'request.role.domain'};
                   3147:     }
                   3148:     my %can_assign = (
                   3149:                           krb4 => 1,
                   3150:                           krb5 => 1,
                   3151:                           int  => 1,
                   3152:                           loc  => 1,
                   3153:                      );
                   3154:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3155:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3156:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3157:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3158:             my $context;
                   3159:             if ($env{'request.role'} =~ /^au/) {
                   3160:                 $context = 'author';
1.1075.2.117  raeburn  3161:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3162:                 $context = 'domain';
                   3163:             } elsif ($env{'request.course.id'}) {
                   3164:                 $context = 'course';
                   3165:             }
                   3166:             if ($context) {
                   3167:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3168:                    %can_assign = %{$authhash->{$context}}; 
                   3169:                 }
                   3170:             }
                   3171:         }
                   3172:     }
                   3173:     my $authnum = 0;
                   3174:     foreach my $key (keys(%can_assign)) {
                   3175:         if ($can_assign{$key}) {
                   3176:             $authnum ++;
                   3177:         }
                   3178:     }
                   3179:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3180:         $authnum --;
                   3181:     }
                   3182:     return ($authnum,%can_assign);
                   3183: }
                   3184: 
1.1075.2.137  raeburn  3185: sub check_passwd_rules {
                   3186:     my ($domain,$plainpass) = @_;
                   3187:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3188:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3189:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3190:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3191:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3192:             if ($passwdconf{'min'} > $min) {
                   3193:                 $min = $passwdconf{'min'};
                   3194:             }
1.1075.2.137  raeburn  3195:         }
                   3196:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3197:             $max = $passwdconf{'max'};
                   3198:         }
                   3199:         @chars = @{$passwdconf{'chars'}};
                   3200:     }
                   3201:     if (($min) && (length($plainpass) < $min)) {
                   3202:         push(@brokerule,'min');
                   3203:     }
                   3204:     if (($max) && (length($plainpass) > $max)) {
                   3205:         push(@brokerule,'max');
                   3206:     }
                   3207:     if (@chars) {
                   3208:         my %rules;
                   3209:         map { $rules{$_} = 1; } @chars;
                   3210:         if ($rules{'uc'}) {
                   3211:             unless ($plainpass =~ /[A-Z]/) {
                   3212:                 push(@brokerule,'uc');
                   3213:             }
                   3214:         }
                   3215:         if ($rules{'lc'}) {
                   3216:             unless ($plainpass =~ /[a-z]/) {
                   3217:                 push(@brokerule,'lc');
                   3218:             }
                   3219:         }
                   3220:         if ($rules{'num'}) {
                   3221:             unless ($plainpass =~ /\d/) {
                   3222:                 push(@brokerule,'num');
                   3223:             }
                   3224:         }
                   3225:         if ($rules{'spec'}) {
                   3226:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3227:                 push(@brokerule,'spec');
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     if (@brokerule) {
                   3232:         my %rulenames = &Apache::lonlocal::texthash(
                   3233:             uc   => 'At least one upper case letter',
                   3234:             lc   => 'At least one lower case letter',
                   3235:             num  => 'At least one number',
                   3236:             spec => 'At least one non-alphanumeric',
                   3237:         );
                   3238:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3239:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3240:         $rulenames{'num'} .= ': 0123456789';
                   3241:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3242:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3243:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3244:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.141.  .3(raebu 3245:20):         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3246:             if (grep(/^$rule$/,@brokerule)) {
                   3247:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3248:             }
                   3249:         }
                   3250:         $warning .= '</ul>';
                   3251:     }
                   3252:     if (wantarray) {
                   3253:         return @brokerule;
                   3254:     }
                   3255:     return $warning;
                   3256: }
                   3257: 
1.80      albertel 3258: ###############################################################
                   3259: ##    Get Kerberos Defaults for Domain                 ##
                   3260: ###############################################################
                   3261: ##
                   3262: ## Returns default kerberos version and an associated argument
                   3263: ## as listed in file domain.tab. If not listed, provides
                   3264: ## appropriate default domain and kerberos version.
                   3265: ##
                   3266: #-------------------------------------------
                   3267: 
                   3268: =pod
                   3269: 
1.648     raeburn  3270: =item * &get_kerberos_defaults()
1.80      albertel 3271: 
                   3272: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3273: version and domain. If not found, it defaults to version 4 and the 
                   3274: domain of the server.
1.80      albertel 3275: 
1.648     raeburn  3276: =over 4
                   3277: 
1.80      albertel 3278: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3279: 
1.648     raeburn  3280: =back
                   3281: 
                   3282: =back
                   3283: 
1.80      albertel 3284: =cut
                   3285: 
                   3286: #-------------------------------------------
                   3287: sub get_kerberos_defaults {
                   3288:     my $domain=shift;
1.641     raeburn  3289:     my ($krbdef,$krbdefdom);
                   3290:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3291:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3292:         $krbdef = $domdefaults{'auth_def'};
                   3293:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3294:     } else {
1.80      albertel 3295:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3296:         my $krbdefdom=$1;
                   3297:         $krbdefdom=~tr/a-z/A-Z/;
                   3298:         $krbdef = "krb4";
                   3299:     }
                   3300:     return ($krbdef,$krbdefdom);
                   3301: }
1.112     bowersj2 3302: 
1.32      matthew  3303: 
1.46      matthew  3304: ###############################################################
                   3305: ##                Thesaurus Functions                        ##
                   3306: ###############################################################
1.20      www      3307: 
1.46      matthew  3308: =pod
1.20      www      3309: 
1.112     bowersj2 3310: =head1 Thesaurus Functions
                   3311: 
                   3312: =over 4
                   3313: 
1.648     raeburn  3314: =item * &initialize_keywords()
1.46      matthew  3315: 
                   3316: Initializes the package variable %Keywords if it is empty.  Uses the
                   3317: package variable $thesaurus_db_file.
                   3318: 
                   3319: =cut
                   3320: 
                   3321: ###################################################
                   3322: 
                   3323: sub initialize_keywords {
                   3324:     return 1 if (scalar keys(%Keywords));
                   3325:     # If we are here, %Keywords is empty, so fill it up
                   3326:     #   Make sure the file we need exists...
                   3327:     if (! -e $thesaurus_db_file) {
                   3328:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3329:                                  " failed because it does not exist");
                   3330:         return 0;
                   3331:     }
                   3332:     #   Set up the hash as a database
                   3333:     my %thesaurus_db;
                   3334:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3335:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3336:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3337:                                  $thesaurus_db_file);
                   3338:         return 0;
                   3339:     } 
                   3340:     #  Get the average number of appearances of a word.
                   3341:     my $avecount = $thesaurus_db{'average.count'};
                   3342:     #  Put keywords (those that appear > average) into %Keywords
                   3343:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3344:         my ($count,undef) = split /:/,$data;
                   3345:         $Keywords{$word}++ if ($count > $avecount);
                   3346:     }
                   3347:     untie %thesaurus_db;
                   3348:     # Remove special values from %Keywords.
1.356     albertel 3349:     foreach my $value ('total.count','average.count') {
                   3350:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3351:   }
1.46      matthew  3352:     return 1;
                   3353: }
                   3354: 
                   3355: ###################################################
                   3356: 
                   3357: =pod
                   3358: 
1.648     raeburn  3359: =item * &keyword($word)
1.46      matthew  3360: 
                   3361: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3362: than the average number of times in the thesaurus database.  Calls 
                   3363: &initialize_keywords
                   3364: 
                   3365: =cut
                   3366: 
                   3367: ###################################################
1.20      www      3368: 
                   3369: sub keyword {
1.46      matthew  3370:     return if (!&initialize_keywords());
                   3371:     my $word=lc(shift());
                   3372:     $word=~s/\W//g;
                   3373:     return exists($Keywords{$word});
1.20      www      3374: }
1.46      matthew  3375: 
                   3376: ###############################################################
                   3377: 
                   3378: =pod 
1.20      www      3379: 
1.648     raeburn  3380: =item * &get_related_words()
1.46      matthew  3381: 
1.160     matthew  3382: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3383: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3384: will be returned.  The order of the words returned is determined by the
                   3385: database which holds them.
                   3386: 
                   3387: Uses global $thesaurus_db_file.
                   3388: 
1.1057    foxr     3389: 
1.46      matthew  3390: =cut
                   3391: 
                   3392: ###############################################################
                   3393: sub get_related_words {
                   3394:     my $keyword = shift;
                   3395:     my %thesaurus_db;
                   3396:     if (! -e $thesaurus_db_file) {
                   3397:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3398:                                  "failed because the file does not exist");
                   3399:         return ();
                   3400:     }
                   3401:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3402:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3403:         return ();
                   3404:     } 
                   3405:     my @Words=();
1.429     www      3406:     my $count=0;
1.46      matthew  3407:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3408: 	# The first element is the number of times
                   3409: 	# the word appears.  We do not need it now.
1.429     www      3410: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3411: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3412: 	my $threshold=$mostfrequentcount/10;
                   3413:         foreach my $possibleword (@RelatedWords) {
                   3414:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3415:             if ($wordcount>$threshold) {
                   3416: 		push(@Words,$word);
                   3417:                 $count++;
                   3418:                 if ($count>10) { last; }
                   3419: 	    }
1.20      www      3420:         }
                   3421:     }
1.46      matthew  3422:     untie %thesaurus_db;
                   3423:     return @Words;
1.14      harris41 3424: }
1.46      matthew  3425: 
1.112     bowersj2 3426: =pod
                   3427: 
                   3428: =back
                   3429: 
                   3430: =cut
1.61      www      3431: 
                   3432: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3433: =pod
                   3434: 
1.112     bowersj2 3435: =head1 User Name Functions
                   3436: 
                   3437: =over 4
                   3438: 
1.648     raeburn  3439: =item * &plainname($uname,$udom,$first)
1.81      albertel 3440: 
1.112     bowersj2 3441: Takes a users logon name and returns it as a string in
1.226     albertel 3442: "first middle last generation" form 
                   3443: if $first is set to 'lastname' then it returns it as
                   3444: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3445: 
                   3446: =cut
1.61      www      3447: 
1.295     www      3448: 
1.81      albertel 3449: ###############################################################
1.61      www      3450: sub plainname {
1.226     albertel 3451:     my ($uname,$udom,$first)=@_;
1.537     albertel 3452:     return if (!defined($uname) || !defined($udom));
1.295     www      3453:     my %names=&getnames($uname,$udom);
1.226     albertel 3454:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3455: 					  $names{'middlename'},
                   3456: 					  $names{'lastname'},
                   3457: 					  $names{'generation'},$first);
                   3458:     $name=~s/^\s+//;
1.62      www      3459:     $name=~s/\s+$//;
                   3460:     $name=~s/\s+/ /g;
1.353     albertel 3461:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3462:     return $name;
1.61      www      3463: }
1.66      www      3464: 
                   3465: # -------------------------------------------------------------------- Nickname
1.81      albertel 3466: =pod
                   3467: 
1.648     raeburn  3468: =item * &nickname($uname,$udom)
1.81      albertel 3469: 
                   3470: Gets a users name and returns it as a string as
                   3471: 
                   3472: "&quot;nickname&quot;"
1.66      www      3473: 
1.81      albertel 3474: if the user has a nickname or
                   3475: 
                   3476: "first middle last generation"
                   3477: 
                   3478: if the user does not
                   3479: 
                   3480: =cut
1.66      www      3481: 
                   3482: sub nickname {
                   3483:     my ($uname,$udom)=@_;
1.537     albertel 3484:     return if (!defined($uname) || !defined($udom));
1.295     www      3485:     my %names=&getnames($uname,$udom);
1.68      albertel 3486:     my $name=$names{'nickname'};
1.66      www      3487:     if ($name) {
                   3488:        $name='&quot;'.$name.'&quot;'; 
                   3489:     } else {
                   3490:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3491: 	     $names{'lastname'}.' '.$names{'generation'};
                   3492:        $name=~s/\s+$//;
                   3493:        $name=~s/\s+/ /g;
                   3494:     }
                   3495:     return $name;
                   3496: }
                   3497: 
1.295     www      3498: sub getnames {
                   3499:     my ($uname,$udom)=@_;
1.537     albertel 3500:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3501:     if ($udom eq 'public' && $uname eq 'public') {
                   3502: 	return ('lastname' => &mt('Public'));
                   3503:     }
1.295     www      3504:     my $id=$uname.':'.$udom;
                   3505:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3506:     if ($cached) {
                   3507: 	return %{$names};
                   3508:     } else {
                   3509: 	my %loadnames=&Apache::lonnet::get('environment',
                   3510:                     ['firstname','middlename','lastname','generation','nickname'],
                   3511: 					 $udom,$uname);
                   3512: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3513: 	return %loadnames;
                   3514:     }
                   3515: }
1.61      www      3516: 
1.542     raeburn  3517: # -------------------------------------------------------------------- getemails
1.648     raeburn  3518: 
1.542     raeburn  3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &getemails($uname,$udom)
1.542     raeburn  3522: 
                   3523: Gets a user's email information and returns it as a hash with keys:
                   3524: notification, critnotification, permanentemail
                   3525: 
                   3526: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3527: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3528:  
1.648     raeburn  3529: 
1.542     raeburn  3530: =cut
                   3531: 
1.648     raeburn  3532: 
1.466     albertel 3533: sub getemails {
                   3534:     my ($uname,$udom)=@_;
                   3535:     if ($udom eq 'public' && $uname eq 'public') {
                   3536: 	return;
                   3537:     }
1.467     www      3538:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3540:     my $id=$uname.':'.$udom;
                   3541:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3542:     if ($cached) {
                   3543: 	return %{$names};
                   3544:     } else {
                   3545: 	my %loadnames=&Apache::lonnet::get('environment',
                   3546:                     			   ['notification','critnotification',
                   3547: 					    'permanentemail'],
                   3548: 					   $udom,$uname);
                   3549: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3550: 	return %loadnames;
                   3551:     }
                   3552: }
                   3553: 
1.551     albertel 3554: sub flush_email_cache {
                   3555:     my ($uname,$udom)=@_;
                   3556:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3557:     if (!$uname) { $uname=$env{'user.name'};   }
                   3558:     return if ($udom eq 'public' && $uname eq 'public');
                   3559:     my $id=$uname.':'.$udom;
                   3560:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3561: }
                   3562: 
1.728     raeburn  3563: # -------------------------------------------------------------------- getlangs
                   3564: 
                   3565: =pod
                   3566: 
                   3567: =item * &getlangs($uname,$udom)
                   3568: 
                   3569: Gets a user's language preference and returns it as a hash with key:
                   3570: language.
                   3571: 
                   3572: =cut
                   3573: 
                   3574: 
                   3575: sub getlangs {
                   3576:     my ($uname,$udom) = @_;
                   3577:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3578:     if (!$uname) { $uname=$env{'user.name'};   }
                   3579:     my $id=$uname.':'.$udom;
                   3580:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3581:     if ($cached) {
                   3582:         return %{$langs};
                   3583:     } else {
                   3584:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3585:                                            $udom,$uname);
                   3586:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3587:         return %loadlangs;
                   3588:     }
                   3589: }
                   3590: 
                   3591: sub flush_langs_cache {
                   3592:     my ($uname,$udom)=@_;
                   3593:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3594:     if (!$uname) { $uname=$env{'user.name'};   }
                   3595:     return if ($udom eq 'public' && $uname eq 'public');
                   3596:     my $id=$uname.':'.$udom;
                   3597:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3598: }
                   3599: 
1.61      www      3600: # ------------------------------------------------------------------ Screenname
1.81      albertel 3601: 
                   3602: =pod
                   3603: 
1.648     raeburn  3604: =item * &screenname($uname,$udom)
1.81      albertel 3605: 
                   3606: Gets a users screenname and returns it as a string
                   3607: 
                   3608: =cut
1.61      www      3609: 
                   3610: sub screenname {
                   3611:     my ($uname,$udom)=@_;
1.258     albertel 3612:     if ($uname eq $env{'user.name'} &&
                   3613: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3614:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3615:     return $names{'screenname'};
1.62      www      3616: }
                   3617: 
1.212     albertel 3618: 
1.802     bisitz   3619: # ------------------------------------------------------------- Confirm Wrapper
                   3620: =pod
                   3621: 
1.1075.2.42  raeburn  3622: =item * &confirmwrapper($message)
1.802     bisitz   3623: 
                   3624: Wrap messages about completion of operation in box
                   3625: 
                   3626: =cut
                   3627: 
                   3628: sub confirmwrapper {
                   3629:     my ($message)=@_;
                   3630:     if ($message) {
                   3631:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3632:                .$message."\n"
                   3633:                .'</div>'."\n";
                   3634:     } else {
                   3635:         return $message;
                   3636:     }
                   3637: }
                   3638: 
1.62      www      3639: # ------------------------------------------------------------- Message Wrapper
                   3640: 
                   3641: sub messagewrapper {
1.369     www      3642:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3643:     return 
1.441     albertel 3644:         '<a href="/adm/email?compose=individual&amp;'.
                   3645:         'recname='.$username.'&amp;recdom='.$domain.
                   3646: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3647:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3648: }
1.802     bisitz   3649: 
1.74      www      3650: # --------------------------------------------------------------- Notes Wrapper
                   3651: 
                   3652: sub noteswrapper {
                   3653:     my ($link,$un,$do)=@_;
                   3654:     return 
1.896     amueller 3655: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3656: }
1.802     bisitz   3657: 
1.62      www      3658: # ------------------------------------------------------------- Aboutme Wrapper
                   3659: 
                   3660: sub aboutmewrapper {
1.1070    raeburn  3661:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3662:     if (!defined($username)  && !defined($domain)) {
                   3663:         return;
                   3664:     }
1.1075.2.15  raeburn  3665:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3666: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3667: }
                   3668: 
                   3669: # ------------------------------------------------------------ Syllabus Wrapper
                   3670: 
                   3671: sub syllabuswrapper {
1.707     bisitz   3672:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3673:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3674: }
1.14      harris41 3675: 
1.802     bisitz   3676: # -----------------------------------------------------------------------------
                   3677: 
1.208     matthew  3678: sub track_student_link {
1.887     raeburn  3679:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3680:     my $link ="/adm/trackstudent?";
1.208     matthew  3681:     my $title = 'View recent activity';
                   3682:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3683:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3684:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3685:         $title .= ' of this student';
1.268     albertel 3686:     } 
1.208     matthew  3687:     if (defined($target) && $target !~ /^\s*$/) {
                   3688:         $target = qq{target="$target"};
                   3689:     } else {
                   3690:         $target = '';
                   3691:     }
1.268     albertel 3692:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3693:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3694:     $title = &mt($title);
                   3695:     $linktext = &mt($linktext);
1.448     albertel 3696:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3697: 	&help_open_topic('View_recent_activity');
1.208     matthew  3698: }
                   3699: 
1.781     raeburn  3700: sub slot_reservations_link {
                   3701:     my ($linktext,$sname,$sdom,$target) = @_;
                   3702:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3703:     my $title = 'View slot reservation history';
                   3704:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3705:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3706:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3707:         $title .= ' of this student';
                   3708:     }
                   3709:     if (defined($target) && $target !~ /^\s*$/) {
                   3710:         $target = qq{target="$target"};
                   3711:     } else {
                   3712:         $target = '';
                   3713:     }
                   3714:     $title = &mt($title);
                   3715:     $linktext = &mt($linktext);
                   3716:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3717: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3718: 
                   3719: }
                   3720: 
1.508     www      3721: # ===================================================== Display a student photo
                   3722: 
                   3723: 
1.509     albertel 3724: sub student_image_tag {
1.508     www      3725:     my ($domain,$user)=@_;
                   3726:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3727:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3728: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3729:     } else {
                   3730: 	return '';
                   3731:     }
                   3732: }
                   3733: 
1.112     bowersj2 3734: =pod
                   3735: 
                   3736: =back
                   3737: 
                   3738: =head1 Access .tab File Data
                   3739: 
                   3740: =over 4
                   3741: 
1.648     raeburn  3742: =item * &languageids() 
1.112     bowersj2 3743: 
                   3744: returns list of all language ids
                   3745: 
                   3746: =cut
                   3747: 
1.14      harris41 3748: sub languageids {
1.16      harris41 3749:     return sort(keys(%language));
1.14      harris41 3750: }
                   3751: 
1.112     bowersj2 3752: =pod
                   3753: 
1.648     raeburn  3754: =item * &languagedescription() 
1.112     bowersj2 3755: 
                   3756: returns description of a specified language id
                   3757: 
                   3758: =cut
                   3759: 
1.14      harris41 3760: sub languagedescription {
1.125     www      3761:     my $code=shift;
                   3762:     return  ($supported_language{$code}?'* ':'').
                   3763:             $language{$code}.
1.126     www      3764: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3765: }
                   3766: 
1.1048    foxr     3767: =pod
                   3768: 
                   3769: =item * &plainlanguagedescription
                   3770: 
                   3771: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3772: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3773: 
                   3774: =cut
                   3775: 
1.145     www      3776: sub plainlanguagedescription {
                   3777:     my $code=shift;
                   3778:     return $language{$code};
                   3779: }
                   3780: 
1.1048    foxr     3781: =pod
                   3782: 
                   3783: =item * &supportedlanguagecode
                   3784: 
                   3785: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3786: code.
                   3787: 
                   3788: =cut
                   3789: 
1.145     www      3790: sub supportedlanguagecode {
                   3791:     my $code=shift;
                   3792:     return $supported_language{$code};
1.97      www      3793: }
                   3794: 
1.112     bowersj2 3795: =pod
                   3796: 
1.1048    foxr     3797: =item * &latexlanguage()
                   3798: 
                   3799: Given a language key code returns the correspondnig language to use
                   3800: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3801: is no supported hyphenation for the language code.
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub latexlanguage {
                   3806:     my $code = shift;
                   3807:     return $latex_language{$code};
                   3808: }
                   3809: 
                   3810: =pod
                   3811: 
                   3812: =item * &latexhyphenation()
                   3813: 
                   3814: Same as above but what's supplied is the language as it might be stored
                   3815: in the metadata.
                   3816: 
                   3817: =cut
                   3818: 
                   3819: sub latexhyphenation {
                   3820:     my $key = shift;
                   3821:     return $latex_language_bykey{$key};
                   3822: }
                   3823: 
                   3824: =pod
                   3825: 
1.648     raeburn  3826: =item * &copyrightids() 
1.112     bowersj2 3827: 
                   3828: returns list of all copyrights
                   3829: 
                   3830: =cut
                   3831: 
                   3832: sub copyrightids {
                   3833:     return sort(keys(%cprtag));
                   3834: }
                   3835: 
                   3836: =pod
                   3837: 
1.648     raeburn  3838: =item * &copyrightdescription() 
1.112     bowersj2 3839: 
                   3840: returns description of a specified copyright id
                   3841: 
                   3842: =cut
                   3843: 
                   3844: sub copyrightdescription {
1.166     www      3845:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3846: }
1.197     matthew  3847: 
                   3848: =pod
                   3849: 
1.648     raeburn  3850: =item * &source_copyrightids() 
1.192     taceyjo1 3851: 
                   3852: returns list of all source copyrights
                   3853: 
                   3854: =cut
                   3855: 
                   3856: sub source_copyrightids {
                   3857:     return sort(keys(%scprtag));
                   3858: }
                   3859: 
                   3860: =pod
                   3861: 
1.648     raeburn  3862: =item * &source_copyrightdescription() 
1.192     taceyjo1 3863: 
                   3864: returns description of a specified source copyright id
                   3865: 
                   3866: =cut
                   3867: 
                   3868: sub source_copyrightdescription {
                   3869:     return &mt($scprtag{shift(@_)});
                   3870: }
1.112     bowersj2 3871: 
                   3872: =pod
                   3873: 
1.648     raeburn  3874: =item * &filecategories() 
1.112     bowersj2 3875: 
                   3876: returns list of all file categories
                   3877: 
                   3878: =cut
                   3879: 
                   3880: sub filecategories {
                   3881:     return sort(keys(%category_extensions));
                   3882: }
                   3883: 
                   3884: =pod
                   3885: 
1.648     raeburn  3886: =item * &filecategorytypes() 
1.112     bowersj2 3887: 
                   3888: returns list of file types belonging to a given file
                   3889: category
                   3890: 
                   3891: =cut
                   3892: 
                   3893: sub filecategorytypes {
1.356     albertel 3894:     my ($cat) = @_;
                   3895:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3896: }
                   3897: 
                   3898: =pod
                   3899: 
1.648     raeburn  3900: =item * &fileembstyle() 
1.112     bowersj2 3901: 
                   3902: returns embedding style for a specified file type
                   3903: 
                   3904: =cut
                   3905: 
                   3906: sub fileembstyle {
                   3907:     return $fe{lc(shift(@_))};
1.169     www      3908: }
                   3909: 
1.351     www      3910: sub filemimetype {
                   3911:     return $fm{lc(shift(@_))};
                   3912: }
                   3913: 
1.169     www      3914: 
                   3915: sub filecategoryselect {
                   3916:     my ($name,$value)=@_;
1.189     matthew  3917:     return &select_form($value,$name,
1.970     raeburn  3918:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3919: }
                   3920: 
                   3921: =pod
                   3922: 
1.648     raeburn  3923: =item * &filedescription() 
1.112     bowersj2 3924: 
                   3925: returns description for a specified file type
                   3926: 
                   3927: =cut
                   3928: 
                   3929: sub filedescription {
1.188     matthew  3930:     my $file_description = $fd{lc(shift())};
                   3931:     $file_description =~ s:([\[\]]):~$1:g;
                   3932:     return &mt($file_description);
1.112     bowersj2 3933: }
                   3934: 
                   3935: =pod
                   3936: 
1.648     raeburn  3937: =item * &filedescriptionex() 
1.112     bowersj2 3938: 
                   3939: returns description for a specified file type with
                   3940: extra formatting
                   3941: 
                   3942: =cut
                   3943: 
                   3944: sub filedescriptionex {
                   3945:     my $ex=shift;
1.188     matthew  3946:     my $file_description = $fd{lc($ex)};
                   3947:     $file_description =~ s:([\[\]]):~$1:g;
                   3948:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3949: }
                   3950: 
                   3951: # End of .tab access
                   3952: =pod
                   3953: 
                   3954: =back
                   3955: 
                   3956: =cut
                   3957: 
                   3958: # ------------------------------------------------------------------ File Types
                   3959: sub fileextensions {
                   3960:     return sort(keys(%fe));
                   3961: }
                   3962: 
1.97      www      3963: # ----------------------------------------------------------- Display Languages
                   3964: # returns a hash with all desired display languages
                   3965: #
                   3966: 
                   3967: sub display_languages {
                   3968:     my %languages=();
1.695     raeburn  3969:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3970: 	$languages{$lang}=1;
1.97      www      3971:     }
                   3972:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3973:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3974: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3975: 	    $languages{$lang}=1;
1.97      www      3976:         }
                   3977:     }
                   3978:     return %languages;
1.14      harris41 3979: }
                   3980: 
1.582     albertel 3981: sub languages {
                   3982:     my ($possible_langs) = @_;
1.695     raeburn  3983:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3984:     if (!ref($possible_langs)) {
                   3985: 	if( wantarray ) {
                   3986: 	    return @preferred_langs;
                   3987: 	} else {
                   3988: 	    return $preferred_langs[0];
                   3989: 	}
                   3990:     }
                   3991:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3992:     my @preferred_possibilities;
                   3993:     foreach my $preferred_lang (@preferred_langs) {
                   3994: 	if (exists($possibilities{$preferred_lang})) {
                   3995: 	    push(@preferred_possibilities, $preferred_lang);
                   3996: 	}
                   3997:     }
                   3998:     if( wantarray ) {
                   3999: 	return @preferred_possibilities;
                   4000:     }
                   4001:     return $preferred_possibilities[0];
                   4002: }
                   4003: 
1.742     raeburn  4004: sub user_lang {
                   4005:     my ($touname,$toudom,$fromcid) = @_;
                   4006:     my @userlangs;
                   4007:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4008:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4009:                     $env{'course.'.$fromcid.'.languages'}));
                   4010:     } else {
                   4011:         my %langhash = &getlangs($touname,$toudom);
                   4012:         if ($langhash{'languages'} ne '') {
                   4013:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4014:         } else {
                   4015:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4016:             if ($domdefs{'lang_def'} ne '') {
                   4017:                 @userlangs = ($domdefs{'lang_def'});
                   4018:             }
                   4019:         }
                   4020:     }
                   4021:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4022:     my $user_lh = Apache::localize->get_handle(@languages);
                   4023:     return $user_lh;
                   4024: }
                   4025: 
                   4026: 
1.112     bowersj2 4027: ###############################################################
                   4028: ##               Student Answer Attempts                     ##
                   4029: ###############################################################
                   4030: 
                   4031: =pod
                   4032: 
                   4033: =head1 Alternate Problem Views
                   4034: 
                   4035: =over 4
                   4036: 
1.648     raeburn  4037: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4038:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4039: 
                   4040: Return string with previous attempt on problem. Arguments:
                   4041: 
                   4042: =over 4
                   4043: 
                   4044: =item * $symb: Problem, including path
                   4045: 
                   4046: =item * $username: username of the desired student
                   4047: 
                   4048: =item * $domain: domain of the desired student
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $course: Course ID
1.14      harris41 4051: 
1.112     bowersj2 4052: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4053:     something
1.14      harris41 4054: 
1.112     bowersj2 4055: =item * $regexp: if string matches this regexp, the string will be
                   4056:     sent to $gradesub
1.14      harris41 4057: 
1.112     bowersj2 4058: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4059: 
1.1075.2.86  raeburn  4060: =item * $usec: section of the desired student
                   4061: 
                   4062: =item * $identifier: counter for student (multiple students one problem) or
                   4063:     problem (one student; whole sequence).
                   4064: 
1.112     bowersj2 4065: =back
1.14      harris41 4066: 
1.112     bowersj2 4067: The output string is a table containing all desired attempts, if any.
1.16      harris41 4068: 
1.112     bowersj2 4069: =cut
1.1       albertel 4070: 
                   4071: sub get_previous_attempt {
1.1075.2.86  raeburn  4072:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4073:   my $prevattempts='';
1.43      ng       4074:   no strict 'refs';
1.1       albertel 4075:   if ($symb) {
1.3       albertel 4076:     my (%returnhash)=
                   4077:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4078:     if ($returnhash{'version'}) {
                   4079:       my %lasthash=();
                   4080:       my $version;
                   4081:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4082:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4083:             if ($key =~ /\.rawrndseed$/) {
                   4084:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4085:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4086:             } else {
                   4087:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4088:             }
1.19      harris41 4089:         }
1.1       albertel 4090:       }
1.596     albertel 4091:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4092:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4093:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4094:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4095:       foreach my $key (sort(keys(%lasthash))) {
                   4096: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4097: 	if ($#parts > 0) {
1.31      albertel 4098: 	  my $data=$parts[-1];
1.989     raeburn  4099:           next if ($data eq 'foilorder');
1.31      albertel 4100: 	  pop(@parts);
1.1010    www      4101:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4102:           if ($data eq 'type') {
                   4103:               unless ($showsurv) {
                   4104:                   my $id = join(',',@parts);
                   4105:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4106:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4107:                       $lasthidden{$ign.'.'.$id} = 1;
                   4108:                   }
1.945     raeburn  4109:               }
1.1075.2.86  raeburn  4110:               if ($identifier ne '') {
                   4111:                   my $id = join(',',@parts);
                   4112:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4113:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4114:                       $hidestatus{$ign.'.'.$id} = 1;
                   4115:                   }
                   4116:               }
                   4117:           } elsif ($data eq 'regrader') {
                   4118:               if (($identifier ne '') && (@parts)) {
                   4119:                   my $id = join(',',@parts);
                   4120:                   $regraded{$ign.'.'.$id} = 1;
                   4121:               }
1.1010    www      4122:           } 
1.31      albertel 4123: 	} else {
1.41      ng       4124: 	  if ($#parts == 0) {
                   4125: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4126: 	  } else {
                   4127: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4128: 	  }
1.31      albertel 4129: 	}
1.16      harris41 4130:       }
1.596     albertel 4131:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4132:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4133:         my (%solved,%resets,%probstatus);
                   4134:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4135:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4136:                 foreach my $id (keys(%regraded)) {
                   4137:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4138:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4139:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4140:                         push(@{$resets{$id}},$version);
                   4141:                     }
                   4142:                 }
                   4143:             }
                   4144:         }
1.40      ng       4145: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4146:             my (@hidden,@unsolved);
1.945     raeburn  4147:             if (%typeparts) {
                   4148:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4149:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4150:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4151:                         push(@hidden,$id);
1.1075.2.86  raeburn  4152:                     } elsif ($identifier ne '') {
                   4153:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4154:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4155:                                 ($hidestatus{$id})) {
                   4156:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4157:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4158:                                 push(@{$solved{$id}},$version);
                   4159:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4160:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4161:                                 my $skip;
                   4162:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4163:                                     foreach my $reset (@{$resets{$id}}) {
                   4164:                                         if ($reset > $solved{$id}[-1]) {
                   4165:                                             $skip=1;
                   4166:                                             last;
                   4167:                                         }
                   4168:                                     }
                   4169:                                 }
                   4170:                                 unless ($skip) {
                   4171:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4172:                                     push(@unsolved,$partslist);
                   4173:                                 }
                   4174:                             }
                   4175:                         }
1.945     raeburn  4176:                     }
                   4177:                 }
                   4178:             }
                   4179:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4180:                            '<td>'.&mt('Transaction [_1]',$version);
                   4181:             if (@unsolved) {
                   4182:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4183:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4184:                                  &mt('Hide').'</label></span>';
                   4185:             }
                   4186:             $prevattempts .= '</td>';
1.945     raeburn  4187:             if (@hidden) {
                   4188:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4189:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4190:                     my $hide;
                   4191:                     foreach my $id (@hidden) {
                   4192:                         if ($key =~ /^\Q$id\E/) {
                   4193:                             $hide = 1;
                   4194:                             last;
                   4195:                         }
                   4196:                     }
                   4197:                     if ($hide) {
                   4198:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4199:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4200:                             my $value = &format_previous_attempt_value($key,
                   4201:                                              $returnhash{$version.':'.$key});
                   4202:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4203:                         } else {
                   4204:                             $prevattempts.='<td>&nbsp;</td>';
                   4205:                         }
                   4206:                     } else {
                   4207:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4208:                             my $value = $returnhash{$version.':'.$key};
                   4209:                             if ($key =~ /\.rndseed$/) {
                   4210:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4211:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4212:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4213:                                 }
                   4214:                             }
                   4215:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4216:                                            '&nbsp;</td>';
1.945     raeburn  4217:                         } else {
                   4218:                             $prevattempts.='<td>&nbsp;</td>';
                   4219:                         }
                   4220:                     }
                   4221:                 }
                   4222:             } else {
                   4223: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4224:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4225:                     my $value = $returnhash{$version.':'.$key};
                   4226:                     if ($key =~ /\.rndseed$/) {
                   4227:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4228:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4229:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4230:                         }
                   4231:                     }
                   4232:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4233:                                    '&nbsp;</td>';
1.945     raeburn  4234: 	        }
                   4235:             }
                   4236: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4237: 	 }
1.1       albertel 4238:       }
1.945     raeburn  4239:       my @currhidden = keys(%lasthidden);
1.596     albertel 4240:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4241:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4242:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4243:           if (%typeparts) {
                   4244:               my $hidden;
                   4245:               foreach my $id (@currhidden) {
                   4246:                   if ($key =~ /^\Q$id\E/) {
                   4247:                       $hidden = 1;
                   4248:                       last;
                   4249:                   }
                   4250:               }
                   4251:               if ($hidden) {
                   4252:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4253:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4254:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4255:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4256:                           $value = &$gradesub($value);
                   4257:                       }
                   4258:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4259:                   } else {
                   4260:                       $prevattempts.='<td>&nbsp;</td>';
                   4261:                   }
                   4262:               } else {
                   4263:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4264:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4265:                       $value = &$gradesub($value);
                   4266:                   }
                   4267:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4268:               }
                   4269:           } else {
                   4270: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4271: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4272:                   $value = &$gradesub($value);
                   4273:               }
                   4274: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4275:           }
1.16      harris41 4276:       }
1.596     albertel 4277:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4278:     } else {
1.596     albertel 4279:       $prevattempts=
                   4280: 	  &start_data_table().&start_data_table_row().
                   4281: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4282: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4283:     }
                   4284:   } else {
1.596     albertel 4285:     $prevattempts=
                   4286: 	  &start_data_table().&start_data_table_row().
                   4287: 	  '<td>'.&mt('No data.').'</td>'.
                   4288: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4289:   }
1.10      albertel 4290: }
                   4291: 
1.581     albertel 4292: sub format_previous_attempt_value {
                   4293:     my ($key,$value) = @_;
1.1011    www      4294:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4295: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4296:     } elsif (ref($value) eq 'ARRAY') {
                   4297: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4298:     } elsif ($key =~ /answerstring$/) {
                   4299:         my %answers = &Apache::lonnet::str2hash($value);
                   4300:         my @anskeys = sort(keys(%answers));
                   4301:         if (@anskeys == 1) {
                   4302:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4303:             if ($answer =~ m{\0}) {
                   4304:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4305:             }
                   4306:             my $tag_internal_answer_name = 'INTERNAL';
                   4307:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4308:                 $value = $answer; 
                   4309:             } else {
                   4310:                 $value = $anskeys[0].'='.$answer;
                   4311:             }
                   4312:         } else {
                   4313:             foreach my $ans (@anskeys) {
                   4314:                 my $answer = $answers{$ans};
1.1001    raeburn  4315:                 if ($answer =~ m{\0}) {
                   4316:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4317:                 }
                   4318:                 $value .=  $ans.'='.$answer.'<br />';;
                   4319:             } 
                   4320:         }
1.581     albertel 4321:     } else {
                   4322: 	$value = &unescape($value);
                   4323:     }
                   4324:     return $value;
                   4325: }
                   4326: 
                   4327: 
1.107     albertel 4328: sub relative_to_absolute {
                   4329:     my ($url,$output)=@_;
                   4330:     my $parser=HTML::TokeParser->new(\$output);
                   4331:     my $token;
                   4332:     my $thisdir=$url;
                   4333:     my @rlinks=();
                   4334:     while ($token=$parser->get_token) {
                   4335: 	if ($token->[0] eq 'S') {
                   4336: 	    if ($token->[1] eq 'a') {
                   4337: 		if ($token->[2]->{'href'}) {
                   4338: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4339: 		}
                   4340: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4341: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4342: 	    } elsif ($token->[1] eq 'base') {
                   4343: 		$thisdir=$token->[2]->{'href'};
                   4344: 	    }
                   4345: 	}
                   4346:     }
                   4347:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4348:     foreach my $link (@rlinks) {
1.726     raeburn  4349: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4350: 		($link=~/^\//) ||
                   4351: 		($link=~/^javascript:/i) ||
                   4352: 		($link=~/^mailto:/i) ||
                   4353: 		($link=~/^\#/)) {
                   4354: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4355: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4356: 	}
                   4357:     }
                   4358: # -------------------------------------------------- Deal with Applet codebases
                   4359:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4360:     return $output;
                   4361: }
                   4362: 
1.112     bowersj2 4363: =pod
                   4364: 
1.648     raeburn  4365: =item * &get_student_view()
1.112     bowersj2 4366: 
                   4367: show a snapshot of what student was looking at
                   4368: 
                   4369: =cut
                   4370: 
1.10      albertel 4371: sub get_student_view {
1.186     albertel 4372:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4373:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4374:   my (%form);
1.10      albertel 4375:   my @elements=('symb','courseid','domain','username');
                   4376:   foreach my $element (@elements) {
1.186     albertel 4377:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4378:   }
1.186     albertel 4379:   if (defined($moreenv)) {
                   4380:       %form=(%form,%{$moreenv});
                   4381:   }
1.236     albertel 4382:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4383:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4384:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4385:   $userview=~s/\<body[^\>]*\>//gi;
                   4386:   $userview=~s/\<\/body\>//gi;
                   4387:   $userview=~s/\<html\>//gi;
                   4388:   $userview=~s/\<\/html\>//gi;
                   4389:   $userview=~s/\<head\>//gi;
                   4390:   $userview=~s/\<\/head\>//gi;
                   4391:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4392:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4393:   if (wantarray) {
                   4394:      return ($userview,$response);
                   4395:   } else {
                   4396:      return $userview;
                   4397:   }
                   4398: }
                   4399: 
                   4400: sub get_student_view_with_retries {
                   4401:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4402: 
                   4403:     my $ok = 0;                 # True if we got a good response.
                   4404:     my $content;
                   4405:     my $response;
                   4406: 
                   4407:     # Try to get the student_view done. within the retries count:
                   4408:     
                   4409:     do {
                   4410:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4411:          $ok      = $response->is_success;
                   4412:          if (!$ok) {
                   4413:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4414:          }
                   4415:          $retries--;
                   4416:     } while (!$ok && ($retries > 0));
                   4417:     
                   4418:     if (!$ok) {
                   4419:        $content = '';          # On error return an empty content.
                   4420:     }
1.651     www      4421:     if (wantarray) {
                   4422:        return ($content, $response);
                   4423:     } else {
                   4424:        return $content;
                   4425:     }
1.11      albertel 4426: }
                   4427: 
1.112     bowersj2 4428: =pod
                   4429: 
1.648     raeburn  4430: =item * &get_student_answers() 
1.112     bowersj2 4431: 
                   4432: show a snapshot of how student was answering problem
                   4433: 
                   4434: =cut
                   4435: 
1.11      albertel 4436: sub get_student_answers {
1.100     sakharuk 4437:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4438:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4439:   my (%moreenv);
1.11      albertel 4440:   my @elements=('symb','courseid','domain','username');
                   4441:   foreach my $element (@elements) {
1.186     albertel 4442:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4443:   }
1.186     albertel 4444:   $moreenv{'grade_target'}='answer';
                   4445:   %moreenv=(%form,%moreenv);
1.497     raeburn  4446:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4447:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4448:   return $userview;
1.1       albertel 4449: }
1.116     albertel 4450: 
                   4451: =pod
                   4452: 
                   4453: =item * &submlink()
                   4454: 
1.242     albertel 4455: Inputs: $text $uname $udom $symb $target
1.116     albertel 4456: 
                   4457: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4458: 
                   4459: =cut
                   4460: 
                   4461: ###############################################
                   4462: sub submlink {
1.242     albertel 4463:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4464:     if (!($uname && $udom)) {
                   4465: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4466: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4467: 	if (!$symb) { $symb=$cursymb; }
                   4468:     }
1.254     matthew  4469:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4470:     $symb=&escape($symb);
1.960     bisitz   4471:     if ($target) { $target=" target=\"$target\""; }
                   4472:     return
                   4473:         '<a href="/adm/grades?command=submission'.
                   4474:         '&amp;symb='.$symb.
                   4475:         '&amp;student='.$uname.
                   4476:         '&amp;userdom='.$udom.'"'.
                   4477:         $target.'>'.$text.'</a>';
1.242     albertel 4478: }
                   4479: ##############################################
                   4480: 
                   4481: =pod
                   4482: 
                   4483: =item * &pgrdlink()
                   4484: 
                   4485: Inputs: $text $uname $udom $symb $target
                   4486: 
                   4487: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4488: 
                   4489: =cut
                   4490: 
                   4491: ###############################################
                   4492: sub pgrdlink {
                   4493:     my $link=&submlink(@_);
                   4494:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4495:     return $link;
                   4496: }
                   4497: ##############################################
                   4498: 
                   4499: =pod
                   4500: 
                   4501: =item * &pprmlink()
                   4502: 
                   4503: Inputs: $text $uname $udom $symb $target
                   4504: 
                   4505: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4506: student and a specific resource
1.242     albertel 4507: 
                   4508: =cut
                   4509: 
                   4510: ###############################################
                   4511: sub pprmlink {
                   4512:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4513:     if (!($uname && $udom)) {
                   4514: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4515: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4516: 	if (!$symb) { $symb=$cursymb; }
                   4517:     }
1.254     matthew  4518:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4519:     $symb=&escape($symb);
1.242     albertel 4520:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4521:     return '<a href="/adm/parmset?command=set&amp;'.
                   4522: 	'symb='.$symb.'&amp;uname='.$uname.
                   4523: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4524: }
                   4525: ##############################################
1.37      matthew  4526: 
1.112     bowersj2 4527: =pod
                   4528: 
                   4529: =back
                   4530: 
                   4531: =cut
                   4532: 
1.37      matthew  4533: ###############################################
1.51      www      4534: 
                   4535: 
                   4536: sub timehash {
1.687     raeburn  4537:     my ($thistime) = @_;
                   4538:     my $timezone = &Apache::lonlocal::gettimezone();
                   4539:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4540:                      ->set_time_zone($timezone);
                   4541:     my $wday = $dt->day_of_week();
                   4542:     if ($wday == 7) { $wday = 0; }
                   4543:     return ( 'second' => $dt->second(),
                   4544:              'minute' => $dt->minute(),
                   4545:              'hour'   => $dt->hour(),
                   4546:              'day'     => $dt->day_of_month(),
                   4547:              'month'   => $dt->month(),
                   4548:              'year'    => $dt->year(),
                   4549:              'weekday' => $wday,
                   4550:              'dayyear' => $dt->day_of_year(),
                   4551:              'dlsav'   => $dt->is_dst() );
1.51      www      4552: }
                   4553: 
1.370     www      4554: sub utc_string {
                   4555:     my ($date)=@_;
1.371     www      4556:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4557: }
                   4558: 
1.51      www      4559: sub maketime {
                   4560:     my %th=@_;
1.687     raeburn  4561:     my ($epoch_time,$timezone,$dt);
                   4562:     $timezone = &Apache::lonlocal::gettimezone();
                   4563:     eval {
                   4564:         $dt = DateTime->new( year   => $th{'year'},
                   4565:                              month  => $th{'month'},
                   4566:                              day    => $th{'day'},
                   4567:                              hour   => $th{'hour'},
                   4568:                              minute => $th{'minute'},
                   4569:                              second => $th{'second'},
                   4570:                              time_zone => $timezone,
                   4571:                          );
                   4572:     };
                   4573:     if (!$@) {
                   4574:         $epoch_time = $dt->epoch;
                   4575:         if ($epoch_time) {
                   4576:             return $epoch_time;
                   4577:         }
                   4578:     }
1.51      www      4579:     return POSIX::mktime(
                   4580:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4581:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4582: }
                   4583: 
                   4584: #########################################
1.51      www      4585: 
                   4586: sub findallcourses {
1.482     raeburn  4587:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4588:     my %roles;
                   4589:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4590:     my %courses;
1.51      www      4591:     my $now=time;
1.482     raeburn  4592:     if (!defined($uname)) {
                   4593:         $uname = $env{'user.name'};
                   4594:     }
                   4595:     if (!defined($udom)) {
                   4596:         $udom = $env{'user.domain'};
                   4597:     }
                   4598:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4599:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4600:         if (!%roles) {
                   4601:             %roles = (
                   4602:                        cc => 1,
1.907     raeburn  4603:                        co => 1,
1.482     raeburn  4604:                        in => 1,
                   4605:                        ep => 1,
                   4606:                        ta => 1,
                   4607:                        cr => 1,
                   4608:                        st => 1,
                   4609:              );
                   4610:         }
                   4611:         foreach my $entry (keys(%roleshash)) {
                   4612:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4613:             if ($trole =~ /^cr/) { 
                   4614:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4615:             } else {
                   4616:                 next if (!exists($roles{$trole}));
                   4617:             }
                   4618:             if ($tend) {
                   4619:                 next if ($tend < $now);
                   4620:             }
                   4621:             if ($tstart) {
                   4622:                 next if ($tstart > $now);
                   4623:             }
1.1058    raeburn  4624:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4625:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4626:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4627:             if ($secpart eq '') {
                   4628:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4629:                 $sec = 'none';
1.1058    raeburn  4630:                 $value .= $cnum.'/';
1.482     raeburn  4631:             } else {
                   4632:                 $cnum = $cnumpart;
                   4633:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4634:                 $value .= $cnum.'/'.$sec;
                   4635:             }
                   4636:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4637:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4638:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4639:                 }
                   4640:             } else {
                   4641:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4642:             }
1.482     raeburn  4643:         }
                   4644:     } else {
                   4645:         foreach my $key (keys(%env)) {
1.483     albertel 4646: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4647:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4648: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4649: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4650: 	        next if (%roles && !exists($roles{$role}));
                   4651: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4652:                 my $active=1;
                   4653:                 if ($starttime) {
                   4654: 		    if ($now<$starttime) { $active=0; }
                   4655:                 }
                   4656:                 if ($endtime) {
                   4657:                     if ($now>$endtime) { $active=0; }
                   4658:                 }
                   4659:                 if ($active) {
1.1058    raeburn  4660:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4661:                     if ($sec eq '') {
                   4662:                         $sec = 'none';
1.1058    raeburn  4663:                     } else {
                   4664:                         $value .= $sec;
                   4665:                     }
                   4666:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4667:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4668:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4669:                         }
                   4670:                     } else {
                   4671:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4672:                     }
1.474     raeburn  4673:                 }
                   4674:             }
1.51      www      4675:         }
                   4676:     }
1.474     raeburn  4677:     return %courses;
1.51      www      4678: }
1.37      matthew  4679: 
1.54      www      4680: ###############################################
1.474     raeburn  4681: 
                   4682: sub blockcheck {
1.1075.2.73  raeburn  4683:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4684: 
1.1075.2.73  raeburn  4685:     if (defined($udom) && defined($uname)) {
                   4686:         # If uname and udom are for a course, check for blocks in the course.
                   4687:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4688:             my ($startblock,$endblock,$triggerblock) =
                   4689:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4690:             return ($startblock,$endblock,$triggerblock);
                   4691:         }
                   4692:     } else {
1.490     raeburn  4693:         $udom = $env{'user.domain'};
                   4694:         $uname = $env{'user.name'};
                   4695:     }
                   4696: 
1.502     raeburn  4697:     my $startblock = 0;
                   4698:     my $endblock = 0;
1.1062    raeburn  4699:     my $triggerblock = '';
1.482     raeburn  4700:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4701: 
1.490     raeburn  4702:     # If uname is for a user, and activity is course-specific, i.e.,
                   4703:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4704: 
1.490     raeburn  4705:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.141.  .6(raebu 4706:20):          $activity eq 'groups' || $activity eq 'printout' ||
                   4707:20):          $activity eq 'reinit' || $activity eq 'alert') &&
1.1075.2.73  raeburn  4708:         ($env{'request.course.id'})) {
1.490     raeburn  4709:         foreach my $key (keys(%live_courses)) {
                   4710:             if ($key ne $env{'request.course.id'}) {
                   4711:                 delete($live_courses{$key});
                   4712:             }
                   4713:         }
                   4714:     }
                   4715: 
                   4716:     my $otheruser = 0;
                   4717:     my %own_courses;
                   4718:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4719:         # Resource belongs to user other than current user.
                   4720:         $otheruser = 1;
                   4721:         # Gather courses for current user
                   4722:         %own_courses = 
                   4723:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4724:     }
                   4725: 
                   4726:     # Gather active course roles - course coordinator, instructor, 
                   4727:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4728: 
                   4729:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4730:         my ($cdom,$cnum);
                   4731:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4732:             $cdom = $env{'course.'.$course.'.domain'};
                   4733:             $cnum = $env{'course.'.$course.'.num'};
                   4734:         } else {
1.490     raeburn  4735:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4736:         }
                   4737:         my $no_ownblock = 0;
                   4738:         my $no_userblock = 0;
1.533     raeburn  4739:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4740:             # Check if current user has 'evb' priv for this
                   4741:             if (defined($own_courses{$course})) {
                   4742:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4743:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4744:                     if ($sec ne 'none') {
                   4745:                         $checkrole .= '/'.$sec;
                   4746:                     }
                   4747:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4748:                         $no_ownblock = 1;
                   4749:                         last;
                   4750:                     }
                   4751:                 }
                   4752:             }
                   4753:             # if they have 'evb' priv and are currently not playing student
                   4754:             next if (($no_ownblock) &&
                   4755:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4756:         }
1.474     raeburn  4757:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4758:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4759:             if ($sec ne 'none') {
1.482     raeburn  4760:                 $checkrole .= '/'.$sec;
1.474     raeburn  4761:             }
1.490     raeburn  4762:             if ($otheruser) {
                   4763:                 # Resource belongs to user other than current user.
                   4764:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4765:                 my (%allroles,%userroles);
                   4766:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4767:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4768:                         my ($trole,$tdom,$tnum,$tsec);
                   4769:                         if ($entry =~ /^cr/) {
                   4770:                             ($trole,$tdom,$tnum,$tsec) = 
                   4771:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4772:                         } else {
                   4773:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4774:                         }
                   4775:                         my ($spec,$area,$trest);
                   4776:                         $area = '/'.$tdom.'/'.$tnum;
                   4777:                         $trest = $tnum;
                   4778:                         if ($tsec ne '') {
                   4779:                             $area .= '/'.$tsec;
                   4780:                             $trest .= '/'.$tsec;
                   4781:                         }
                   4782:                         $spec = $trole.'.'.$area;
                   4783:                         if ($trole =~ /^cr/) {
                   4784:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4785:                                                               $tdom,$spec,$trest,$area);
                   4786:                         } else {
                   4787:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4788:                                                                 $tdom,$spec,$trest,$area);
                   4789:                         }
                   4790:                     }
1.1075.2.124  raeburn  4791:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4792:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4793:                         if ($1) {
                   4794:                             $no_userblock = 1;
                   4795:                             last;
                   4796:                         }
1.486     raeburn  4797:                     }
                   4798:                 }
1.490     raeburn  4799:             } else {
                   4800:                 # Resource belongs to current user
                   4801:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4802:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4803:                     $no_ownblock = 1;
                   4804:                     last;
                   4805:                 }
1.474     raeburn  4806:             }
                   4807:         }
                   4808:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4809:         next if (($no_ownblock) &&
1.491     albertel 4810:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4811:         next if ($no_userblock);
1.474     raeburn  4812: 
1.1075.2.128  raeburn  4813:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4814:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4815:         
1.1062    raeburn  4816:         my ($start,$end,$trigger) = 
                   4817:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4818:         if (($start != 0) && 
                   4819:             (($startblock == 0) || ($startblock > $start))) {
                   4820:             $startblock = $start;
1.1062    raeburn  4821:             if ($trigger ne '') {
                   4822:                 $triggerblock = $trigger;
                   4823:             }
1.502     raeburn  4824:         }
                   4825:         if (($end != 0)  &&
                   4826:             (($endblock == 0) || ($endblock < $end))) {
                   4827:             $endblock = $end;
1.1062    raeburn  4828:             if ($trigger ne '') {
                   4829:                 $triggerblock = $trigger;
                   4830:             }
1.502     raeburn  4831:         }
1.490     raeburn  4832:     }
1.1062    raeburn  4833:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4834: }
                   4835: 
                   4836: sub get_blocks {
1.1062    raeburn  4837:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4838:     my $startblock = 0;
                   4839:     my $endblock = 0;
1.1062    raeburn  4840:     my $triggerblock = '';
1.490     raeburn  4841:     my $course = $cdom.'_'.$cnum;
                   4842:     $setters->{$course} = {};
                   4843:     $setters->{$course}{'staff'} = [];
                   4844:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4845:     $setters->{$course}{'triggers'} = [];
                   4846:     my (@blockers,%triggered);
                   4847:     my $now = time;
                   4848:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4849:     if ($activity eq 'docs') {
                   4850:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4851:         foreach my $block (@blockers) {
                   4852:             if ($block =~ /^firstaccess____(.+)$/) {
                   4853:                 my $item = $1;
                   4854:                 my $type = 'map';
                   4855:                 my $timersymb = $item;
                   4856:                 if ($item eq 'course') {
                   4857:                     $type = 'course';
                   4858:                 } elsif ($item =~ /___\d+___/) {
                   4859:                     $type = 'resource';
                   4860:                 } else {
                   4861:                     $timersymb = &Apache::lonnet::symbread($item);
                   4862:                 }
                   4863:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4864:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4865:                 $triggered{$block} = {
                   4866:                                        start => $start,
                   4867:                                        end   => $end,
                   4868:                                        type  => $type,
                   4869:                                      };
                   4870:             }
                   4871:         }
                   4872:     } else {
                   4873:         foreach my $block (keys(%commblocks)) {
                   4874:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4875:                 my ($start,$end) = ($1,$2);
                   4876:                 if ($start <= time && $end >= time) {
                   4877:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4878:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4879:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4880:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4881:                                     push(@blockers,$block);
                   4882:                                 }
                   4883:                             }
                   4884:                         }
                   4885:                     }
                   4886:                 }
                   4887:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4888:                 my $item = $1;
                   4889:                 my $timersymb = $item; 
                   4890:                 my $type = 'map';
                   4891:                 if ($item eq 'course') {
                   4892:                     $type = 'course';
                   4893:                 } elsif ($item =~ /___\d+___/) {
                   4894:                     $type = 'resource';
                   4895:                 } else {
                   4896:                     $timersymb = &Apache::lonnet::symbread($item);
                   4897:                 }
                   4898:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4899:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4900:                 if ($start && $end) {
                   4901:                     if (($start <= time) && ($end >= time)) {
                   4902:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4903:                             push(@blockers,$block);
                   4904:                             $triggered{$block} = {
                   4905:                                                    start => $start,
                   4906:                                                    end   => $end,
                   4907:                                                    type  => $type,
                   4908:                                                  };
                   4909:                         }
                   4910:                     }
1.490     raeburn  4911:                 }
1.1062    raeburn  4912:             }
                   4913:         }
                   4914:     }
                   4915:     foreach my $blocker (@blockers) {
                   4916:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4917:             &parse_block_record($commblocks{$blocker});
                   4918:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4919:         my ($start,$end,$triggertype);
                   4920:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4921:             ($start,$end) = ($1,$2);
                   4922:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4923:             $start = $triggered{$blocker}{'start'};
                   4924:             $end = $triggered{$blocker}{'end'};
                   4925:             $triggertype = $triggered{$blocker}{'type'};
                   4926:         }
                   4927:         if ($start) {
                   4928:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4929:             if ($triggertype) {
                   4930:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4931:             } else {
                   4932:                 push(@{$$setters{$course}{'triggers'}},0);
                   4933:             }
                   4934:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4935:                 $startblock = $start;
                   4936:                 if ($triggertype) {
                   4937:                     $triggerblock = $blocker;
1.474     raeburn  4938:                 }
                   4939:             }
1.1062    raeburn  4940:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4941:                $endblock = $end;
                   4942:                if ($triggertype) {
                   4943:                    $triggerblock = $blocker;
                   4944:                }
                   4945:             }
1.474     raeburn  4946:         }
                   4947:     }
1.1062    raeburn  4948:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4949: }
                   4950: 
                   4951: sub parse_block_record {
                   4952:     my ($record) = @_;
                   4953:     my ($setuname,$setudom,$title,$blocks);
                   4954:     if (ref($record) eq 'HASH') {
                   4955:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4956:         $title = &unescape($record->{'event'});
                   4957:         $blocks = $record->{'blocks'};
                   4958:     } else {
                   4959:         my @data = split(/:/,$record,3);
                   4960:         if (scalar(@data) eq 2) {
                   4961:             $title = $data[1];
                   4962:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4963:         } else {
                   4964:             ($setuname,$setudom,$title) = @data;
                   4965:         }
                   4966:         $blocks = { 'com' => 'on' };
                   4967:     }
                   4968:     return ($setuname,$setudom,$title,$blocks);
                   4969: }
                   4970: 
1.854     kalberla 4971: sub blocking_status {
1.1075.2.73  raeburn  4972:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4973:     my %setters;
1.890     droeschl 4974: 
1.1061    raeburn  4975: # check for active blocking
1.1062    raeburn  4976:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4977:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4978:     my $blocked = 0;
                   4979:     if ($startblock && $endblock) {
                   4980:         $blocked = 1;
                   4981:     }
1.890     droeschl 4982: 
1.1061    raeburn  4983: # caller just wants to know whether a block is active
                   4984:     if (!wantarray) { return $blocked; }
                   4985: 
                   4986: # build a link to a popup window containing the details
                   4987:     my $querystring  = "?activity=$activity";
                   4988: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4989:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4990:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4991:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4992:     } elsif ($activity eq 'docs') {
                   4993:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4994:     }
1.1061    raeburn  4995: 
                   4996:     my $output .= <<'END_MYBLOCK';
                   4997: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4998:     var options = "width=" + w + ",height=" + h + ",";
                   4999:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5000:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5001:     var newWin = window.open(url, wdwName, options);
                   5002:     newWin.focus();
                   5003: }
1.890     droeschl 5004: END_MYBLOCK
1.854     kalberla 5005: 
1.1061    raeburn  5006:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5007:   
1.1061    raeburn  5008:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5009:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5010:     my $class = 'LC_comblock';
1.1062    raeburn  5011:     if ($activity eq 'docs') {
                   5012:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5013:         $class = '';
1.1063    raeburn  5014:     } elsif ($activity eq 'printout') {
                   5015:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5016:     } elsif ($activity eq 'passwd') {
                   5017:         $text = &mt('Password Changing Blocked');
1.1075.2.141.  .6(raebu 5018:20):     } elsif ($activity eq 'grades') {
                   5019:20):         $text = &mt('Gradebook Blocked');
                   5020:20):     } elsif ($activity eq 'alert') {
                   5021:20):         $text = &mt('Checking Critical Messages Blocked');
                   5022:20):     } elsif ($activity eq 'reinit') {
                   5023:20):         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5024:     }
1.1061    raeburn  5025:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5026: <div class='$class'>
1.869     kalberla 5027:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5028:   title='$text'>
                   5029:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5030:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5031:   title='$text'>$text</a>
1.867     kalberla 5032: </div>
                   5033: 
                   5034: END_BLOCK
1.474     raeburn  5035: 
1.1061    raeburn  5036:     return ($blocked, $output);
1.854     kalberla 5037: }
1.490     raeburn  5038: 
1.60      matthew  5039: ###############################################
                   5040: 
1.682     raeburn  5041: sub check_ip_acc {
1.1075.2.105  raeburn  5042:     my ($acc,$clientip)=@_;
1.682     raeburn  5043:     &Apache::lonxml::debug("acc is $acc");
                   5044:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5045:         return 1;
                   5046:     }
1.1075.2.141.  .4(raebu 5047:20):     my ($ip,$allowed);
                   5048:20):     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5049:20):         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5050:20):         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5051:20):     } else {
                   5052:20):         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5053:20):     }
1.682     raeburn  5054: 
                   5055:     my $name;
1.1075.2.141.  .1(raebu 5056:20):     my %access = (
                   5057:20):                      allowfrom => 1,
                   5058:20):                      denyfrom  => 0,
                   5059:20):                  );
                   5060:20):     my @allows;
                   5061:20):     my @denies;
                   5062:20):     foreach my $item (split(',',$acc)) {
                   5063:20):         $item =~ s/^\s*//;
                   5064:20):         $item =~ s/\s*$//;
                   5065:20):         if ($item =~ /^\!(.+)$/) {
                   5066:20):             push(@denies,$1);
                   5067:20):         } else {
                   5068:20):             push(@allows,$item);
                   5069:20):         }
                   5070:20):     }
                   5071:20):     my $numdenies = scalar(@denies);
                   5072:20):     my $numallows = scalar(@allows);
                   5073:20):     my $count = 0;
                   5074:20):     foreach my $pattern (@denies,@allows) {
                   5075:20):         $count ++;
                   5076:20):         my $acctype = 'allowfrom';
                   5077:20):         if ($count <= $numdenies) {
                   5078:20):             $acctype = 'denyfrom';
                   5079:20):         }
1.682     raeburn  5080:         if ($pattern =~ /\*$/) {
                   5081:             #35.8.*
                   5082:             $pattern=~s/\*//;
1.1075.2.141.  .1(raebu 5083:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5084:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5085:             #35.8.3.[34-56]
                   5086:             my $low=$2;
                   5087:             my $high=$3;
                   5088:             $pattern=$1;
                   5089:             if ($ip =~ /^\Q$pattern\E/) {
                   5090:                 my $last=(split(/\./,$ip))[3];
1.1075.2.141.  .1(raebu 5091:20):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5092:             }
                   5093:         } elsif ($pattern =~ /^\*/) {
                   5094:             #*.msu.edu
                   5095:             $pattern=~s/\*//;
                   5096:             if (!defined($name)) {
                   5097:                 use Socket;
                   5098:                 my $netaddr=inet_aton($ip);
                   5099:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5100:             }
1.1075.2.141.  .1(raebu 5101:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5102:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5103:             #127.0.0.1
1.1075.2.141.  .1(raebu 5104:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5105:         } else {
                   5106:             #some.name.com
                   5107:             if (!defined($name)) {
                   5108:                 use Socket;
                   5109:                 my $netaddr=inet_aton($ip);
                   5110:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5111:             }
1.1075.2.141.  .1(raebu 5112:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5113:20):         }
                   5114:20):         if ($allowed =~ /^(0|1)$/) { last; }
                   5115:20):     }
                   5116:20):     if ($allowed eq '') {
                   5117:20):         if ($numdenies && !$numallows) {
                   5118:20):             $allowed = 1;
                   5119:20):         } else {
                   5120:20):             $allowed = 0;
1.682     raeburn  5121:         }
                   5122:     }
                   5123:     return $allowed;
                   5124: }
                   5125: 
                   5126: ###############################################
                   5127: 
1.60      matthew  5128: =pod
                   5129: 
1.112     bowersj2 5130: =head1 Domain Template Functions
                   5131: 
                   5132: =over 4
                   5133: 
                   5134: =item * &determinedomain()
1.60      matthew  5135: 
                   5136: Inputs: $domain (usually will be undef)
                   5137: 
1.63      www      5138: Returns: Determines which domain should be used for designs
1.60      matthew  5139: 
                   5140: =cut
1.54      www      5141: 
1.60      matthew  5142: ###############################################
1.63      www      5143: sub determinedomain {
                   5144:     my $domain=shift;
1.531     albertel 5145:     if (! $domain) {
1.60      matthew  5146:         # Determine domain if we have not been given one
1.893     raeburn  5147:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5148:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5149:         if ($env{'request.role.domain'}) { 
                   5150:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5151:         }
                   5152:     }
1.63      www      5153:     return $domain;
                   5154: }
                   5155: ###############################################
1.517     raeburn  5156: 
1.518     albertel 5157: sub devalidate_domconfig_cache {
                   5158:     my ($udom)=@_;
                   5159:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5160: }
                   5161: 
                   5162: # ---------------------- Get domain configuration for a domain
                   5163: sub get_domainconf {
                   5164:     my ($udom) = @_;
                   5165:     my $cachetime=1800;
                   5166:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5167:     if (defined($cached)) { return %{$result}; }
                   5168: 
                   5169:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5170: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5171:     my (%designhash,%legacy);
1.518     albertel 5172:     if (keys(%domconfig) > 0) {
                   5173:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5174:             if (keys(%{$domconfig{'login'}})) {
                   5175:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5176:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5177:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5178:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5179:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5180:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5181:                                         if ($key eq 'loginvia') {
                   5182:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5183:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5184:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5185:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5186:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5187:                                                 } else {
                   5188:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5189:                                                 }
1.948     raeburn  5190:                                             }
1.1075.2.87  raeburn  5191:                                         } elsif ($key eq 'headtag') {
                   5192:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5193:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5194:                                             }
1.946     raeburn  5195:                                         }
1.1075.2.87  raeburn  5196:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5197:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5198:                                         }
1.946     raeburn  5199:                                     }
                   5200:                                 }
                   5201:                             }
                   5202:                         } else {
                   5203:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5204:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5205:                                     $domconfig{'login'}{$key}{$img};
                   5206:                             }
1.699     raeburn  5207:                         }
                   5208:                     } else {
                   5209:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5210:                     }
1.632     raeburn  5211:                 }
                   5212:             } else {
                   5213:                 $legacy{'login'} = 1;
1.518     albertel 5214:             }
1.632     raeburn  5215:         } else {
                   5216:             $legacy{'login'} = 1;
1.518     albertel 5217:         }
                   5218:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5219:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5220:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5221:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5222:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5223:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5224:                         }
1.518     albertel 5225:                     }
                   5226:                 }
1.632     raeburn  5227:             } else {
                   5228:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5229:             }
1.632     raeburn  5230:         } else {
                   5231:             $legacy{'rolecolors'} = 1;
1.518     albertel 5232:         }
1.948     raeburn  5233:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5234:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5235:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5236:             }
                   5237:         }
1.632     raeburn  5238:         if (keys(%legacy) > 0) {
                   5239:             my %legacyhash = &get_legacy_domconf($udom);
                   5240:             foreach my $item (keys(%legacyhash)) {
                   5241:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5242:                     if ($legacy{'login'}) { 
                   5243:                         $designhash{$item} = $legacyhash{$item};
                   5244:                     }
                   5245:                 } else {
                   5246:                     if ($legacy{'rolecolors'}) {
                   5247:                         $designhash{$item} = $legacyhash{$item};
                   5248:                     }
1.518     albertel 5249:                 }
                   5250:             }
                   5251:         }
1.632     raeburn  5252:     } else {
                   5253:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5254:     }
                   5255:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5256: 				  $cachetime);
                   5257:     return %designhash;
                   5258: }
                   5259: 
1.632     raeburn  5260: sub get_legacy_domconf {
                   5261:     my ($udom) = @_;
                   5262:     my %legacyhash;
                   5263:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5264:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5265:     if (-e $designfile) {
1.1075.2.128  raeburn  5266:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5267:             while (my $line = <$fh>) {
                   5268:                 next if ($line =~ /^\#/);
                   5269:                 chomp($line);
                   5270:                 my ($key,$val)=(split(/\=/,$line));
                   5271:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5272:             }
                   5273:             close($fh);
                   5274:         }
                   5275:     }
1.1026    raeburn  5276:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5277:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5278:     }
                   5279:     return %legacyhash;
                   5280: }
                   5281: 
1.63      www      5282: =pod
                   5283: 
1.112     bowersj2 5284: =item * &domainlogo()
1.63      www      5285: 
                   5286: Inputs: $domain (usually will be undef)
                   5287: 
                   5288: Returns: A link to a domain logo, if the domain logo exists.
                   5289: If the domain logo does not exist, a description of the domain.
                   5290: 
                   5291: =cut
1.112     bowersj2 5292: 
1.63      www      5293: ###############################################
                   5294: sub domainlogo {
1.517     raeburn  5295:     my $domain = &determinedomain(shift);
1.518     albertel 5296:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5297:     # See if there is a logo
                   5298:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5299:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5300:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5301: 	    if ($imgsrc =~ m{^/res/}) {
                   5302: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5303: 		&Apache::lonnet::repcopy($local_name);
                   5304: 	    }
                   5305: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5306:         } 
                   5307:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5308:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5309:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5310:     } else {
1.60      matthew  5311:         return '';
1.59      www      5312:     }
                   5313: }
1.63      www      5314: ##############################################
                   5315: 
                   5316: =pod
                   5317: 
1.112     bowersj2 5318: =item * &designparm()
1.63      www      5319: 
                   5320: Inputs: $which parameter; $domain (usually will be undef)
                   5321: 
                   5322: Returns: value of designparamter $which
                   5323: 
                   5324: =cut
1.112     bowersj2 5325: 
1.397     albertel 5326: 
1.400     albertel 5327: ##############################################
1.397     albertel 5328: sub designparm {
                   5329:     my ($which,$domain)=@_;
                   5330:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5331:         return $env{'environment.color.'.$which};
1.96      www      5332:     }
1.63      www      5333:     $domain=&determinedomain($domain);
1.1016    raeburn  5334:     my %domdesign;
                   5335:     unless ($domain eq 'public') {
                   5336:         %domdesign = &get_domainconf($domain);
                   5337:     }
1.520     raeburn  5338:     my $output;
1.517     raeburn  5339:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5340:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5341:     } else {
1.520     raeburn  5342:         $output = $defaultdesign{$which};
                   5343:     }
                   5344:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5345:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5346:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5347:             if ($output =~ m{^/res/}) {
                   5348:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5349:                 &Apache::lonnet::repcopy($local_name);
                   5350:             }
1.520     raeburn  5351:             $output = &lonhttpdurl($output);
                   5352:         }
1.63      www      5353:     }
1.520     raeburn  5354:     return $output;
1.63      www      5355: }
1.59      www      5356: 
1.822     bisitz   5357: ##############################################
                   5358: =pod
                   5359: 
1.832     bisitz   5360: =item * &authorspace()
                   5361: 
1.1028    raeburn  5362: Inputs: $url (usually will be undef).
1.832     bisitz   5363: 
1.1075.2.40  raeburn  5364: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5365:          directory being viewed (or for which action is being taken). 
                   5366:          If $url is provided, and begins /priv/<domain>/<uname>
                   5367:          the path will be that portion of the $context argument.
                   5368:          Otherwise the path will be for the author space of the current
                   5369:          user when the current role is author, or for that of the 
                   5370:          co-author/assistant co-author space when the current role 
                   5371:          is co-author or assistant co-author.
1.832     bisitz   5372: 
                   5373: =cut
                   5374: 
                   5375: sub authorspace {
1.1028    raeburn  5376:     my ($url) = @_;
                   5377:     if ($url ne '') {
                   5378:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5379:            return $1;
                   5380:         }
                   5381:     }
1.832     bisitz   5382:     my $caname = '';
1.1024    www      5383:     my $cadom = '';
1.1028    raeburn  5384:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5385:         ($cadom,$caname) =
1.832     bisitz   5386:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5387:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5388:         $caname = $env{'user.name'};
1.1024    www      5389:         $cadom = $env{'user.domain'};
1.832     bisitz   5390:     }
1.1028    raeburn  5391:     if (($caname ne '') && ($cadom ne '')) {
                   5392:         return "/priv/$cadom/$caname/";
                   5393:     }
                   5394:     return;
1.832     bisitz   5395: }
                   5396: 
                   5397: ##############################################
                   5398: =pod
                   5399: 
1.822     bisitz   5400: =item * &head_subbox()
                   5401: 
                   5402: Inputs: $content (contains HTML code with page functions, etc.)
                   5403: 
                   5404: Returns: HTML div with $content
                   5405:          To be included in page header
                   5406: 
                   5407: =cut
                   5408: 
                   5409: sub head_subbox {
                   5410:     my ($content)=@_;
                   5411:     my $output =
1.993     raeburn  5412:         '<div class="LC_head_subbox">'
1.822     bisitz   5413:        .$content
                   5414:        .'</div>'
                   5415: }
                   5416: 
                   5417: ##############################################
                   5418: =pod
                   5419: 
                   5420: =item * &CSTR_pageheader()
                   5421: 
1.1026    raeburn  5422: Input: (optional) filename from which breadcrumb trail is built.
                   5423:        In most cases no input as needed, as $env{'request.filename'}
                   5424:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5425: 
                   5426: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5427:          To be included on Authoring Space pages
1.822     bisitz   5428: 
                   5429: =cut
                   5430: 
                   5431: sub CSTR_pageheader {
1.1026    raeburn  5432:     my ($trailfile) = @_;
                   5433:     if ($trailfile eq '') {
                   5434:         $trailfile = $env{'request.filename'};
                   5435:     }
                   5436: 
                   5437: # this is for resources; directories have customtitle, and crumbs
                   5438: # and select recent are created in lonpubdir.pm
                   5439: 
                   5440:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5441:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5442:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5443:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5444:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5445: 
                   5446:     my $parentpath = '';
                   5447:     my $lastitem = '';
                   5448:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5449:         $parentpath = $1;
                   5450:         $lastitem = $2;
                   5451:     } else {
                   5452:         $lastitem = $thisdisfn;
                   5453:     }
1.921     bisitz   5454: 
                   5455:     my $output =
1.822     bisitz   5456:          '<div>'
                   5457:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5458:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5459:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5460:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5461:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5462: 
                   5463:     if ($lastitem) {
                   5464:         $output .=
                   5465:              '<span class="LC_filename">'
                   5466:             .$lastitem
                   5467:             .'</span>';
                   5468:     }
                   5469:     $output .=
                   5470:          '<br />'
1.822     bisitz   5471:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5472:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5473:         .'</form>'
                   5474:         .&Apache::lonmenu::constspaceform()
                   5475:         .'</div>';
1.921     bisitz   5476: 
                   5477:     return $output;
1.822     bisitz   5478: }
                   5479: 
1.60      matthew  5480: ###############################################
                   5481: ###############################################
                   5482: 
                   5483: =pod
                   5484: 
1.112     bowersj2 5485: =back
                   5486: 
1.549     albertel 5487: =head1 HTML Helpers
1.112     bowersj2 5488: 
                   5489: =over 4
                   5490: 
                   5491: =item * &bodytag()
1.60      matthew  5492: 
                   5493: Returns a uniform header for LON-CAPA web pages.
                   5494: 
                   5495: Inputs: 
                   5496: 
1.112     bowersj2 5497: =over 4
                   5498: 
                   5499: =item * $title, A title to be displayed on the page.
                   5500: 
                   5501: =item * $function, the current role (can be undef).
                   5502: 
                   5503: =item * $addentries, extra parameters for the <body> tag.
                   5504: 
                   5505: =item * $bodyonly, if defined, only return the <body> tag.
                   5506: 
                   5507: =item * $domain, if defined, force a given domain.
                   5508: 
                   5509: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5510:             text interface only)
1.60      matthew  5511: 
1.814     bisitz   5512: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5513:                      navigational links
1.317     albertel 5514: 
1.338     albertel 5515: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5516: 
1.1075.2.12  raeburn  5517: =item * $no_inline_link, if true and in remote mode, don't show the
                   5518:          'Switch To Inline Menu' link
                   5519: 
1.460     albertel 5520: =item * $args, optional argument valid values are
                   5521:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5522:             use_absolute     -> for external resource or syllabus, this will
                   5523:                                 contain https://<hostname> if server uses
                   5524:                                 https (as per hosts.tab), but request is for http
                   5525:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5526: 
1.1075.2.15  raeburn  5527: =item * $advtoolsref, optional argument, ref to an array containing
                   5528:             inlineremote items to be added in "Functions" menu below
                   5529:             breadcrumbs.
                   5530: 
1.112     bowersj2 5531: =back
                   5532: 
1.60      matthew  5533: Returns: A uniform header for LON-CAPA web pages.  
                   5534: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5535: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5536: other decorations will be returned.
                   5537: 
                   5538: =cut
                   5539: 
1.54      www      5540: sub bodytag {
1.831     bisitz   5541:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5542:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5543: 
1.954     raeburn  5544:     my $public;
                   5545:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5546:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5547:         $public = 1;
                   5548:     }
1.460     albertel 5549:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5550:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5551:     my $hostname = $args->{'hostname'};
1.339     albertel 5552: 
1.183     matthew  5553:     $function = &get_users_function() if (!$function);
1.339     albertel 5554:     my $img =    &designparm($function.'.img',$domain);
                   5555:     my $font =   &designparm($function.'.font',$domain);
                   5556:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5557: 
1.803     bisitz   5558:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5559: 		   'bgcolor' => $pgbg,
1.339     albertel 5560: 		   'text'    => $font,
                   5561:                    'alink'   => &designparm($function.'.alink',$domain),
                   5562: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5563: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5564:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5565: 
1.63      www      5566:  # role and realm
1.1075.2.68  raeburn  5567:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5568:     if ($realm) {
                   5569:         $realm = '/'.$realm;
                   5570:     }
1.378     raeburn  5571:     if ($role  eq 'ca') {
1.479     albertel 5572:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5573:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5574:     } 
1.55      www      5575: # realm
1.258     albertel 5576:     if ($env{'request.course.id'}) {
1.378     raeburn  5577:         if ($env{'request.role'} !~ /^cr/) {
                   5578:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5579:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5580:             if ($env{'request.role.desc'}) {
                   5581:                 $role = $env{'request.role.desc'};
                   5582:             } else {
                   5583:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5584:             }
1.1075.2.115  raeburn  5585:         } else {
                   5586:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5587:         }
1.898     raeburn  5588:         if ($env{'request.course.sec'}) {
                   5589:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5590:         }   
1.359     albertel 5591: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5592:     } else {
                   5593:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5594:     }
1.433     albertel 5595: 
1.359     albertel 5596:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5597: 
1.438     albertel 5598:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5599: 
1.101     www      5600: # construct main body tag
1.359     albertel 5601:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5602: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5603: 
1.1075.2.38  raeburn  5604:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5605: 
                   5606:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5607:         return $bodytag;
1.1075.2.38  raeburn  5608:     }
1.359     albertel 5609: 
1.954     raeburn  5610:     if ($public) {
1.433     albertel 5611: 	undef($role);
                   5612:     }
1.359     albertel 5613:     
1.762     bisitz   5614:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5615:     #
                   5616:     # Extra info if you are the DC
                   5617:     my $dc_info = '';
                   5618:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5619:                         $env{'course.'.$env{'request.course.id'}.
                   5620:                                  '.domain'}.'/'})) {
                   5621:         my $cid = $env{'request.course.id'};
1.917     raeburn  5622:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5623:         $dc_info =~ s/\s+$//;
1.359     albertel 5624:     }
                   5625: 
1.1075.2.108  raeburn  5626:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5627: 
1.1075.2.13  raeburn  5628:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5629: 
1.1075.2.38  raeburn  5630: 
                   5631: 
1.1075.2.21  raeburn  5632:     my $funclist;
                   5633:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5634:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5635:                     Apache::lonmenu::serverform();
                   5636:         my $forbodytag;
                   5637:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5638:                                             $forcereg,$args->{'group'},
                   5639:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5640:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5641:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5642:             $funclist = $forbodytag;
                   5643:         }
                   5644:     } else {
1.903     droeschl 5645: 
                   5646:         #    if ($env{'request.state'} eq 'construct') {
                   5647:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5648:         #    }
                   5649: 
1.1075.2.38  raeburn  5650:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5651:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5652: 
1.1075.2.38  raeburn  5653:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5654: 
1.916     droeschl 5655:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5656:             if ($dc_info) {
                   5657:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5658:             }
1.1075.2.38  raeburn  5659:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5660:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5661:             return $bodytag;
                   5662:         }
1.894     droeschl 5663: 
1.927     raeburn  5664:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5665:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5666:         }
1.916     droeschl 5667: 
1.1075.2.38  raeburn  5668:         $bodytag .= $right;
1.852     droeschl 5669: 
1.917     raeburn  5670:         if ($dc_info) {
                   5671:             $dc_info = &dc_courseid_toggle($dc_info);
                   5672:         }
                   5673:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5674: 
1.1075.2.61  raeburn  5675:         #if directed to not display the secondary menu, don't.
                   5676:         if ($args->{'no_secondary_menu'}) {
                   5677:             return $bodytag;
                   5678:         }
1.903     droeschl 5679:         #don't show menus for public users
1.954     raeburn  5680:         if (!$public){
1.1075.2.52  raeburn  5681:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5682:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5683:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5684:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5685:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5686:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5687:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5688:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5689:                                                             $args->{'group'},
1.1075.2.133  raeburn  5690:                                                             $args->{'hide_buttons',
                   5691:                                                             $hostname});
1.1075.2.15  raeburn  5692:             } else {
1.1075.2.21  raeburn  5693:                 my $forbodytag;
                   5694:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5695:                                                     $forcereg,$args->{'group'},
                   5696:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5697:                                                     $advtoolsref,'',$hostname,
                   5698:                                                     \$forbodytag);
1.1075.2.21  raeburn  5699:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5700:                     $bodytag .= $forbodytag;
                   5701:                 }
1.920     raeburn  5702:             }
1.903     droeschl 5703:         }else{
                   5704:             # this is to seperate menu from content when there's no secondary
                   5705:             # menu. Especially needed for public accessible ressources.
                   5706:             $bodytag .= '<hr style="clear:both" />';
                   5707:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5708:         }
1.903     droeschl 5709: 
1.235     raeburn  5710:         return $bodytag;
1.1075.2.12  raeburn  5711:     }
                   5712: 
                   5713: #
                   5714: # Top frame rendering, Remote is up
                   5715: #
                   5716: 
                   5717:     my $imgsrc = $img;
                   5718:     if ($img =~ /^\/adm/) {
                   5719:         $imgsrc = &lonhttpdurl($img);
                   5720:     }
                   5721:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5722: 
1.1075.2.60  raeburn  5723:     my $help=($no_inline_link?''
                   5724:               :&Apache::loncommon::top_nav_help('Help'));
                   5725: 
1.1075.2.12  raeburn  5726:     # Explicit link to get inline menu
                   5727:     my $menu= ($no_inline_link?''
                   5728:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5729: 
                   5730:     if ($dc_info) {
                   5731:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5732:     }
                   5733: 
1.1075.2.38  raeburn  5734:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5735:     unless ($public) {
                   5736:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5737:                                 undef,'LC_menubuttons_link');
                   5738:     }
                   5739: 
1.1075.2.12  raeburn  5740:     unless ($env{'form.inhibitmenu'}) {
                   5741:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5742:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5743:                        <li>$help</li>
1.1075.2.12  raeburn  5744:                        <li>$menu</li>
                   5745:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5746:     }
1.1075.2.13  raeburn  5747:     if ($env{'request.state'} eq 'construct') {
                   5748:         if (!$public){
                   5749:             if ($env{'request.state'} eq 'construct') {
                   5750:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5751:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5752:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5753:                             &Apache::lonmenu::innerregister($forcereg,
                   5754:                                                             $args->{'bread_crumbs'});
                   5755:             }
                   5756:         }
                   5757:     }
1.1075.2.21  raeburn  5758:     return $bodytag."\n".$funclist;
1.182     matthew  5759: }
                   5760: 
1.917     raeburn  5761: sub dc_courseid_toggle {
                   5762:     my ($dc_info) = @_;
1.980     raeburn  5763:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5764:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5765:            &mt('(More ...)').'</a></span>'.
                   5766:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5767: }
                   5768: 
1.330     albertel 5769: sub make_attr_string {
                   5770:     my ($register,$attr_ref) = @_;
                   5771: 
                   5772:     if ($attr_ref && !ref($attr_ref)) {
                   5773: 	die("addentries Must be a hash ref ".
                   5774: 	    join(':',caller(1))." ".
                   5775: 	    join(':',caller(0))." ");
                   5776:     }
                   5777: 
                   5778:     if ($register) {
1.339     albertel 5779: 	my ($on_load,$on_unload);
                   5780: 	foreach my $key (keys(%{$attr_ref})) {
                   5781: 	    if      (lc($key) eq 'onload') {
                   5782: 		$on_load.=$attr_ref->{$key}.';';
                   5783: 		delete($attr_ref->{$key});
                   5784: 
                   5785: 	    } elsif (lc($key) eq 'onunload') {
                   5786: 		$on_unload.=$attr_ref->{$key}.';';
                   5787: 		delete($attr_ref->{$key});
                   5788: 	    }
                   5789: 	}
1.1075.2.12  raeburn  5790:         if ($env{'environment.remote'} eq 'on') {
                   5791:             $attr_ref->{'onload'}  =
                   5792:                 &Apache::lonmenu::loadevents().  $on_load;
                   5793:             $attr_ref->{'onunload'}=
                   5794:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5795:         } else {  
                   5796: 	    $attr_ref->{'onload'}  = $on_load;
                   5797: 	    $attr_ref->{'onunload'}= $on_unload;
                   5798:         }
1.330     albertel 5799:     }
1.339     albertel 5800: 
1.330     albertel 5801:     my $attr_string;
1.1075.2.56  raeburn  5802:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5803: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5804:     }
                   5805:     return $attr_string;
                   5806: }
                   5807: 
                   5808: 
1.182     matthew  5809: ###############################################
1.251     albertel 5810: ###############################################
                   5811: 
                   5812: =pod
                   5813: 
                   5814: =item * &endbodytag()
                   5815: 
                   5816: Returns a uniform footer for LON-CAPA web pages.
                   5817: 
1.635     raeburn  5818: Inputs: 1 - optional reference to an args hash
                   5819: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5820: a 'Continue' link is not displayed if the page contains an
                   5821: internal redirect in the <head></head> section,
                   5822: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5823: 
                   5824: =cut
                   5825: 
                   5826: sub endbodytag {
1.635     raeburn  5827:     my ($args) = @_;
1.1075.2.6  raeburn  5828:     my $endbodytag;
                   5829:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5830:         $endbodytag='</body>';
                   5831:     }
1.315     albertel 5832:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5833:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5834: 	    $endbodytag=
                   5835: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5836: 	        &mt('Continue').'</a>'.
                   5837: 	        $endbodytag;
                   5838:         }
1.315     albertel 5839:     }
1.251     albertel 5840:     return $endbodytag;
                   5841: }
                   5842: 
1.352     albertel 5843: =pod
                   5844: 
                   5845: =item * &standard_css()
                   5846: 
                   5847: Returns a style sheet
                   5848: 
                   5849: Inputs: (all optional)
                   5850:             domain         -> force to color decorate a page for a specific
                   5851:                                domain
                   5852:             function       -> force usage of a specific rolish color scheme
                   5853:             bgcolor        -> override the default page bgcolor
                   5854: 
                   5855: =cut
                   5856: 
1.343     albertel 5857: sub standard_css {
1.345     albertel 5858:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5859:     $function  = &get_users_function() if (!$function);
                   5860:     my $img    = &designparm($function.'.img',   $domain);
                   5861:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5862:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5863:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5864: #second colour for later usage
1.345     albertel 5865:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5866:     my $pgbg_or_bgcolor =
                   5867: 	         $bgcolor ||
1.352     albertel 5868: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5869:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5870:     my $alink  = &designparm($function.'.alink', $domain);
                   5871:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5872:     my $link   = &designparm($function.'.link',  $domain);
                   5873: 
1.602     albertel 5874:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5875:     my $mono                 = 'monospace';
1.850     bisitz   5876:     my $data_table_head      = $sidebg;
                   5877:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5878:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5879:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5880:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5881:     my $mail_new             = '#FFBB77';
                   5882:     my $mail_new_hover       = '#DD9955';
                   5883:     my $mail_read            = '#BBBB77';
                   5884:     my $mail_read_hover      = '#999944';
                   5885:     my $mail_replied         = '#AAAA88';
                   5886:     my $mail_replied_hover   = '#888855';
                   5887:     my $mail_other           = '#99BBBB';
                   5888:     my $mail_other_hover     = '#669999';
1.391     albertel 5889:     my $table_header         = '#DDDDDD';
1.489     raeburn  5890:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5891:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5892:     my $button_hover         = '#BF2317';
1.392     albertel 5893: 
1.608     albertel 5894:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5895:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5896:                                              : '0 3px 0 4px';
1.448     albertel 5897: 
1.523     albertel 5898: 
1.343     albertel 5899:     return <<END;
1.947     droeschl 5900: 
                   5901: /* needed for iframe to allow 100% height in FF */
                   5902: body, html { 
                   5903:     margin: 0;
                   5904:     padding: 0 0.5%;
                   5905:     height: 99%; /* to avoid scrollbars */
                   5906: }
                   5907: 
1.795     www      5908: body {
1.911     bisitz   5909:   font-family: $sans;
                   5910:   line-height:130%;
                   5911:   font-size:0.83em;
                   5912:   color:$font;
1.795     www      5913: }
                   5914: 
1.959     onken    5915: a:focus,
                   5916: a:focus img {
1.795     www      5917:   color: red;
                   5918: }
1.698     harmsja  5919: 
1.911     bisitz   5920: form, .inline {
                   5921:   display: inline;
1.795     www      5922: }
1.721     harmsja  5923: 
1.795     www      5924: .LC_right {
1.911     bisitz   5925:   text-align:right;
1.795     www      5926: }
                   5927: 
                   5928: .LC_middle {
1.911     bisitz   5929:   vertical-align:middle;
1.795     www      5930: }
1.721     harmsja  5931: 
1.1075.2.38  raeburn  5932: .LC_floatleft {
                   5933:   float: left;
                   5934: }
                   5935: 
                   5936: .LC_floatright {
                   5937:   float: right;
                   5938: }
                   5939: 
1.911     bisitz   5940: .LC_400Box {
                   5941:   width:400px;
                   5942: }
1.721     harmsja  5943: 
1.947     droeschl 5944: .LC_iframecontainer {
                   5945:     width: 98%;
                   5946:     margin: 0;
                   5947:     position: fixed;
                   5948:     top: 8.5em;
                   5949:     bottom: 0;
                   5950: }
                   5951: 
                   5952: .LC_iframecontainer iframe{
                   5953:     border: none;
                   5954:     width: 100%;
                   5955:     height: 100%;
                   5956: }
                   5957: 
1.778     bisitz   5958: .LC_filename {
                   5959:   font-family: $mono;
                   5960:   white-space:pre;
1.921     bisitz   5961:   font-size: 120%;
1.778     bisitz   5962: }
                   5963: 
                   5964: .LC_fileicon {
                   5965:   border: none;
                   5966:   height: 1.3em;
                   5967:   vertical-align: text-bottom;
                   5968:   margin-right: 0.3em;
                   5969:   text-decoration:none;
                   5970: }
                   5971: 
1.1008    www      5972: .LC_setting {
                   5973:   text-decoration:underline;
                   5974: }
                   5975: 
1.350     albertel 5976: .LC_error {
                   5977:   color: red;
                   5978: }
1.795     www      5979: 
1.1075.2.15  raeburn  5980: .LC_warning {
                   5981:   color: darkorange;
                   5982: }
                   5983: 
1.457     albertel 5984: .LC_diff_removed {
1.733     bisitz   5985:   color: red;
1.394     albertel 5986: }
1.532     albertel 5987: 
                   5988: .LC_info,
1.457     albertel 5989: .LC_success,
                   5990: .LC_diff_added {
1.350     albertel 5991:   color: green;
                   5992: }
1.795     www      5993: 
1.802     bisitz   5994: div.LC_confirm_box {
                   5995:   background-color: #FAFAFA;
                   5996:   border: 1px solid $lg_border_color;
                   5997:   margin-right: 0;
                   5998:   padding: 5px;
                   5999: }
                   6000: 
                   6001: div.LC_confirm_box .LC_error img,
                   6002: div.LC_confirm_box .LC_success img {
                   6003:   vertical-align: middle;
                   6004: }
                   6005: 
1.1075.2.108  raeburn  6006: .LC_maxwidth {
                   6007:   max-width: 100%;
                   6008:   height: auto;
                   6009: }
                   6010: 
                   6011: .LC_textsize_mobile {
                   6012:   \@media only screen and (max-device-width: 480px) {
                   6013:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6014:   }
                   6015: }
                   6016: 
1.440     albertel 6017: .LC_icon {
1.771     droeschl 6018:   border: none;
1.790     droeschl 6019:   vertical-align: middle;
1.771     droeschl 6020: }
                   6021: 
1.543     albertel 6022: .LC_docs_spacer {
                   6023:   width: 25px;
                   6024:   height: 1px;
1.771     droeschl 6025:   border: none;
1.543     albertel 6026: }
1.346     albertel 6027: 
1.532     albertel 6028: .LC_internal_info {
1.735     bisitz   6029:   color: #999999;
1.532     albertel 6030: }
                   6031: 
1.794     www      6032: .LC_discussion {
1.1050    www      6033:   background: $data_table_dark;
1.911     bisitz   6034:   border: 1px solid black;
                   6035:   margin: 2px;
1.794     www      6036: }
                   6037: 
                   6038: .LC_disc_action_left {
1.1050    www      6039:   background: $sidebg;
1.911     bisitz   6040:   text-align: left;
1.1050    www      6041:   padding: 4px;
                   6042:   margin: 2px;
1.794     www      6043: }
                   6044: 
                   6045: .LC_disc_action_right {
1.1050    www      6046:   background: $sidebg;
1.911     bisitz   6047:   text-align: right;
1.1050    www      6048:   padding: 4px;
                   6049:   margin: 2px;
1.794     www      6050: }
                   6051: 
                   6052: .LC_disc_new_item {
1.911     bisitz   6053:   background: white;
                   6054:   border: 2px solid red;
1.1050    www      6055:   margin: 4px;
                   6056:   padding: 4px;
1.794     www      6057: }
                   6058: 
                   6059: .LC_disc_old_item {
1.911     bisitz   6060:   background: white;
1.1050    www      6061:   margin: 4px;
                   6062:   padding: 4px;
1.794     www      6063: }
                   6064: 
1.458     albertel 6065: table.LC_pastsubmission {
                   6066:   border: 1px solid black;
                   6067:   margin: 2px;
                   6068: }
                   6069: 
1.924     bisitz   6070: table#LC_menubuttons {
1.345     albertel 6071:   width: 100%;
                   6072:   background: $pgbg;
1.392     albertel 6073:   border: 2px;
1.402     albertel 6074:   border-collapse: separate;
1.803     bisitz   6075:   padding: 0;
1.345     albertel 6076: }
1.392     albertel 6077: 
1.801     tempelho 6078: table#LC_title_bar a {
                   6079:   color: $fontmenu;
                   6080: }
1.836     bisitz   6081: 
1.807     droeschl 6082: table#LC_title_bar {
1.819     tempelho 6083:   clear: both;
1.836     bisitz   6084:   display: none;
1.807     droeschl 6085: }
                   6086: 
1.795     www      6087: table#LC_title_bar,
1.933     droeschl 6088: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6089: table#LC_title_bar.LC_with_remote {
1.359     albertel 6090:   width: 100%;
1.392     albertel 6091:   border-color: $pgbg;
                   6092:   border-style: solid;
                   6093:   border-width: $border;
1.379     albertel 6094:   background: $pgbg;
1.801     tempelho 6095:   color: $fontmenu;
1.392     albertel 6096:   border-collapse: collapse;
1.803     bisitz   6097:   padding: 0;
1.819     tempelho 6098:   margin: 0;
1.359     albertel 6099: }
1.795     www      6100: 
1.933     droeschl 6101: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6102:     margin: 0;
                   6103:     padding: 0;
1.933     droeschl 6104:     position: relative;
                   6105:     list-style: none;
1.913     droeschl 6106: }
1.933     droeschl 6107: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6108:     display: inline;
                   6109: }
1.933     droeschl 6110: 
                   6111: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6112:     padding: 0;
1.933     droeschl 6113:     margin: 0;
                   6114:     float: left;
1.913     droeschl 6115: }
1.933     droeschl 6116: .LC_breadcrumb_tools_tools {
                   6117:     padding: 0;
                   6118:     margin: 0;
1.913     droeschl 6119:     float: right;
                   6120: }
                   6121: 
1.359     albertel 6122: table#LC_title_bar td {
                   6123:   background: $tabbg;
                   6124: }
1.795     www      6125: 
1.911     bisitz   6126: table#LC_menubuttons img {
1.803     bisitz   6127:   border: none;
1.346     albertel 6128: }
1.795     www      6129: 
1.842     droeschl 6130: .LC_breadcrumbs_component {
1.911     bisitz   6131:   float: right;
                   6132:   margin: 0 1em;
1.357     albertel 6133: }
1.842     droeschl 6134: .LC_breadcrumbs_component img {
1.911     bisitz   6135:   vertical-align: middle;
1.777     tempelho 6136: }
1.795     www      6137: 
1.1075.2.108  raeburn  6138: .LC_breadcrumbs_hoverable {
                   6139:   background: $sidebg;
                   6140: }
                   6141: 
1.383     albertel 6142: td.LC_table_cell_checkbox {
                   6143:   text-align: center;
                   6144: }
1.795     www      6145: 
                   6146: .LC_fontsize_small {
1.911     bisitz   6147:   font-size: 70%;
1.705     tempelho 6148: }
                   6149: 
1.844     bisitz   6150: #LC_breadcrumbs {
1.911     bisitz   6151:   clear:both;
                   6152:   background: $sidebg;
                   6153:   border-bottom: 1px solid $lg_border_color;
                   6154:   line-height: 2.5em;
1.933     droeschl 6155:   overflow: hidden;
1.911     bisitz   6156:   margin: 0;
                   6157:   padding: 0;
1.995     raeburn  6158:   text-align: left;
1.819     tempelho 6159: }
1.862     bisitz   6160: 
1.1075.2.16  raeburn  6161: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6162:   clear:both;
                   6163:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6164:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6165:   margin: 0 0 10px 0;
1.966     bisitz   6166:   padding: 3px;
1.995     raeburn  6167:   text-align: left;
1.822     bisitz   6168: }
                   6169: 
1.795     www      6170: .LC_fontsize_medium {
1.911     bisitz   6171:   font-size: 85%;
1.705     tempelho 6172: }
                   6173: 
1.795     www      6174: .LC_fontsize_large {
1.911     bisitz   6175:   font-size: 120%;
1.705     tempelho 6176: }
                   6177: 
1.346     albertel 6178: .LC_menubuttons_inline_text {
                   6179:   color: $font;
1.698     harmsja  6180:   font-size: 90%;
1.701     harmsja  6181:   padding-left:3px;
1.346     albertel 6182: }
                   6183: 
1.934     droeschl 6184: .LC_menubuttons_inline_text img{
                   6185:   vertical-align: middle;
                   6186: }
                   6187: 
1.1051    www      6188: li.LC_menubuttons_inline_text img {
1.951     onken    6189:   cursor:pointer;
1.1002    droeschl 6190:   text-decoration: none;
1.951     onken    6191: }
                   6192: 
1.526     www      6193: .LC_menubuttons_link {
                   6194:   text-decoration: none;
                   6195: }
1.795     www      6196: 
1.522     albertel 6197: .LC_menubuttons_category {
1.521     www      6198:   color: $font;
1.526     www      6199:   background: $pgbg;
1.521     www      6200:   font-size: larger;
                   6201:   font-weight: bold;
                   6202: }
                   6203: 
1.346     albertel 6204: td.LC_menubuttons_text {
1.911     bisitz   6205:   color: $font;
1.346     albertel 6206: }
1.706     harmsja  6207: 
1.346     albertel 6208: .LC_current_location {
                   6209:   background: $tabbg;
                   6210: }
1.795     www      6211: 
1.1075.2.134  raeburn  6212: td.LC_zero_height {
                   6213:   line-height: 0;
                   6214:   cellpadding: 0;
                   6215: }
                   6216: 
1.938     bisitz   6217: table.LC_data_table {
1.347     albertel 6218:   border: 1px solid #000000;
1.402     albertel 6219:   border-collapse: separate;
1.426     albertel 6220:   border-spacing: 1px;
1.610     albertel 6221:   background: $pgbg;
1.347     albertel 6222: }
1.795     www      6223: 
1.422     albertel 6224: .LC_data_table_dense {
                   6225:   font-size: small;
                   6226: }
1.795     www      6227: 
1.507     raeburn  6228: table.LC_nested_outer {
                   6229:   border: 1px solid #000000;
1.589     raeburn  6230:   border-collapse: collapse;
1.803     bisitz   6231:   border-spacing: 0;
1.507     raeburn  6232:   width: 100%;
                   6233: }
1.795     www      6234: 
1.879     raeburn  6235: table.LC_innerpickbox,
1.507     raeburn  6236: table.LC_nested {
1.803     bisitz   6237:   border: none;
1.589     raeburn  6238:   border-collapse: collapse;
1.803     bisitz   6239:   border-spacing: 0;
1.507     raeburn  6240:   width: 100%;
                   6241: }
1.795     www      6242: 
1.911     bisitz   6243: table.LC_data_table tr th,
                   6244: table.LC_calendar tr th,
1.879     raeburn  6245: table.LC_prior_tries tr th,
                   6246: table.LC_innerpickbox tr th {
1.349     albertel 6247:   font-weight: bold;
                   6248:   background-color: $data_table_head;
1.801     tempelho 6249:   color:$fontmenu;
1.701     harmsja  6250:   font-size:90%;
1.347     albertel 6251: }
1.795     www      6252: 
1.879     raeburn  6253: table.LC_innerpickbox tr th,
                   6254: table.LC_innerpickbox tr td {
                   6255:   vertical-align: top;
                   6256: }
                   6257: 
1.711     raeburn  6258: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6259:   background-color: #CCCCCC;
1.711     raeburn  6260:   font-weight: bold;
                   6261:   text-align: left;
                   6262: }
1.795     www      6263: 
1.912     bisitz   6264: table.LC_data_table tr.LC_odd_row > td {
                   6265:   background-color: $data_table_light;
                   6266:   padding: 2px;
                   6267:   vertical-align: top;
                   6268: }
                   6269: 
1.809     bisitz   6270: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6271:   background-color: $data_table_light;
1.912     bisitz   6272:   vertical-align: top;
                   6273: }
                   6274: 
                   6275: table.LC_data_table tr.LC_even_row > td {
                   6276:   background-color: $data_table_dark;
1.425     albertel 6277:   padding: 2px;
1.900     bisitz   6278:   vertical-align: top;
1.347     albertel 6279: }
1.795     www      6280: 
1.809     bisitz   6281: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6282:   background-color: $data_table_dark;
1.900     bisitz   6283:   vertical-align: top;
1.347     albertel 6284: }
1.795     www      6285: 
1.425     albertel 6286: table.LC_data_table tr.LC_data_table_highlight td {
                   6287:   background-color: $data_table_darker;
                   6288: }
1.795     www      6289: 
1.639     raeburn  6290: table.LC_data_table tr td.LC_leftcol_header {
                   6291:   background-color: $data_table_head;
                   6292:   font-weight: bold;
                   6293: }
1.795     www      6294: 
1.451     albertel 6295: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6296: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6297:   font-weight: bold;
                   6298:   font-style: italic;
                   6299:   text-align: center;
                   6300:   padding: 8px;
1.347     albertel 6301: }
1.795     www      6302: 
1.1075.2.30  raeburn  6303: table.LC_data_table tr.LC_empty_row td,
                   6304: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6305:   background-color: $sidebg;
                   6306: }
                   6307: 
                   6308: table.LC_nested tr.LC_empty_row td {
                   6309:   background-color: #FFFFFF;
                   6310: }
                   6311: 
1.890     droeschl 6312: table.LC_caption {
                   6313: }
                   6314: 
1.507     raeburn  6315: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6316:   padding: 4ex
                   6317: }
1.795     www      6318: 
1.507     raeburn  6319: table.LC_nested_outer tr th {
                   6320:   font-weight: bold;
1.801     tempelho 6321:   color:$fontmenu;
1.507     raeburn  6322:   background-color: $data_table_head;
1.701     harmsja  6323:   font-size: small;
1.507     raeburn  6324:   border-bottom: 1px solid #000000;
                   6325: }
1.795     www      6326: 
1.507     raeburn  6327: table.LC_nested_outer tr td.LC_subheader {
                   6328:   background-color: $data_table_head;
                   6329:   font-weight: bold;
                   6330:   font-size: small;
                   6331:   border-bottom: 1px solid #000000;
                   6332:   text-align: right;
1.451     albertel 6333: }
1.795     www      6334: 
1.507     raeburn  6335: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6336:   background-color: #CCCCCC;
1.451     albertel 6337:   font-weight: bold;
                   6338:   font-size: small;
1.507     raeburn  6339:   text-align: center;
                   6340: }
1.795     www      6341: 
1.589     raeburn  6342: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6343: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6344:   text-align: left;
1.451     albertel 6345: }
1.795     www      6346: 
1.507     raeburn  6347: table.LC_nested td {
1.735     bisitz   6348:   background-color: #FFFFFF;
1.451     albertel 6349:   font-size: small;
1.507     raeburn  6350: }
1.795     www      6351: 
1.507     raeburn  6352: table.LC_nested_outer tr th.LC_right_item,
                   6353: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6354: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6355: table.LC_nested tr td.LC_right_item {
1.451     albertel 6356:   text-align: right;
                   6357: }
                   6358: 
1.507     raeburn  6359: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6360:   background-color: #EEEEEE;
1.451     albertel 6361: }
                   6362: 
1.473     raeburn  6363: table.LC_createuser {
                   6364: }
                   6365: 
                   6366: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6367:   font-size: small;
1.473     raeburn  6368: }
                   6369: 
                   6370: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6371:   background-color: #CCCCCC;
1.473     raeburn  6372:   font-weight: bold;
                   6373:   text-align: center;
                   6374: }
                   6375: 
1.349     albertel 6376: table.LC_calendar {
                   6377:   border: 1px solid #000000;
                   6378:   border-collapse: collapse;
1.917     raeburn  6379:   width: 98%;
1.349     albertel 6380: }
1.795     www      6381: 
1.349     albertel 6382: table.LC_calendar_pickdate {
                   6383:   font-size: xx-small;
                   6384: }
1.795     www      6385: 
1.349     albertel 6386: table.LC_calendar tr td {
                   6387:   border: 1px solid #000000;
                   6388:   vertical-align: top;
1.917     raeburn  6389:   width: 14%;
1.349     albertel 6390: }
1.795     www      6391: 
1.349     albertel 6392: table.LC_calendar tr td.LC_calendar_day_empty {
                   6393:   background-color: $data_table_dark;
                   6394: }
1.795     www      6395: 
1.779     bisitz   6396: table.LC_calendar tr td.LC_calendar_day_current {
                   6397:   background-color: $data_table_highlight;
1.777     tempelho 6398: }
1.795     www      6399: 
1.938     bisitz   6400: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6401:   background-color: $mail_new;
                   6402: }
1.795     www      6403: 
1.938     bisitz   6404: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6405:   background-color: $mail_new_hover;
                   6406: }
1.795     www      6407: 
1.938     bisitz   6408: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6409:   background-color: $mail_read;
                   6410: }
1.795     www      6411: 
1.938     bisitz   6412: /*
                   6413: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6414:   background-color: $mail_read_hover;
                   6415: }
1.938     bisitz   6416: */
1.795     www      6417: 
1.938     bisitz   6418: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6419:   background-color: $mail_replied;
                   6420: }
1.795     www      6421: 
1.938     bisitz   6422: /*
                   6423: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6424:   background-color: $mail_replied_hover;
                   6425: }
1.938     bisitz   6426: */
1.795     www      6427: 
1.938     bisitz   6428: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6429:   background-color: $mail_other;
                   6430: }
1.795     www      6431: 
1.938     bisitz   6432: /*
                   6433: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6434:   background-color: $mail_other_hover;
                   6435: }
1.938     bisitz   6436: */
1.494     raeburn  6437: 
1.777     tempelho 6438: table.LC_data_table tr > td.LC_browser_file,
                   6439: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6440:   background: #AAEE77;
1.389     albertel 6441: }
1.795     www      6442: 
1.777     tempelho 6443: table.LC_data_table tr > td.LC_browser_file_locked,
                   6444: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6445:   background: #FFAA99;
1.387     albertel 6446: }
1.795     www      6447: 
1.777     tempelho 6448: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6449:   background: #888888;
1.779     bisitz   6450: }
1.795     www      6451: 
1.777     tempelho 6452: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6453: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6454:   background: #F8F866;
1.777     tempelho 6455: }
1.795     www      6456: 
1.696     bisitz   6457: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6458:   background: #E0E8FF;
1.387     albertel 6459: }
1.696     bisitz   6460: 
1.707     bisitz   6461: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6462:   /* background: #77FF77; */
1.707     bisitz   6463: }
1.795     www      6464: 
1.707     bisitz   6465: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6466:   border-right: 8px solid #FFFF77;
1.707     bisitz   6467: }
1.795     www      6468: 
1.707     bisitz   6469: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6470:   border-right: 8px solid #FFAA77;
1.707     bisitz   6471: }
1.795     www      6472: 
1.707     bisitz   6473: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6474:   border-right: 8px solid #FF7777;
1.707     bisitz   6475: }
1.795     www      6476: 
1.707     bisitz   6477: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6478:   border-right: 8px solid #AAFF77;
1.707     bisitz   6479: }
1.795     www      6480: 
1.707     bisitz   6481: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6482:   border-right: 8px solid #11CC55;
1.707     bisitz   6483: }
                   6484: 
1.388     albertel 6485: span.LC_current_location {
1.701     harmsja  6486:   font-size:larger;
1.388     albertel 6487:   background: $pgbg;
                   6488: }
1.387     albertel 6489: 
1.1029    www      6490: span.LC_current_nav_location {
                   6491:   font-weight:bold;
                   6492:   background: $sidebg;
                   6493: }
                   6494: 
1.395     albertel 6495: span.LC_parm_menu_item {
                   6496:   font-size: larger;
                   6497: }
1.795     www      6498: 
1.395     albertel 6499: span.LC_parm_scope_all {
                   6500:   color: red;
                   6501: }
1.795     www      6502: 
1.395     albertel 6503: span.LC_parm_scope_folder {
                   6504:   color: green;
                   6505: }
1.795     www      6506: 
1.395     albertel 6507: span.LC_parm_scope_resource {
                   6508:   color: orange;
                   6509: }
1.795     www      6510: 
1.395     albertel 6511: span.LC_parm_part {
                   6512:   color: blue;
                   6513: }
1.795     www      6514: 
1.911     bisitz   6515: span.LC_parm_folder,
                   6516: span.LC_parm_symb {
1.395     albertel 6517:   font-size: x-small;
                   6518:   font-family: $mono;
                   6519:   color: #AAAAAA;
                   6520: }
                   6521: 
1.977     bisitz   6522: ul.LC_parm_parmlist li {
                   6523:   display: inline-block;
                   6524:   padding: 0.3em 0.8em;
                   6525:   vertical-align: top;
                   6526:   width: 150px;
                   6527:   border-top:1px solid $lg_border_color;
                   6528: }
                   6529: 
1.795     www      6530: td.LC_parm_overview_level_menu,
                   6531: td.LC_parm_overview_map_menu,
                   6532: td.LC_parm_overview_parm_selectors,
                   6533: td.LC_parm_overview_restrictions  {
1.396     albertel 6534:   border: 1px solid black;
                   6535:   border-collapse: collapse;
                   6536: }
1.795     www      6537: 
1.396     albertel 6538: table.LC_parm_overview_restrictions td {
                   6539:   border-width: 1px 4px 1px 4px;
                   6540:   border-style: solid;
                   6541:   border-color: $pgbg;
                   6542:   text-align: center;
                   6543: }
1.795     www      6544: 
1.396     albertel 6545: table.LC_parm_overview_restrictions th {
                   6546:   background: $tabbg;
                   6547:   border-width: 1px 4px 1px 4px;
                   6548:   border-style: solid;
                   6549:   border-color: $pgbg;
                   6550: }
1.795     www      6551: 
1.398     albertel 6552: table#LC_helpmenu {
1.803     bisitz   6553:   border: none;
1.398     albertel 6554:   height: 55px;
1.803     bisitz   6555:   border-spacing: 0;
1.398     albertel 6556: }
                   6557: 
                   6558: table#LC_helpmenu fieldset legend {
                   6559:   font-size: larger;
                   6560: }
1.795     www      6561: 
1.397     albertel 6562: table#LC_helpmenu_links {
                   6563:   width: 100%;
                   6564:   border: 1px solid black;
                   6565:   background: $pgbg;
1.803     bisitz   6566:   padding: 0;
1.397     albertel 6567:   border-spacing: 1px;
                   6568: }
1.795     www      6569: 
1.397     albertel 6570: table#LC_helpmenu_links tr td {
                   6571:   padding: 1px;
                   6572:   background: $tabbg;
1.399     albertel 6573:   text-align: center;
                   6574:   font-weight: bold;
1.397     albertel 6575: }
1.396     albertel 6576: 
1.795     www      6577: table#LC_helpmenu_links a:link,
                   6578: table#LC_helpmenu_links a:visited,
1.397     albertel 6579: table#LC_helpmenu_links a:active {
                   6580:   text-decoration: none;
                   6581:   color: $font;
                   6582: }
1.795     www      6583: 
1.397     albertel 6584: table#LC_helpmenu_links a:hover {
                   6585:   text-decoration: underline;
                   6586:   color: $vlink;
                   6587: }
1.396     albertel 6588: 
1.417     albertel 6589: .LC_chrt_popup_exists {
                   6590:   border: 1px solid #339933;
                   6591:   margin: -1px;
                   6592: }
1.795     www      6593: 
1.417     albertel 6594: .LC_chrt_popup_up {
                   6595:   border: 1px solid yellow;
                   6596:   margin: -1px;
                   6597: }
1.795     www      6598: 
1.417     albertel 6599: .LC_chrt_popup {
                   6600:   border: 1px solid #8888FF;
                   6601:   background: #CCCCFF;
                   6602: }
1.795     www      6603: 
1.421     albertel 6604: table.LC_pick_box {
                   6605:   border-collapse: separate;
                   6606:   background: white;
                   6607:   border: 1px solid black;
                   6608:   border-spacing: 1px;
                   6609: }
1.795     www      6610: 
1.421     albertel 6611: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6612:   background: $sidebg;
1.421     albertel 6613:   font-weight: bold;
1.900     bisitz   6614:   text-align: left;
1.740     bisitz   6615:   vertical-align: top;
1.421     albertel 6616:   width: 184px;
                   6617:   padding: 8px;
                   6618: }
1.795     www      6619: 
1.579     raeburn  6620: table.LC_pick_box td.LC_pick_box_value {
                   6621:   text-align: left;
                   6622:   padding: 8px;
                   6623: }
1.795     www      6624: 
1.579     raeburn  6625: table.LC_pick_box td.LC_pick_box_select {
                   6626:   text-align: left;
                   6627:   padding: 8px;
                   6628: }
1.795     www      6629: 
1.424     albertel 6630: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6631:   padding: 0;
1.421     albertel 6632:   height: 1px;
                   6633:   background: black;
                   6634: }
1.795     www      6635: 
1.421     albertel 6636: table.LC_pick_box td.LC_pick_box_submit {
                   6637:   text-align: right;
                   6638: }
1.795     www      6639: 
1.579     raeburn  6640: table.LC_pick_box td.LC_evenrow_value {
                   6641:   text-align: left;
                   6642:   padding: 8px;
                   6643:   background-color: $data_table_light;
                   6644: }
1.795     www      6645: 
1.579     raeburn  6646: table.LC_pick_box td.LC_oddrow_value {
                   6647:   text-align: left;
                   6648:   padding: 8px;
                   6649:   background-color: $data_table_light;
                   6650: }
1.795     www      6651: 
1.579     raeburn  6652: span.LC_helpform_receipt_cat {
                   6653:   font-weight: bold;
                   6654: }
1.795     www      6655: 
1.424     albertel 6656: table.LC_group_priv_box {
                   6657:   background: white;
                   6658:   border: 1px solid black;
                   6659:   border-spacing: 1px;
                   6660: }
1.795     www      6661: 
1.424     albertel 6662: table.LC_group_priv_box td.LC_pick_box_title {
                   6663:   background: $tabbg;
                   6664:   font-weight: bold;
                   6665:   text-align: right;
                   6666:   width: 184px;
                   6667: }
1.795     www      6668: 
1.424     albertel 6669: table.LC_group_priv_box td.LC_groups_fixed {
                   6670:   background: $data_table_light;
                   6671:   text-align: center;
                   6672: }
1.795     www      6673: 
1.424     albertel 6674: table.LC_group_priv_box td.LC_groups_optional {
                   6675:   background: $data_table_dark;
                   6676:   text-align: center;
                   6677: }
1.795     www      6678: 
1.424     albertel 6679: table.LC_group_priv_box td.LC_groups_functionality {
                   6680:   background: $data_table_darker;
                   6681:   text-align: center;
                   6682:   font-weight: bold;
                   6683: }
1.795     www      6684: 
1.424     albertel 6685: table.LC_group_priv td {
                   6686:   text-align: left;
1.803     bisitz   6687:   padding: 0;
1.424     albertel 6688: }
                   6689: 
                   6690: .LC_navbuttons {
                   6691:   margin: 2ex 0ex 2ex 0ex;
                   6692: }
1.795     www      6693: 
1.423     albertel 6694: .LC_topic_bar {
                   6695:   font-weight: bold;
                   6696:   background: $tabbg;
1.918     wenzelju 6697:   margin: 1em 0em 1em 2em;
1.805     bisitz   6698:   padding: 3px;
1.918     wenzelju 6699:   font-size: 1.2em;
1.423     albertel 6700: }
1.795     www      6701: 
1.423     albertel 6702: .LC_topic_bar span {
1.918     wenzelju 6703:   left: 0.5em;
                   6704:   position: absolute;
1.423     albertel 6705:   vertical-align: middle;
1.918     wenzelju 6706:   font-size: 1.2em;
1.423     albertel 6707: }
1.795     www      6708: 
1.423     albertel 6709: table.LC_course_group_status {
                   6710:   margin: 20px;
                   6711: }
1.795     www      6712: 
1.423     albertel 6713: table.LC_status_selector td {
                   6714:   vertical-align: top;
                   6715:   text-align: center;
1.424     albertel 6716:   padding: 4px;
                   6717: }
1.795     www      6718: 
1.599     albertel 6719: div.LC_feedback_link {
1.616     albertel 6720:   clear: both;
1.829     kalberla 6721:   background: $sidebg;
1.779     bisitz   6722:   width: 100%;
1.829     kalberla 6723:   padding-bottom: 10px;
                   6724:   border: 1px $tabbg solid;
1.833     kalberla 6725:   height: 22px;
                   6726:   line-height: 22px;
                   6727:   padding-top: 5px;
                   6728: }
                   6729: 
                   6730: div.LC_feedback_link img {
                   6731:   height: 22px;
1.867     kalberla 6732:   vertical-align:middle;
1.829     kalberla 6733: }
                   6734: 
1.911     bisitz   6735: div.LC_feedback_link a {
1.829     kalberla 6736:   text-decoration: none;
1.489     raeburn  6737: }
1.795     www      6738: 
1.867     kalberla 6739: div.LC_comblock {
1.911     bisitz   6740:   display:inline;
1.867     kalberla 6741:   color:$font;
                   6742:   font-size:90%;
                   6743: }
                   6744: 
                   6745: div.LC_feedback_link div.LC_comblock {
                   6746:   padding-left:5px;
                   6747: }
                   6748: 
                   6749: div.LC_feedback_link div.LC_comblock a {
                   6750:   color:$font;
                   6751: }
                   6752: 
1.489     raeburn  6753: span.LC_feedback_link {
1.858     bisitz   6754:   /* background: $feedback_link_bg; */
1.599     albertel 6755:   font-size: larger;
                   6756: }
1.795     www      6757: 
1.599     albertel 6758: span.LC_message_link {
1.858     bisitz   6759:   /* background: $feedback_link_bg; */
1.599     albertel 6760:   font-size: larger;
                   6761:   position: absolute;
                   6762:   right: 1em;
1.489     raeburn  6763: }
1.421     albertel 6764: 
1.515     albertel 6765: table.LC_prior_tries {
1.524     albertel 6766:   border: 1px solid #000000;
                   6767:   border-collapse: separate;
                   6768:   border-spacing: 1px;
1.515     albertel 6769: }
1.523     albertel 6770: 
1.515     albertel 6771: table.LC_prior_tries td {
1.524     albertel 6772:   padding: 2px;
1.515     albertel 6773: }
1.523     albertel 6774: 
                   6775: .LC_answer_correct {
1.795     www      6776:   background: lightgreen;
                   6777:   color: darkgreen;
                   6778:   padding: 6px;
1.523     albertel 6779: }
1.795     www      6780: 
1.523     albertel 6781: .LC_answer_charged_try {
1.797     www      6782:   background: #FFAAAA;
1.795     www      6783:   color: darkred;
                   6784:   padding: 6px;
1.523     albertel 6785: }
1.795     www      6786: 
1.779     bisitz   6787: .LC_answer_not_charged_try,
1.523     albertel 6788: .LC_answer_no_grade,
                   6789: .LC_answer_late {
1.795     www      6790:   background: lightyellow;
1.523     albertel 6791:   color: black;
1.795     www      6792:   padding: 6px;
1.523     albertel 6793: }
1.795     www      6794: 
1.523     albertel 6795: .LC_answer_previous {
1.795     www      6796:   background: lightblue;
                   6797:   color: darkblue;
                   6798:   padding: 6px;
1.523     albertel 6799: }
1.795     www      6800: 
1.779     bisitz   6801: .LC_answer_no_message {
1.777     tempelho 6802:   background: #FFFFFF;
                   6803:   color: black;
1.795     www      6804:   padding: 6px;
1.779     bisitz   6805: }
1.795     www      6806: 
1.1075.2.140  raeburn  6807: .LC_answer_unknown,
                   6808: .LC_answer_warning {
1.779     bisitz   6809:   background: orange;
                   6810:   color: black;
1.795     www      6811:   padding: 6px;
1.777     tempelho 6812: }
1.795     www      6813: 
1.529     albertel 6814: span.LC_prior_numerical,
                   6815: span.LC_prior_string,
                   6816: span.LC_prior_custom,
                   6817: span.LC_prior_reaction,
                   6818: span.LC_prior_math {
1.925     bisitz   6819:   font-family: $mono;
1.523     albertel 6820:   white-space: pre;
                   6821: }
                   6822: 
1.525     albertel 6823: span.LC_prior_string {
1.925     bisitz   6824:   font-family: $mono;
1.525     albertel 6825:   white-space: pre;
                   6826: }
                   6827: 
1.523     albertel 6828: table.LC_prior_option {
                   6829:   width: 100%;
                   6830:   border-collapse: collapse;
                   6831: }
1.795     www      6832: 
1.911     bisitz   6833: table.LC_prior_rank,
1.795     www      6834: table.LC_prior_match {
1.528     albertel 6835:   border-collapse: collapse;
                   6836: }
1.795     www      6837: 
1.528     albertel 6838: table.LC_prior_option tr td,
                   6839: table.LC_prior_rank tr td,
                   6840: table.LC_prior_match tr td {
1.524     albertel 6841:   border: 1px solid #000000;
1.515     albertel 6842: }
                   6843: 
1.855     bisitz   6844: .LC_nobreak {
1.544     albertel 6845:   white-space: nowrap;
1.519     raeburn  6846: }
                   6847: 
1.576     raeburn  6848: span.LC_cusr_emph {
                   6849:   font-style: italic;
                   6850: }
                   6851: 
1.633     raeburn  6852: span.LC_cusr_subheading {
                   6853:   font-weight: normal;
                   6854:   font-size: 85%;
                   6855: }
                   6856: 
1.861     bisitz   6857: div.LC_docs_entry_move {
1.859     bisitz   6858:   border: 1px solid #BBBBBB;
1.545     albertel 6859:   background: #DDDDDD;
1.861     bisitz   6860:   width: 22px;
1.859     bisitz   6861:   padding: 1px;
                   6862:   margin: 0;
1.545     albertel 6863: }
                   6864: 
1.861     bisitz   6865: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6866: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6867:   font-size: x-small;
                   6868: }
1.795     www      6869: 
1.861     bisitz   6870: .LC_docs_entry_parameter {
                   6871:   white-space: nowrap;
                   6872: }
                   6873: 
1.544     albertel 6874: .LC_docs_copy {
1.545     albertel 6875:   color: #000099;
1.544     albertel 6876: }
1.795     www      6877: 
1.544     albertel 6878: .LC_docs_cut {
1.545     albertel 6879:   color: #550044;
1.544     albertel 6880: }
1.795     www      6881: 
1.544     albertel 6882: .LC_docs_rename {
1.545     albertel 6883:   color: #009900;
1.544     albertel 6884: }
1.795     www      6885: 
1.544     albertel 6886: .LC_docs_remove {
1.545     albertel 6887:   color: #990000;
                   6888: }
                   6889: 
1.1075.2.134  raeburn  6890: .LC_domprefs_email,
1.547     albertel 6891: .LC_docs_reinit_warn,
                   6892: .LC_docs_ext_edit {
                   6893:   font-size: x-small;
                   6894: }
                   6895: 
1.545     albertel 6896: table.LC_docs_adddocs td,
                   6897: table.LC_docs_adddocs th {
                   6898:   border: 1px solid #BBBBBB;
                   6899:   padding: 4px;
                   6900:   background: #DDDDDD;
1.543     albertel 6901: }
                   6902: 
1.584     albertel 6903: table.LC_sty_begin {
                   6904:   background: #BBFFBB;
                   6905: }
1.795     www      6906: 
1.584     albertel 6907: table.LC_sty_end {
                   6908:   background: #FFBBBB;
                   6909: }
                   6910: 
1.589     raeburn  6911: table.LC_double_column {
1.803     bisitz   6912:   border-width: 0;
1.589     raeburn  6913:   border-collapse: collapse;
                   6914:   width: 100%;
                   6915:   padding: 2px;
                   6916: }
                   6917: 
                   6918: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6919:   top: 2px;
1.589     raeburn  6920:   left: 2px;
                   6921:   width: 47%;
                   6922:   vertical-align: top;
                   6923: }
                   6924: 
                   6925: table.LC_double_column tr td.LC_right_col {
                   6926:   top: 2px;
1.779     bisitz   6927:   right: 2px;
1.589     raeburn  6928:   width: 47%;
                   6929:   vertical-align: top;
                   6930: }
                   6931: 
1.591     raeburn  6932: div.LC_left_float {
                   6933:   float: left;
                   6934:   padding-right: 5%;
1.597     albertel 6935:   padding-bottom: 4px;
1.591     raeburn  6936: }
                   6937: 
                   6938: div.LC_clear_float_header {
1.597     albertel 6939:   padding-bottom: 2px;
1.591     raeburn  6940: }
                   6941: 
                   6942: div.LC_clear_float_footer {
1.597     albertel 6943:   padding-top: 10px;
1.591     raeburn  6944:   clear: both;
                   6945: }
                   6946: 
1.597     albertel 6947: div.LC_grade_show_user {
1.941     bisitz   6948: /*  border-left: 5px solid $sidebg; */
                   6949:   border-top: 5px solid #000000;
                   6950:   margin: 50px 0 0 0;
1.936     bisitz   6951:   padding: 15px 0 5px 10px;
1.597     albertel 6952: }
1.795     www      6953: 
1.936     bisitz   6954: div.LC_grade_show_user_odd_row {
1.941     bisitz   6955: /*  border-left: 5px solid #000000; */
                   6956: }
                   6957: 
                   6958: div.LC_grade_show_user div.LC_Box {
                   6959:   margin-right: 50px;
1.597     albertel 6960: }
                   6961: 
                   6962: div.LC_grade_submissions,
                   6963: div.LC_grade_message_center,
1.936     bisitz   6964: div.LC_grade_info_links {
1.597     albertel 6965:   margin: 5px;
                   6966:   width: 99%;
                   6967:   background: #FFFFFF;
                   6968: }
1.795     www      6969: 
1.597     albertel 6970: div.LC_grade_submissions_header,
1.936     bisitz   6971: div.LC_grade_message_center_header {
1.705     tempelho 6972:   font-weight: bold;
                   6973:   font-size: large;
1.597     albertel 6974: }
1.795     www      6975: 
1.597     albertel 6976: div.LC_grade_submissions_body,
1.936     bisitz   6977: div.LC_grade_message_center_body {
1.597     albertel 6978:   border: 1px solid black;
                   6979:   width: 99%;
                   6980:   background: #FFFFFF;
                   6981: }
1.795     www      6982: 
1.613     albertel 6983: table.LC_scantron_action {
                   6984:   width: 100%;
                   6985: }
1.795     www      6986: 
1.613     albertel 6987: table.LC_scantron_action tr th {
1.698     harmsja  6988:   font-weight:bold;
                   6989:   font-style:normal;
1.613     albertel 6990: }
1.795     www      6991: 
1.779     bisitz   6992: .LC_edit_problem_header,
1.614     albertel 6993: div.LC_edit_problem_footer {
1.705     tempelho 6994:   font-weight: normal;
                   6995:   font-size:  medium;
1.602     albertel 6996:   margin: 2px;
1.1060    bisitz   6997:   background-color: $sidebg;
1.600     albertel 6998: }
1.795     www      6999: 
1.600     albertel 7000: div.LC_edit_problem_header,
1.602     albertel 7001: div.LC_edit_problem_header div,
1.614     albertel 7002: div.LC_edit_problem_footer,
                   7003: div.LC_edit_problem_footer div,
1.602     albertel 7004: div.LC_edit_problem_editxml_header,
                   7005: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7006:   z-index: 100;
1.600     albertel 7007: }
1.795     www      7008: 
1.600     albertel 7009: div.LC_edit_problem_header_title {
1.705     tempelho 7010:   font-weight: bold;
                   7011:   font-size: larger;
1.602     albertel 7012:   background: $tabbg;
                   7013:   padding: 3px;
1.1060    bisitz   7014:   margin: 0 0 5px 0;
1.602     albertel 7015: }
1.795     www      7016: 
1.602     albertel 7017: table.LC_edit_problem_header_title {
                   7018:   width: 100%;
1.600     albertel 7019:   background: $tabbg;
1.602     albertel 7020: }
                   7021: 
1.1075.2.112  raeburn  7022: div.LC_edit_actionbar {
                   7023:     background-color: $sidebg;
                   7024:     margin: 0;
                   7025:     padding: 0;
                   7026:     line-height: 200%;
1.602     albertel 7027: }
1.795     www      7028: 
1.1075.2.112  raeburn  7029: div.LC_edit_actionbar div{
                   7030:     padding: 0;
                   7031:     margin: 0;
                   7032:     display: inline-block;
1.600     albertel 7033: }
1.795     www      7034: 
1.1075.2.34  raeburn  7035: .LC_edit_opt {
                   7036:   padding-left: 1em;
                   7037:   white-space: nowrap;
                   7038: }
                   7039: 
1.1075.2.57  raeburn  7040: .LC_edit_problem_latexhelper{
                   7041:     text-align: right;
                   7042: }
                   7043: 
                   7044: #LC_edit_problem_colorful div{
                   7045:     margin-left: 40px;
                   7046: }
                   7047: 
1.1075.2.112  raeburn  7048: #LC_edit_problem_codemirror div{
                   7049:     margin-left: 0px;
                   7050: }
                   7051: 
1.911     bisitz   7052: img.stift {
1.803     bisitz   7053:   border-width: 0;
                   7054:   vertical-align: middle;
1.677     riegler  7055: }
1.680     riegler  7056: 
1.923     bisitz   7057: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7058:   vertical-align: top;
1.777     tempelho 7059: }
1.795     www      7060: 
1.716     raeburn  7061: div.LC_createcourse {
1.911     bisitz   7062:   margin: 10px 10px 10px 10px;
1.716     raeburn  7063: }
                   7064: 
1.917     raeburn  7065: .LC_dccid {
1.1075.2.38  raeburn  7066:   float: right;
1.917     raeburn  7067:   margin: 0.2em 0 0 0;
                   7068:   padding: 0;
                   7069:   font-size: 90%;
                   7070:   display:none;
                   7071: }
                   7072: 
1.897     wenzelju 7073: ol.LC_primary_menu a:hover,
1.721     harmsja  7074: ol#LC_MenuBreadcrumbs a:hover,
                   7075: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7076: ul#LC_secondary_menu a:hover,
1.721     harmsja  7077: .LC_FormSectionClearButton input:hover
1.795     www      7078: ul.LC_TabContent   li:hover a {
1.952     onken    7079:   color:$button_hover;
1.911     bisitz   7080:   text-decoration:none;
1.693     droeschl 7081: }
                   7082: 
1.779     bisitz   7083: h1 {
1.911     bisitz   7084:   padding: 0;
                   7085:   line-height:130%;
1.693     droeschl 7086: }
1.698     harmsja  7087: 
1.911     bisitz   7088: h2,
                   7089: h3,
                   7090: h4,
                   7091: h5,
                   7092: h6 {
                   7093:   margin: 5px 0 5px 0;
                   7094:   padding: 0;
                   7095:   line-height:130%;
1.693     droeschl 7096: }
1.795     www      7097: 
                   7098: .LC_hcell {
1.911     bisitz   7099:   padding:3px 15px 3px 15px;
                   7100:   margin: 0;
                   7101:   background-color:$tabbg;
                   7102:   color:$fontmenu;
                   7103:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7104: }
1.795     www      7105: 
1.840     bisitz   7106: .LC_Box > .LC_hcell {
1.911     bisitz   7107:   margin: 0 -10px 10px -10px;
1.835     bisitz   7108: }
                   7109: 
1.721     harmsja  7110: .LC_noBorder {
1.911     bisitz   7111:   border: 0;
1.698     harmsja  7112: }
1.693     droeschl 7113: 
1.721     harmsja  7114: .LC_FormSectionClearButton input {
1.911     bisitz   7115:   background-color:transparent;
                   7116:   border: none;
                   7117:   cursor:pointer;
                   7118:   text-decoration:underline;
1.693     droeschl 7119: }
1.763     bisitz   7120: 
                   7121: .LC_help_open_topic {
1.911     bisitz   7122:   color: #FFFFFF;
                   7123:   background-color: #EEEEFF;
                   7124:   margin: 1px;
                   7125:   padding: 4px;
                   7126:   border: 1px solid #000033;
                   7127:   white-space: nowrap;
                   7128:   /* vertical-align: middle; */
1.759     neumanie 7129: }
1.693     droeschl 7130: 
1.911     bisitz   7131: dl,
                   7132: ul,
                   7133: div,
                   7134: fieldset {
                   7135:   margin: 10px 10px 10px 0;
                   7136:   /* overflow: hidden; */
1.693     droeschl 7137: }
1.795     www      7138: 
1.1075.2.90  raeburn  7139: article.geogebraweb div {
                   7140:     margin: 0;
                   7141: }
                   7142: 
1.838     bisitz   7143: fieldset > legend {
1.911     bisitz   7144:   font-weight: bold;
                   7145:   padding: 0 5px 0 5px;
1.838     bisitz   7146: }
                   7147: 
1.813     bisitz   7148: #LC_nav_bar {
1.911     bisitz   7149:   float: left;
1.995     raeburn  7150:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7151:   margin: 0 0 2px 0;
1.807     droeschl 7152: }
                   7153: 
1.916     droeschl 7154: #LC_realm {
                   7155:   margin: 0.2em 0 0 0;
                   7156:   padding: 0;
                   7157:   font-weight: bold;
                   7158:   text-align: center;
1.995     raeburn  7159:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7160: }
                   7161: 
1.911     bisitz   7162: #LC_nav_bar em {
                   7163:   font-weight: bold;
                   7164:   font-style: normal;
1.807     droeschl 7165: }
                   7166: 
1.897     wenzelju 7167: ol.LC_primary_menu {
1.934     droeschl 7168:   margin: 0;
1.1075.2.2  raeburn  7169:   padding: 0;
1.807     droeschl 7170: }
                   7171: 
1.852     droeschl 7172: ol#LC_PathBreadcrumbs {
1.911     bisitz   7173:   margin: 0;
1.693     droeschl 7174: }
                   7175: 
1.897     wenzelju 7176: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7177:   color: RGB(80, 80, 80);
                   7178:   vertical-align: middle;
                   7179:   text-align: left;
                   7180:   list-style: none;
1.1075.2.112  raeburn  7181:   position: relative;
1.1075.2.2  raeburn  7182:   float: left;
1.1075.2.112  raeburn  7183:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7184:   line-height: 1.5em;
1.1075.2.2  raeburn  7185: }
                   7186: 
1.1075.2.113  raeburn  7187: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7188: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7189:   display: block;
                   7190:   margin: 0;
                   7191:   padding: 0 5px 0 10px;
                   7192:   text-decoration: none;
                   7193: }
                   7194: 
1.1075.2.112  raeburn  7195: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7196:   display: inline-block;
                   7197:   width: 95%;
                   7198:   text-align: left;
                   7199: }
                   7200: 
                   7201: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7202:   display: inline-block;
                   7203:   width: 5%;
                   7204:   float: right;
                   7205:   text-align: right;
                   7206:   font-size: 70%;
                   7207: }
                   7208: 
                   7209: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7210:   display: none;
1.1075.2.112  raeburn  7211:   width: 15em;
1.1075.2.2  raeburn  7212:   background-color: $data_table_light;
1.1075.2.112  raeburn  7213:   position: absolute;
                   7214:   top: 100%;
                   7215: }
                   7216: 
                   7217: ol.LC_primary_menu ul ul {
                   7218:   left: 100%;
                   7219:   top: 0;
1.1075.2.2  raeburn  7220: }
                   7221: 
1.1075.2.112  raeburn  7222: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7223:   display: block;
                   7224:   position: absolute;
                   7225:   margin: 0;
                   7226:   padding: 0;
1.1075.2.5  raeburn  7227:   z-index: 2;
1.1075.2.2  raeburn  7228: }
                   7229: 
                   7230: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7231: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7232:   font-size: 90%;
1.911     bisitz   7233:   vertical-align: top;
1.1075.2.2  raeburn  7234:   float: none;
1.1075.2.5  raeburn  7235:   border-left: 1px solid black;
                   7236:   border-right: 1px solid black;
1.1075.2.112  raeburn  7237: /* A dark bottom border to visualize different menu options;
                   7238: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7239:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7240: }
                   7241: 
1.1075.2.112  raeburn  7242: ol.LC_primary_menu li li p:hover {
                   7243:   color:$button_hover;
                   7244:   text-decoration:none;
                   7245:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7246: }
                   7247: 
                   7248: ol.LC_primary_menu li li a:hover {
                   7249:    color:$button_hover;
                   7250:    background-color:$data_table_dark;
1.693     droeschl 7251: }
                   7252: 
1.1075.2.112  raeburn  7253: /* Font-size equal to the size of the predecessors*/
                   7254: ol.LC_primary_menu li:hover li li {
                   7255:   font-size: 100%;
                   7256: }
                   7257: 
1.897     wenzelju 7258: ol.LC_primary_menu li img {
1.911     bisitz   7259:   vertical-align: bottom;
1.934     droeschl 7260:   height: 1.1em;
1.1075.2.3  raeburn  7261:   margin: 0.2em 0 0 0;
1.693     droeschl 7262: }
                   7263: 
1.897     wenzelju 7264: ol.LC_primary_menu a {
1.911     bisitz   7265:   color: RGB(80, 80, 80);
                   7266:   text-decoration: none;
1.693     droeschl 7267: }
1.795     www      7268: 
1.949     droeschl 7269: ol.LC_primary_menu a.LC_new_message {
                   7270:   font-weight:bold;
                   7271:   color: darkred;
                   7272: }
                   7273: 
1.975     raeburn  7274: ol.LC_docs_parameters {
                   7275:   margin-left: 0;
                   7276:   padding: 0;
                   7277:   list-style: none;
                   7278: }
                   7279: 
                   7280: ol.LC_docs_parameters li {
                   7281:   margin: 0;
                   7282:   padding-right: 20px;
                   7283:   display: inline;
                   7284: }
                   7285: 
1.976     raeburn  7286: ol.LC_docs_parameters li:before {
                   7287:   content: "\\002022 \\0020";
                   7288: }
                   7289: 
                   7290: li.LC_docs_parameters_title {
                   7291:   font-weight: bold;
                   7292: }
                   7293: 
                   7294: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7295:   content: "";
                   7296: }
                   7297: 
1.897     wenzelju 7298: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7299:   clear: right;
1.911     bisitz   7300:   color: $fontmenu;
                   7301:   background: $tabbg;
                   7302:   list-style: none;
                   7303:   padding: 0;
                   7304:   margin: 0;
                   7305:   width: 100%;
1.995     raeburn  7306:   text-align: left;
1.1075.2.4  raeburn  7307:   float: left;
1.808     droeschl 7308: }
                   7309: 
1.897     wenzelju 7310: ul#LC_secondary_menu li {
1.911     bisitz   7311:   font-weight: bold;
                   7312:   line-height: 1.8em;
                   7313:   border-right: 1px solid black;
1.1075.2.4  raeburn  7314:   float: left;
                   7315: }
                   7316: 
                   7317: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7318:   background-color: $data_table_light;
                   7319: }
                   7320: 
                   7321: ul#LC_secondary_menu li a {
                   7322:   padding: 0 0.8em;
                   7323: }
                   7324: 
                   7325: ul#LC_secondary_menu li ul {
                   7326:   display: none;
                   7327: }
                   7328: 
                   7329: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7330:   display: block;
                   7331:   position: absolute;
                   7332:   margin: 0;
                   7333:   padding: 0;
                   7334:   list-style:none;
                   7335:   float: none;
                   7336:   background-color: $data_table_light;
1.1075.2.5  raeburn  7337:   z-index: 2;
1.1075.2.10  raeburn  7338:   margin-left: -1px;
1.1075.2.4  raeburn  7339: }
                   7340: 
                   7341: ul#LC_secondary_menu li ul li {
                   7342:   font-size: 90%;
                   7343:   vertical-align: top;
                   7344:   border-left: 1px solid black;
                   7345:   border-right: 1px solid black;
1.1075.2.33  raeburn  7346:   background-color: $data_table_light;
1.1075.2.4  raeburn  7347:   list-style:none;
                   7348:   float: none;
                   7349: }
                   7350: 
                   7351: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7352:   background-color: $data_table_dark;
1.807     droeschl 7353: }
                   7354: 
1.847     tempelho 7355: ul.LC_TabContent {
1.911     bisitz   7356:   display:block;
                   7357:   background: $sidebg;
                   7358:   border-bottom: solid 1px $lg_border_color;
                   7359:   list-style:none;
1.1020    raeburn  7360:   margin: -1px -10px 0 -10px;
1.911     bisitz   7361:   padding: 0;
1.693     droeschl 7362: }
                   7363: 
1.795     www      7364: ul.LC_TabContent li,
                   7365: ul.LC_TabContentBigger li {
1.911     bisitz   7366:   float:left;
1.741     harmsja  7367: }
1.795     www      7368: 
1.897     wenzelju 7369: ul#LC_secondary_menu li a {
1.911     bisitz   7370:   color: $fontmenu;
                   7371:   text-decoration: none;
1.693     droeschl 7372: }
1.795     www      7373: 
1.721     harmsja  7374: ul.LC_TabContent {
1.952     onken    7375:   min-height:20px;
1.721     harmsja  7376: }
1.795     www      7377: 
                   7378: ul.LC_TabContent li {
1.911     bisitz   7379:   vertical-align:middle;
1.959     onken    7380:   padding: 0 16px 0 10px;
1.911     bisitz   7381:   background-color:$tabbg;
                   7382:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7383:   border-left: solid 1px $font;
1.721     harmsja  7384: }
1.795     www      7385: 
1.847     tempelho 7386: ul.LC_TabContent .right {
1.911     bisitz   7387:   float:right;
1.847     tempelho 7388: }
                   7389: 
1.911     bisitz   7390: ul.LC_TabContent li a,
                   7391: ul.LC_TabContent li {
                   7392:   color:rgb(47,47,47);
                   7393:   text-decoration:none;
                   7394:   font-size:95%;
                   7395:   font-weight:bold;
1.952     onken    7396:   min-height:20px;
                   7397: }
                   7398: 
1.959     onken    7399: ul.LC_TabContent li a:hover,
                   7400: ul.LC_TabContent li a:focus {
1.952     onken    7401:   color: $button_hover;
1.959     onken    7402:   background:none;
                   7403:   outline:none;
1.952     onken    7404: }
                   7405: 
                   7406: ul.LC_TabContent li:hover {
                   7407:   color: $button_hover;
                   7408:   cursor:pointer;
1.721     harmsja  7409: }
1.795     www      7410: 
1.911     bisitz   7411: ul.LC_TabContent li.active {
1.952     onken    7412:   color: $font;
1.911     bisitz   7413:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7414:   border-bottom:solid 1px #FFFFFF;
                   7415:   cursor: default;
1.744     ehlerst  7416: }
1.795     www      7417: 
1.959     onken    7418: ul.LC_TabContent li.active a {
                   7419:   color:$font;
                   7420:   background:#FFFFFF;
                   7421:   outline: none;
                   7422: }
1.1047    raeburn  7423: 
                   7424: ul.LC_TabContent li.goback {
                   7425:   float: left;
                   7426:   border-left: none;
                   7427: }
                   7428: 
1.870     tempelho 7429: #maincoursedoc {
1.911     bisitz   7430:   clear:both;
1.870     tempelho 7431: }
                   7432: 
                   7433: ul.LC_TabContentBigger {
1.911     bisitz   7434:   display:block;
                   7435:   list-style:none;
                   7436:   padding: 0;
1.870     tempelho 7437: }
                   7438: 
1.795     www      7439: ul.LC_TabContentBigger li {
1.911     bisitz   7440:   vertical-align:bottom;
                   7441:   height: 30px;
                   7442:   font-size:110%;
                   7443:   font-weight:bold;
                   7444:   color: #737373;
1.841     tempelho 7445: }
                   7446: 
1.957     onken    7447: ul.LC_TabContentBigger li.active {
                   7448:   position: relative;
                   7449:   top: 1px;
                   7450: }
                   7451: 
1.870     tempelho 7452: ul.LC_TabContentBigger li a {
1.911     bisitz   7453:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7454:   height: 30px;
                   7455:   line-height: 30px;
                   7456:   text-align: center;
                   7457:   display: block;
                   7458:   text-decoration: none;
1.958     onken    7459:   outline: none;  
1.741     harmsja  7460: }
1.795     www      7461: 
1.870     tempelho 7462: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7463:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7464:   color:$font;
1.744     ehlerst  7465: }
1.795     www      7466: 
1.870     tempelho 7467: ul.LC_TabContentBigger li b {
1.911     bisitz   7468:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7469:   display: block;
                   7470:   float: left;
                   7471:   padding: 0 30px;
1.957     onken    7472:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7473: }
                   7474: 
1.956     onken    7475: ul.LC_TabContentBigger li:hover b {
                   7476:   color:$button_hover;
                   7477: }
                   7478: 
1.870     tempelho 7479: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7480:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7481:   color:$font;
1.957     onken    7482:   border: 0;
1.741     harmsja  7483: }
1.693     droeschl 7484: 
1.870     tempelho 7485: 
1.862     bisitz   7486: ul.LC_CourseBreadcrumbs {
                   7487:   background: $sidebg;
1.1020    raeburn  7488:   height: 2em;
1.862     bisitz   7489:   padding-left: 10px;
1.1020    raeburn  7490:   margin: 0;
1.862     bisitz   7491:   list-style-position: inside;
                   7492: }
                   7493: 
1.911     bisitz   7494: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7495: ol#LC_PathBreadcrumbs {
1.911     bisitz   7496:   padding-left: 10px;
                   7497:   margin: 0;
1.933     droeschl 7498:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7499: }
                   7500: 
1.911     bisitz   7501: ol#LC_MenuBreadcrumbs li,
                   7502: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7503: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7504:   display: inline;
1.933     droeschl 7505:   white-space: normal;  
1.693     droeschl 7506: }
                   7507: 
1.823     bisitz   7508: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7509: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7510:   text-decoration: none;
                   7511:   font-size:90%;
1.693     droeschl 7512: }
1.795     www      7513: 
1.969     droeschl 7514: ol#LC_MenuBreadcrumbs h1 {
                   7515:   display: inline;
                   7516:   font-size: 90%;
                   7517:   line-height: 2.5em;
                   7518:   margin: 0;
                   7519:   padding: 0;
                   7520: }
                   7521: 
1.795     www      7522: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7523:   text-decoration:none;
                   7524:   font-size:100%;
                   7525:   font-weight:bold;
1.693     droeschl 7526: }
1.795     www      7527: 
1.840     bisitz   7528: .LC_Box {
1.911     bisitz   7529:   border: solid 1px $lg_border_color;
                   7530:   padding: 0 10px 10px 10px;
1.746     neumanie 7531: }
1.795     www      7532: 
1.1020    raeburn  7533: .LC_DocsBox {
                   7534:   border: solid 1px $lg_border_color;
                   7535:   padding: 0 0 10px 10px;
                   7536: }
                   7537: 
1.795     www      7538: .LC_AboutMe_Image {
1.911     bisitz   7539:   float:left;
                   7540:   margin-right:10px;
1.747     neumanie 7541: }
1.795     www      7542: 
                   7543: .LC_Clear_AboutMe_Image {
1.911     bisitz   7544:   clear:left;
1.747     neumanie 7545: }
1.795     www      7546: 
1.721     harmsja  7547: dl.LC_ListStyleClean dt {
1.911     bisitz   7548:   padding-right: 5px;
                   7549:   display: table-header-group;
1.693     droeschl 7550: }
                   7551: 
1.721     harmsja  7552: dl.LC_ListStyleClean dd {
1.911     bisitz   7553:   display: table-row;
1.693     droeschl 7554: }
                   7555: 
1.721     harmsja  7556: .LC_ListStyleClean,
                   7557: .LC_ListStyleSimple,
                   7558: .LC_ListStyleNormal,
1.795     www      7559: .LC_ListStyleSpecial {
1.911     bisitz   7560:   /* display:block; */
                   7561:   list-style-position: inside;
                   7562:   list-style-type: none;
                   7563:   overflow: hidden;
                   7564:   padding: 0;
1.693     droeschl 7565: }
                   7566: 
1.721     harmsja  7567: .LC_ListStyleSimple li,
                   7568: .LC_ListStyleSimple dd,
                   7569: .LC_ListStyleNormal li,
                   7570: .LC_ListStyleNormal dd,
                   7571: .LC_ListStyleSpecial li,
1.795     www      7572: .LC_ListStyleSpecial dd {
1.911     bisitz   7573:   margin: 0;
                   7574:   padding: 5px 5px 5px 10px;
                   7575:   clear: both;
1.693     droeschl 7576: }
                   7577: 
1.721     harmsja  7578: .LC_ListStyleClean li,
                   7579: .LC_ListStyleClean dd {
1.911     bisitz   7580:   padding-top: 0;
                   7581:   padding-bottom: 0;
1.693     droeschl 7582: }
                   7583: 
1.721     harmsja  7584: .LC_ListStyleSimple dd,
1.795     www      7585: .LC_ListStyleSimple li {
1.911     bisitz   7586:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7587: }
                   7588: 
1.721     harmsja  7589: .LC_ListStyleSpecial li,
                   7590: .LC_ListStyleSpecial dd {
1.911     bisitz   7591:   list-style-type: none;
                   7592:   background-color: RGB(220, 220, 220);
                   7593:   margin-bottom: 4px;
1.693     droeschl 7594: }
                   7595: 
1.721     harmsja  7596: table.LC_SimpleTable {
1.911     bisitz   7597:   margin:5px;
                   7598:   border:solid 1px $lg_border_color;
1.795     www      7599: }
1.693     droeschl 7600: 
1.721     harmsja  7601: table.LC_SimpleTable tr {
1.911     bisitz   7602:   padding: 0;
                   7603:   border:solid 1px $lg_border_color;
1.693     droeschl 7604: }
1.795     www      7605: 
                   7606: table.LC_SimpleTable thead {
1.911     bisitz   7607:   background:rgb(220,220,220);
1.693     droeschl 7608: }
                   7609: 
1.721     harmsja  7610: div.LC_columnSection {
1.911     bisitz   7611:   display: block;
                   7612:   clear: both;
                   7613:   overflow: hidden;
                   7614:   margin: 0;
1.693     droeschl 7615: }
                   7616: 
1.721     harmsja  7617: div.LC_columnSection>* {
1.911     bisitz   7618:   float: left;
                   7619:   margin: 10px 20px 10px 0;
                   7620:   overflow:hidden;
1.693     droeschl 7621: }
1.721     harmsja  7622: 
1.795     www      7623: table em {
1.911     bisitz   7624:   font-weight: bold;
                   7625:   font-style: normal;
1.748     schulted 7626: }
1.795     www      7627: 
1.779     bisitz   7628: table.LC_tableBrowseRes,
1.795     www      7629: table.LC_tableOfContent {
1.911     bisitz   7630:   border:none;
                   7631:   border-spacing: 1px;
                   7632:   padding: 3px;
                   7633:   background-color: #FFFFFF;
                   7634:   font-size: 90%;
1.753     droeschl 7635: }
1.789     droeschl 7636: 
1.911     bisitz   7637: table.LC_tableOfContent {
                   7638:   border-collapse: collapse;
1.789     droeschl 7639: }
                   7640: 
1.771     droeschl 7641: table.LC_tableBrowseRes a,
1.768     schulted 7642: table.LC_tableOfContent a {
1.911     bisitz   7643:   background-color: transparent;
                   7644:   text-decoration: none;
1.753     droeschl 7645: }
                   7646: 
1.795     www      7647: table.LC_tableOfContent img {
1.911     bisitz   7648:   border: none;
                   7649:   height: 1.3em;
                   7650:   vertical-align: text-bottom;
                   7651:   margin-right: 0.3em;
1.753     droeschl 7652: }
1.757     schulted 7653: 
1.795     www      7654: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7655:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7656: }
                   7657: 
1.795     www      7658: a#LC_content_toolbar_everything {
1.911     bisitz   7659:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7660: }
                   7661: 
1.795     www      7662: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7663:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7664: }
                   7665: 
1.795     www      7666: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7667:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7668: }
                   7669: 
1.795     www      7670: a#LC_content_toolbar_changefolder {
1.911     bisitz   7671:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7672: }
                   7673: 
1.795     www      7674: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7675:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7676: }
                   7677: 
1.1043    raeburn  7678: a#LC_content_toolbar_edittoplevel {
                   7679:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7680: }
                   7681: 
1.795     www      7682: ul#LC_toolbar li a:hover {
1.911     bisitz   7683:   background-position: bottom center;
1.757     schulted 7684: }
                   7685: 
1.795     www      7686: ul#LC_toolbar {
1.911     bisitz   7687:   padding: 0;
                   7688:   margin: 2px;
                   7689:   list-style:none;
                   7690:   position:relative;
                   7691:   background-color:white;
1.1075.2.9  raeburn  7692:   overflow: auto;
1.757     schulted 7693: }
                   7694: 
1.795     www      7695: ul#LC_toolbar li {
1.911     bisitz   7696:   border:1px solid white;
                   7697:   padding: 0;
                   7698:   margin: 0;
                   7699:   float: left;
                   7700:   display:inline;
                   7701:   vertical-align:middle;
1.1075.2.9  raeburn  7702:   white-space: nowrap;
1.911     bisitz   7703: }
1.757     schulted 7704: 
1.783     amueller 7705: 
1.795     www      7706: a.LC_toolbarItem {
1.911     bisitz   7707:   display:block;
                   7708:   padding: 0;
                   7709:   margin: 0;
                   7710:   height: 32px;
                   7711:   width: 32px;
                   7712:   color:white;
                   7713:   border: none;
                   7714:   background-repeat:no-repeat;
                   7715:   background-color:transparent;
1.757     schulted 7716: }
                   7717: 
1.915     droeschl 7718: ul.LC_funclist {
                   7719:     margin: 0;
                   7720:     padding: 0.5em 1em 0.5em 0;
                   7721: }
                   7722: 
1.933     droeschl 7723: ul.LC_funclist > li:first-child {
                   7724:     font-weight:bold; 
                   7725:     margin-left:0.8em;
                   7726: }
                   7727: 
1.915     droeschl 7728: ul.LC_funclist + ul.LC_funclist {
                   7729:     /* 
                   7730:        left border as a seperator if we have more than
                   7731:        one list 
                   7732:     */
                   7733:     border-left: 1px solid $sidebg;
                   7734:     /* 
                   7735:        this hides the left border behind the border of the 
                   7736:        outer box if element is wrapped to the next 'line' 
                   7737:     */
                   7738:     margin-left: -1px;
                   7739: }
                   7740: 
1.843     bisitz   7741: ul.LC_funclist li {
1.915     droeschl 7742:   display: inline;
1.782     bisitz   7743:   white-space: nowrap;
1.915     droeschl 7744:   margin: 0 0 0 25px;
                   7745:   line-height: 150%;
1.782     bisitz   7746: }
                   7747: 
1.974     wenzelju 7748: .LC_hidden {
                   7749:   display: none;
                   7750: }
                   7751: 
1.1030    www      7752: .LCmodal-overlay {
                   7753: 		position:fixed;
                   7754: 		top:0;
                   7755: 		right:0;
                   7756: 		bottom:0;
                   7757: 		left:0;
                   7758: 		height:100%;
                   7759: 		width:100%;
                   7760: 		margin:0;
                   7761: 		padding:0;
                   7762: 		background:#999;
                   7763: 		opacity:.75;
                   7764: 		filter: alpha(opacity=75);
                   7765: 		-moz-opacity: 0.75;
                   7766: 		z-index:101;
                   7767: }
                   7768: 
                   7769: * html .LCmodal-overlay {   
                   7770: 		position: absolute;
                   7771: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7772: }
                   7773: 
                   7774: .LCmodal-window {
                   7775: 		position:fixed;
                   7776: 		top:50%;
                   7777: 		left:50%;
                   7778: 		margin:0;
                   7779: 		padding:0;
                   7780: 		z-index:102;
                   7781: 	}
                   7782: 
                   7783: * html .LCmodal-window {
                   7784: 		position:absolute;
                   7785: }
                   7786: 
                   7787: .LCclose-window {
                   7788: 		position:absolute;
                   7789: 		width:32px;
                   7790: 		height:32px;
                   7791: 		right:8px;
                   7792: 		top:8px;
                   7793: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7794: 		text-indent:-99999px;
                   7795: 		overflow:hidden;
                   7796: 		cursor:pointer;
                   7797: }
                   7798: 
1.1075.2.141  raeburn  7799: pre.LC_wordwrap {
                   7800:   white-space: pre-wrap;
                   7801:   white-space: -moz-pre-wrap;
                   7802:   white-space: -pre-wrap;
                   7803:   white-space: -o-pre-wrap;
                   7804:   word-wrap: break-word;
                   7805: }
                   7806: 
1.1075.2.17  raeburn  7807: /*
                   7808:   styles used by TTH when "Default set of options to pass to tth/m
                   7809:   when converting TeX" in course settings has been set
                   7810: 
                   7811:   option passed: -t
                   7812: 
                   7813: */
                   7814: 
                   7815: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7816: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7817: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7818: td div.norm {line-height:normal;}
                   7819: 
                   7820: /*
                   7821:   option passed -y3
                   7822: */
                   7823: 
                   7824: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7825: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7826: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7827: 
1.1075.2.121  raeburn  7828: #LC_minitab_header {
                   7829:   float:left;
                   7830:   width:100%;
                   7831:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7832:   font-size:93%;
                   7833:   line-height:normal;
                   7834:   margin: 0.5em 0 0.5em 0;
                   7835: }
                   7836: #LC_minitab_header ul {
                   7837:   margin:0;
                   7838:   padding:10px 10px 0;
                   7839:   list-style:none;
                   7840: }
                   7841: #LC_minitab_header li {
                   7842:   float:left;
                   7843:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7844:   margin:0;
                   7845:   padding:0 0 0 9px;
                   7846: }
                   7847: #LC_minitab_header a {
                   7848:   display:block;
                   7849:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7850:   padding:5px 15px 4px 6px;
                   7851: }
                   7852: #LC_minitab_header #LC_current_minitab {
                   7853:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7854: }
                   7855: #LC_minitab_header #LC_current_minitab a {
                   7856:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7857:   padding-bottom:5px;
                   7858: }
                   7859: 
                   7860: 
1.343     albertel 7861: END
                   7862: }
                   7863: 
1.306     albertel 7864: =pod
                   7865: 
                   7866: =item * &headtag()
                   7867: 
                   7868: Returns a uniform footer for LON-CAPA web pages.
                   7869: 
1.307     albertel 7870: Inputs: $title - optional title for the head
                   7871:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7872:         $args - optional arguments
1.319     albertel 7873:             force_register - if is true call registerurl so the remote is 
                   7874:                              informed
1.415     albertel 7875:             redirect       -> array ref of
                   7876:                                    1- seconds before redirect occurs
                   7877:                                    2- url to redirect to
                   7878:                                    3- whether the side effect should occur
1.315     albertel 7879:                            (side effect of setting 
                   7880:                                $env{'internal.head.redirect'} to the url 
                   7881:                                redirected too)
1.352     albertel 7882:             domain         -> force to color decorate a page for a specific
                   7883:                                domain
                   7884:             function       -> force usage of a specific rolish color scheme
                   7885:             bgcolor        -> override the default page bgcolor
1.460     albertel 7886:             no_auto_mt_title
                   7887:                            -> prevent &mt()ing the title arg
1.464     albertel 7888: 
1.306     albertel 7889: =cut
                   7890: 
                   7891: sub headtag {
1.313     albertel 7892:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7893:     
1.363     albertel 7894:     my $function = $args->{'function'} || &get_users_function();
                   7895:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7896:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7897:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7898:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7899: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7900: 		   #time(),
1.418     albertel 7901: 		   $env{'environment.color.timestamp'},
1.363     albertel 7902: 		   $function,$domain,$bgcolor);
                   7903: 
1.369     www      7904:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7905: 
1.308     albertel 7906:     my $result =
                   7907: 	'<head>'.
1.1075.2.56  raeburn  7908: 	&font_settings($args);
1.319     albertel 7909: 
1.1075.2.72  raeburn  7910:     my $inhibitprint;
                   7911:     if ($args->{'print_suppress'}) {
                   7912:         $inhibitprint = &print_suppression();
                   7913:     }
1.1064    raeburn  7914: 
1.461     albertel 7915:     if (!$args->{'frameset'}) {
                   7916: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7917:     }
1.1075.2.12  raeburn  7918:     if ($args->{'force_register'}) {
                   7919:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7920:     }
1.436     albertel 7921:     if (!$args->{'no_nav_bar'} 
                   7922: 	&& !$args->{'only_body'}
                   7923: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7924: 	$result .= &help_menu_js($httphost);
1.1032    www      7925:         $result.=&modal_window();
1.1038    www      7926:         $result.=&togglebox_script();
1.1034    www      7927:         $result.=&wishlist_window();
1.1041    www      7928:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7929:     } else {
                   7930:         if ($args->{'add_modal'}) {
                   7931:            $result.=&modal_window();
                   7932:         }
                   7933:         if ($args->{'add_wishlist'}) {
                   7934:            $result.=&wishlist_window();
                   7935:         }
1.1038    www      7936:         if ($args->{'add_togglebox'}) {
                   7937:            $result.=&togglebox_script();
                   7938:         }
1.1041    www      7939:         if ($args->{'add_progressbar'}) {
                   7940:            $result.=&LCprogressbarUpdate_script();
                   7941:         }
1.436     albertel 7942:     }
1.314     albertel 7943:     if (ref($args->{'redirect'})) {
1.414     albertel 7944: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7945: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7946: 	if (!$inhibit_continue) {
                   7947: 	    $env{'internal.head.redirect'} = $url;
                   7948: 	}
1.313     albertel 7949: 	$result.=<<ADDMETA
                   7950: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7951: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7952: ADDMETA
1.1075.2.89  raeburn  7953:     } else {
                   7954:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7955:             my $requrl = $env{'request.uri'};
                   7956:             if ($requrl eq '') {
                   7957:                 $requrl = $ENV{'REQUEST_URI'};
                   7958:                 $requrl =~ s/\?.+$//;
                   7959:             }
                   7960:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7961:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7962:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7963:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7964:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7965:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.141.  .4(raebu 7966:20):                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7967:20):                     my $offload;
1.1075.2.89  raeburn  7968:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7969:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.141.  .4(raebu 7970:20):                             $offload = 1;
                   7971:20):                         }
                   7972:20):                     }
                   7973:20):                     unless ($offload) {
                   7974:20):                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   7975:20):                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   7976:20):                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   7977:20):                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   7978:20):                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   7979:20):                                         $offload = 1;
                   7980:20):                                         $dom_in_use = $env{'user.domain'};
                   7981:20):                                     }
1.1075.2.89  raeburn  7982:                                 }
1.1075.2.141.  .4(raebu 7983:20):                             }
                   7984:20):                         }
                   7985:20):                     }
                   7986:20):                     if ($offload) {
                   7987:20):                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7988:20):                         if (($newserver) && ($newserver ne $lonhost)) {
                   7989:20):                             my $numsec = 5;
                   7990:20):                             my $timeout = $numsec * 1000;
                   7991:20):                             my ($newurl,$locknum,%locks,$msg);
                   7992:20):                             if ($env{'request.role.adv'}) {
                   7993:20):                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7994:20):                             }
                   7995:20):                             my $disable_submit = 0;
                   7996:20):                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   7997:20):                                 $disable_submit = 1;
                   7998:20):                             }
                   7999:20):                             if ($locknum) {
                   8000:20):                                 my @lockinfo = sort(values(%locks));
                   8001:20):                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   8002:20):                                        join(", ",sort(values(%locks)))."\n";
                   8003:20):                                 if (&show_course()) {
                   8004:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8005:                                 } else {
1.1075.2.141.  .4(raebu 8006:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8007:20):                                 }
                   8008:20):                             } else {
                   8009:20):                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8010:20):                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8011:20):                                 }
                   8012:20):                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8013:20):                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8014:20):                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8015:20):                                     $newurl .= '&role='.$env{'request.role'};
                   8016:20):                                 }
                   8017:20):                                 if ($env{'request.symb'}) {
                   8018:20):                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8019:20):                                     if ($shownsymb =~ m{^/enc/}) {
                   8020:20):                                         my $reqdmajor = 2;
                   8021:20):                                         my $reqdminor = 11;
                   8022:20):                                         my $reqdsubminor = 3;
                   8023:20):                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8024:20):                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8025:20):                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8026:20):                                         if (($major eq '' && $minor eq '') ||
                   8027:20):                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8028:20):                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8029:20):                                              ($reqdsubminor > $subminor))))) {
                   8030:20):                                             undef($shownsymb);
                   8031:20):                                         }
1.1075.2.89  raeburn  8032:                                     }
1.1075.2.141.  .4(raebu 8033:20):                                     if ($shownsymb) {
                   8034:20):                                         &js_escape(\$shownsymb);
                   8035:20):                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8036:                                     }
1.1075.2.141.  .4(raebu 8037:20):                                 } else {
                   8038:20):                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8039:20):                                     &js_escape(\$shownurl);
                   8040:20):                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8041:                                 }
1.1075.2.141.  .4(raebu 8042:20):                             }
                   8043:20):                             &js_escape(\$msg);
                   8044:20):                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8045: <meta http-equiv="pragma" content="no-cache" />
                   8046: <script type="text/javascript">
1.1075.2.92  raeburn  8047: // <![CDATA[
1.1075.2.89  raeburn  8048: function LC_Offload_Now() {
                   8049:     var dest = "$newurl";
                   8050:     if (dest != '') {
                   8051:         window.location.href="$newurl";
                   8052:     }
                   8053: }
1.1075.2.92  raeburn  8054: \$(document).ready(function () {
                   8055:     window.alert('$msg');
                   8056:     if ($disable_submit) {
1.1075.2.89  raeburn  8057:         \$(".LC_hwk_submit").prop("disabled", true);
                   8058:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8059:     }
                   8060:     setTimeout('LC_Offload_Now()', $timeout);
                   8061: });
                   8062: // ]]>
1.1075.2.89  raeburn  8063: </script>
                   8064: OFFLOAD
                   8065:                         }
                   8066:                     }
                   8067:                 }
                   8068:             }
                   8069:         }
1.313     albertel 8070:     }
1.306     albertel 8071:     if (!defined($title)) {
                   8072: 	$title = 'The LearningOnline Network with CAPA';
                   8073:     }
1.460     albertel 8074:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8075:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8076: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8077:     if (!$args->{'frameset'}) {
                   8078:         $result .= ' /';
                   8079:     }
                   8080:     $result .= '>'
1.1064    raeburn  8081:         .$inhibitprint
1.414     albertel 8082: 	.$head_extra;
1.1075.2.108  raeburn  8083:     my $clientmobile;
                   8084:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8085:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8086:     } else {
                   8087:         $clientmobile = $env{'browser.mobile'};
                   8088:     }
                   8089:     if ($clientmobile) {
1.1075.2.42  raeburn  8090:         $result .= '
                   8091: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8092: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8093:     }
1.1075.2.126  raeburn  8094:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8095:     return $result.'</head>';
1.306     albertel 8096: }
                   8097: 
                   8098: =pod
                   8099: 
1.340     albertel 8100: =item * &font_settings()
                   8101: 
                   8102: Returns neccessary <meta> to set the proper encoding
                   8103: 
1.1075.2.56  raeburn  8104: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8105: 
                   8106: =cut
                   8107: 
                   8108: sub font_settings {
1.1075.2.56  raeburn  8109:     my ($args) = @_;
1.340     albertel 8110:     my $headerstring='';
1.1075.2.56  raeburn  8111:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8112:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8113: 	$headerstring.=
1.1075.2.61  raeburn  8114: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8115:         if (!$args->{'frameset'}) {
                   8116:             $headerstring.= ' /';
                   8117:         }
                   8118:         $headerstring .= '>'."\n";
1.340     albertel 8119:     }
                   8120:     return $headerstring;
                   8121: }
                   8122: 
1.341     albertel 8123: =pod
                   8124: 
1.1064    raeburn  8125: =item * &print_suppression()
                   8126: 
                   8127: In course context returns css which causes the body to be blank when media="print",
                   8128: if printout generation is unavailable for the current resource.
                   8129: 
                   8130: This could be because:
                   8131: 
                   8132: (a) printstartdate is in the future
                   8133: 
                   8134: (b) printenddate is in the past
                   8135: 
                   8136: (c) there is an active exam block with "printout"
                   8137: functionality blocked
                   8138: 
                   8139: Users with pav, pfo or evb privileges are exempt.
                   8140: 
                   8141: Inputs: none
                   8142: 
                   8143: =cut
                   8144: 
                   8145: 
                   8146: sub print_suppression {
                   8147:     my $noprint;
                   8148:     if ($env{'request.course.id'}) {
                   8149:         my $scope = $env{'request.course.id'};
                   8150:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8151:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8152:             return;
                   8153:         }
                   8154:         if ($env{'request.course.sec'} ne '') {
                   8155:             $scope .= "/$env{'request.course.sec'}";
                   8156:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8157:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8158:                 return;
1.1064    raeburn  8159:             }
                   8160:         }
                   8161:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8162:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8163:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8164:         if ($blocked) {
                   8165:             my $checkrole = "cm./$cdom/$cnum";
                   8166:             if ($env{'request.course.sec'} ne '') {
                   8167:                 $checkrole .= "/$env{'request.course.sec'}";
                   8168:             }
                   8169:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8170:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8171:                 $noprint = 1;
                   8172:             }
                   8173:         }
                   8174:         unless ($noprint) {
                   8175:             my $symb = &Apache::lonnet::symbread();
                   8176:             if ($symb ne '') {
                   8177:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8178:                 if (ref($navmap)) {
                   8179:                     my $res = $navmap->getBySymb($symb);
                   8180:                     if (ref($res)) {
                   8181:                         if (!$res->resprintable()) {
                   8182:                             $noprint = 1;
                   8183:                         }
                   8184:                     }
                   8185:                 }
                   8186:             }
                   8187:         }
                   8188:         if ($noprint) {
                   8189:             return <<"ENDSTYLE";
                   8190: <style type="text/css" media="print">
                   8191:     body { display:none }
                   8192: </style>
                   8193: ENDSTYLE
                   8194:         }
                   8195:     }
                   8196:     return;
                   8197: }
                   8198: 
                   8199: =pod
                   8200: 
1.341     albertel 8201: =item * &xml_begin()
                   8202: 
                   8203: Returns the needed doctype and <html>
                   8204: 
                   8205: Inputs: none
                   8206: 
                   8207: =cut
                   8208: 
                   8209: sub xml_begin {
1.1075.2.61  raeburn  8210:     my ($is_frameset) = @_;
1.341     albertel 8211:     my $output='';
                   8212: 
                   8213:     if ($env{'browser.mathml'}) {
                   8214: 	$output='<?xml version="1.0"?>'
                   8215:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8216: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8217:             
                   8218: #	    .'<!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">] >'
                   8219: 	    .'<!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">'
                   8220:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8221: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8222:     } elsif ($is_frameset) {
                   8223:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8224:                 '<html>'."\n";
1.341     albertel 8225:     } else {
1.1075.2.61  raeburn  8226: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8227:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8228:     }
                   8229:     return $output;
                   8230: }
1.340     albertel 8231: 
                   8232: =pod
                   8233: 
1.306     albertel 8234: =item * &start_page()
                   8235: 
                   8236: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8237: 
1.648     raeburn  8238: Inputs:
                   8239: 
                   8240: =over 4
                   8241: 
                   8242: $title - optional title for the page
                   8243: 
                   8244: $head_extra - optional extra HTML to incude inside the <head>
                   8245: 
                   8246: $args - additional optional args supported are:
                   8247: 
                   8248: =over 8
                   8249: 
                   8250:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8251:                                     arg on
1.814     bisitz   8252:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8253:              add_entries    -> additional attributes to add to the  <body>
                   8254:              domain         -> force to color decorate a page for a 
1.317     albertel 8255:                                     specific domain
1.648     raeburn  8256:              function       -> force usage of a specific rolish color
1.317     albertel 8257:                                     scheme
1.648     raeburn  8258:              redirect       -> see &headtag()
                   8259:              bgcolor        -> override the default page bg color
                   8260:              js_ready       -> return a string ready for being used in 
1.317     albertel 8261:                                     a javascript writeln
1.648     raeburn  8262:              html_encode    -> return a string ready for being used in 
1.320     albertel 8263:                                     a html attribute
1.648     raeburn  8264:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8265:                                     $forcereg arg
1.648     raeburn  8266:              frameset       -> if true will start with a <frameset>
1.330     albertel 8267:                                     rather than <body>
1.648     raeburn  8268:              skip_phases    -> hash ref of 
1.338     albertel 8269:                                     head -> skip the <html><head> generation
                   8270:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8271:              no_inline_link -> if true and in remote mode, don't show the
                   8272:                                     'Switch To Inline Menu' link
1.648     raeburn  8273:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8274:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8275:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8276:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8277:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8278:              group          -> includes the current group, if page is for a
                   8279:                                specific group
1.1075.2.133  raeburn  8280:              use_absolute   -> for request for external resource or syllabus, this
                   8281:                                will contain https://<hostname> if server uses
                   8282:                                https (as per hosts.tab), but request is for http
                   8283:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8284: 
1.648     raeburn  8285: =back
1.460     albertel 8286: 
1.648     raeburn  8287: =back
1.562     albertel 8288: 
1.306     albertel 8289: =cut
                   8290: 
                   8291: sub start_page {
1.309     albertel 8292:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8293:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8294: 
1.315     albertel 8295:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8296:     my ($result,@advtools);
1.964     droeschl 8297: 
1.338     albertel 8298:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8299:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8300:     }
                   8301:     
                   8302:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8303: 	if ($args->{'frameset'}) {
                   8304: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8305: 						$args->{'add_entries'});
                   8306: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8307:         } else {
                   8308:             $result .=
                   8309:                 &bodytag($title, 
                   8310:                          $args->{'function'},       $args->{'add_entries'},
                   8311:                          $args->{'only_body'},      $args->{'domain'},
                   8312:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8313:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8314:                          $args,                     \@advtools);
1.831     bisitz   8315:         }
1.330     albertel 8316:     }
1.338     albertel 8317: 
1.315     albertel 8318:     if ($args->{'js_ready'}) {
1.713     kaisler  8319: 		$result = &js_ready($result);
1.315     albertel 8320:     }
1.320     albertel 8321:     if ($args->{'html_encode'}) {
1.713     kaisler  8322: 		$result = &html_encode($result);
                   8323:     }
                   8324: 
1.813     bisitz   8325:     # Preparation for new and consistent functionlist at top of screen
                   8326:     # if ($args->{'functionlist'}) {
                   8327:     #            $result .= &build_functionlist();
                   8328:     #}
                   8329: 
1.964     droeschl 8330:     # Don't add anything more if only_body wanted or in const space
                   8331:     return $result if    $args->{'only_body'} 
                   8332:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8333: 
                   8334:     #Breadcrumbs
1.758     kaisler  8335:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8336: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8337: 		#if any br links exists, add them to the breadcrumbs
                   8338: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8339: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8340: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8341: 			}
                   8342: 		}
1.1075.2.19  raeburn  8343:                 # if @advtools array contains items add then to the breadcrumbs
                   8344:                 if (@advtools > 0) {
                   8345:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8346:                 }
1.1075.2.123  raeburn  8347:                 my $menulink;
                   8348:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8349:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8350:                     $menulink = 0;
                   8351:                 } else {
                   8352:                     undef($menulink);
                   8353:                 }
1.758     kaisler  8354: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8355: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8356: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8357: 		}else{
1.1075.2.123  raeburn  8358: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8359: 		}
1.1075.2.24  raeburn  8360:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8361:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8362:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8363:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8364:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8365:     }
1.315     albertel 8366:     return $result;
1.306     albertel 8367: }
                   8368: 
                   8369: sub end_page {
1.315     albertel 8370:     my ($args) = @_;
                   8371:     $env{'internal.end_page'}++;
1.330     albertel 8372:     my $result;
1.335     albertel 8373:     if ($args->{'discussion'}) {
                   8374: 	my ($target,$parser);
                   8375: 	if (ref($args->{'discussion'})) {
                   8376: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8377: 				$args->{'discussion'}{'parser'});
                   8378: 	}
                   8379: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8380:     }
1.330     albertel 8381:     if ($args->{'frameset'}) {
                   8382: 	$result .= '</frameset>';
                   8383:     } else {
1.635     raeburn  8384: 	$result .= &endbodytag($args);
1.330     albertel 8385:     }
1.1075.2.6  raeburn  8386:     unless ($args->{'notbody'}) {
                   8387:         $result .= "\n</html>";
                   8388:     }
1.330     albertel 8389: 
1.315     albertel 8390:     if ($args->{'js_ready'}) {
1.317     albertel 8391: 	$result = &js_ready($result);
1.315     albertel 8392:     }
1.335     albertel 8393: 
1.320     albertel 8394:     if ($args->{'html_encode'}) {
                   8395: 	$result = &html_encode($result);
                   8396:     }
1.335     albertel 8397: 
1.315     albertel 8398:     return $result;
                   8399: }
                   8400: 
1.1034    www      8401: sub wishlist_window {
                   8402:     return(<<'ENDWISHLIST');
1.1046    raeburn  8403: <script type="text/javascript">
1.1034    www      8404: // <![CDATA[
                   8405: // <!-- BEGIN LON-CAPA Internal
                   8406: function set_wishlistlink(title, path) {
                   8407:     if (!title) {
                   8408:         title = document.title;
                   8409:         title = title.replace(/^LON-CAPA /,'');
                   8410:     }
1.1075.2.65  raeburn  8411:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8412:     title = title.replace("'","\\\'");
1.1034    www      8413:     if (!path) {
                   8414:         path = location.pathname;
                   8415:     }
1.1075.2.65  raeburn  8416:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8417:     path = path.replace("'","\\\'");
1.1034    www      8418:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8419:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8420: }
                   8421: // END LON-CAPA Internal -->
                   8422: // ]]>
                   8423: </script>
                   8424: ENDWISHLIST
                   8425: }
                   8426: 
1.1030    www      8427: sub modal_window {
                   8428:     return(<<'ENDMODAL');
1.1046    raeburn  8429: <script type="text/javascript">
1.1030    www      8430: // <![CDATA[
                   8431: // <!-- BEGIN LON-CAPA Internal
                   8432: var modalWindow = {
                   8433: 	parent:"body",
                   8434: 	windowId:null,
                   8435: 	content:null,
                   8436: 	width:null,
                   8437: 	height:null,
                   8438: 	close:function()
                   8439: 	{
                   8440: 	        $(".LCmodal-window").remove();
                   8441: 	        $(".LCmodal-overlay").remove();
                   8442: 	},
                   8443: 	open:function()
                   8444: 	{
                   8445: 		var modal = "";
                   8446: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8447: 		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;\">";
                   8448: 		modal += this.content;
                   8449: 		modal += "</div>";	
                   8450: 
                   8451: 		$(this.parent).append(modal);
                   8452: 
                   8453: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8454: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8455: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8456: 	}
                   8457: };
1.1075.2.42  raeburn  8458: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8459: 	{
1.1075.2.119  raeburn  8460:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8461: 		modalWindow.windowId = "myModal";
                   8462: 		modalWindow.width = width;
                   8463: 		modalWindow.height = height;
1.1075.2.80  raeburn  8464: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8465: 		modalWindow.open();
1.1075.2.87  raeburn  8466: 	};
1.1030    www      8467: // END LON-CAPA Internal -->
                   8468: // ]]>
                   8469: </script>
                   8470: ENDMODAL
                   8471: }
                   8472: 
                   8473: sub modal_link {
1.1075.2.42  raeburn  8474:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8475:     unless ($width) { $width=480; }
                   8476:     unless ($height) { $height=400; }
1.1031    www      8477:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8478:     unless ($transparency) { $transparency='true'; }
                   8479: 
1.1074    raeburn  8480:     my $target_attr;
                   8481:     if (defined($target)) {
                   8482:         $target_attr = 'target="'.$target.'"';
                   8483:     }
                   8484:     return <<"ENDLINK";
1.1075.2.141.  .3(raebu 8485:20): <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8486: ENDLINK
1.1030    www      8487: }
                   8488: 
1.1032    www      8489: sub modal_adhoc_script {
                   8490:     my ($funcname,$width,$height,$content)=@_;
                   8491:     return (<<ENDADHOC);
1.1046    raeburn  8492: <script type="text/javascript">
1.1032    www      8493: // <![CDATA[
                   8494:         var $funcname = function()
                   8495:         {
                   8496:                 modalWindow.windowId = "myModal";
                   8497:                 modalWindow.width = $width;
                   8498:                 modalWindow.height = $height;
                   8499:                 modalWindow.content = '$content';
                   8500:                 modalWindow.open();
                   8501:         };  
                   8502: // ]]>
                   8503: </script>
                   8504: ENDADHOC
                   8505: }
                   8506: 
1.1041    www      8507: sub modal_adhoc_inner {
                   8508:     my ($funcname,$width,$height,$content)=@_;
                   8509:     my $innerwidth=$width-20;
                   8510:     $content=&js_ready(
1.1042    www      8511:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8512:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8513:                  $content.
1.1041    www      8514:                  &end_scrollbox().
1.1075.2.42  raeburn  8515:                  &end_page()
1.1041    www      8516:              );
                   8517:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8518: }
                   8519: 
                   8520: sub modal_adhoc_window {
                   8521:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8522:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8523:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8524: }
                   8525: 
                   8526: sub modal_adhoc_launch {
                   8527:     my ($funcname,$width,$height,$content)=@_;
                   8528:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8529: <script type="text/javascript">
                   8530: // <![CDATA[
                   8531: $funcname();
                   8532: // ]]>
                   8533: </script>
                   8534: ENDLAUNCH
                   8535: }
                   8536: 
                   8537: sub modal_adhoc_close {
                   8538:     return (<<ENDCLOSE);
                   8539: <script type="text/javascript">
                   8540: // <![CDATA[
                   8541: modalWindow.close();
                   8542: // ]]>
                   8543: </script>
                   8544: ENDCLOSE
                   8545: }
                   8546: 
1.1038    www      8547: sub togglebox_script {
                   8548:    return(<<ENDTOGGLE);
                   8549: <script type="text/javascript"> 
                   8550: // <![CDATA[
                   8551: function LCtoggleDisplay(id,hidetext,showtext) {
                   8552:    link = document.getElementById(id + "link").childNodes[0];
                   8553:    with (document.getElementById(id).style) {
                   8554:       if (display == "none" ) {
                   8555:           display = "inline";
                   8556:           link.nodeValue = hidetext;
                   8557:         } else {
                   8558:           display = "none";
                   8559:           link.nodeValue = showtext;
                   8560:        }
                   8561:    }
                   8562: }
                   8563: // ]]>
                   8564: </script>
                   8565: ENDTOGGLE
                   8566: }
                   8567: 
1.1039    www      8568: sub start_togglebox {
                   8569:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8570:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8571:     unless ($showtext) { $showtext=&mt('show'); }
                   8572:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8573:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8574:     return &start_data_table().
                   8575:            &start_data_table_header_row().
                   8576:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8577:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8578:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8579:            &end_data_table_header_row().
                   8580:            '<tr id="'.$id.'" style="display:none""><td>';
                   8581: }
                   8582: 
                   8583: sub end_togglebox {
                   8584:     return '</td></tr>'.&end_data_table();
                   8585: }
                   8586: 
1.1041    www      8587: sub LCprogressbar_script {
1.1075.2.130  raeburn  8588:    my ($id,$number_to_do)=@_;
                   8589:    if ($number_to_do) {
                   8590:        return(<<ENDPROGRESS);
1.1041    www      8591: <script type="text/javascript">
                   8592: // <![CDATA[
1.1045    www      8593: \$('#progressbar$id').progressbar({
1.1041    www      8594:   value: 0,
                   8595:   change: function(event, ui) {
                   8596:     var newVal = \$(this).progressbar('option', 'value');
                   8597:     \$('.pblabel', this).text(LCprogressTxt);
                   8598:   }
                   8599: });
                   8600: // ]]>
                   8601: </script>
                   8602: ENDPROGRESS
1.1075.2.130  raeburn  8603:    } else {
                   8604:        return(<<ENDPROGRESS);
                   8605: <script type="text/javascript">
                   8606: // <![CDATA[
                   8607: \$('#progressbar$id').progressbar({
                   8608:   value: false,
                   8609:   create: function(event, ui) {
                   8610:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8611:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8612:   }
                   8613: });
                   8614: // ]]>
                   8615: </script>
                   8616: ENDPROGRESS
                   8617:    }
1.1041    www      8618: }
                   8619: 
                   8620: sub LCprogressbarUpdate_script {
                   8621:    return(<<ENDPROGRESSUPDATE);
                   8622: <style type="text/css">
                   8623: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8624: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      8625: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8626: </style>
                   8627: <script type="text/javascript">
                   8628: // <![CDATA[
1.1045    www      8629: var LCprogressTxt='---';
                   8630: 
1.1075.2.130  raeburn  8631: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8632:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8633:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8634:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8635:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8636:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8637:    } else {
                   8638:        \$('#progressbar'+id).progressbar('value',percent);
                   8639:    }
1.1041    www      8640: }
                   8641: // ]]>
                   8642: </script>
                   8643: ENDPROGRESSUPDATE
                   8644: }
                   8645: 
1.1042    www      8646: my $LClastpercent;
1.1045    www      8647: my $LCidcnt;
                   8648: my $LCcurrentid;
1.1042    www      8649: 
1.1041    www      8650: sub LCprogressbar {
1.1075.2.130  raeburn  8651:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8652:     $LClastpercent=0;
1.1045    www      8653:     $LCidcnt++;
                   8654:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8655:     my ($starting,$content);
                   8656:     if ($number_to_do) {
                   8657:         $starting=&mt('Starting');
                   8658:         $content=(<<ENDPROGBAR);
                   8659: $preamble
1.1045    www      8660:   <div id="progressbar$LCcurrentid">
1.1041    www      8661:     <span class="pblabel">$starting</span>
                   8662:   </div>
                   8663: ENDPROGBAR
1.1075.2.130  raeburn  8664:     } else {
                   8665:         $starting=&mt('Loading...');
                   8666:         $LClastpercent='false';
                   8667:         $content=(<<ENDPROGBAR);
                   8668: $preamble
                   8669:   <div id="progressbar$LCcurrentid">
                   8670:       <div class="progress-label">$starting</div>
                   8671:   </div>
                   8672: ENDPROGBAR
                   8673:     }
                   8674:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8675: }
                   8676: 
                   8677: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8678:     my ($r,$val,$text,$number_to_do)=@_;
                   8679:     if ($number_to_do) {
                   8680:         unless ($val) { 
                   8681:             if ($LClastpercent) {
                   8682:                 $val=$LClastpercent;
                   8683:             } else {
                   8684:                 $val=0;
                   8685:             }
                   8686:         }
                   8687:         if ($val<0) { $val=0; }
                   8688:         if ($val>100) { $val=0; }
                   8689:         $LClastpercent=$val;
                   8690:         unless ($text) { $text=$val.'%'; }
                   8691:     } else {
                   8692:         $val = 'false';
1.1042    www      8693:     }
1.1041    www      8694:     $text=&js_ready($text);
1.1044    www      8695:     &r_print($r,<<ENDUPDATE);
1.1041    www      8696: <script type="text/javascript">
                   8697: // <![CDATA[
1.1075.2.130  raeburn  8698: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8699: // ]]>
                   8700: </script>
                   8701: ENDUPDATE
1.1035    www      8702: }
                   8703: 
1.1042    www      8704: sub LCprogressbarClose {
                   8705:     my ($r)=@_;
                   8706:     $LClastpercent=0;
1.1044    www      8707:     &r_print($r,<<ENDCLOSE);
1.1042    www      8708: <script type="text/javascript">
                   8709: // <![CDATA[
1.1045    www      8710: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8711: // ]]>
                   8712: </script>
                   8713: ENDCLOSE
1.1044    www      8714: }
                   8715: 
                   8716: sub r_print {
                   8717:     my ($r,$to_print)=@_;
                   8718:     if ($r) {
                   8719:       $r->print($to_print);
                   8720:       $r->rflush();
                   8721:     } else {
                   8722:       print($to_print);
                   8723:     }
1.1042    www      8724: }
                   8725: 
1.320     albertel 8726: sub html_encode {
                   8727:     my ($result) = @_;
                   8728: 
1.322     albertel 8729:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8730:     
                   8731:     return $result;
                   8732: }
1.1044    www      8733: 
1.317     albertel 8734: sub js_ready {
                   8735:     my ($result) = @_;
                   8736: 
1.323     albertel 8737:     $result =~ s/[\n\r]/ /xmsg;
                   8738:     $result =~ s/\\/\\\\/xmsg;
                   8739:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8740:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8741:     
                   8742:     return $result;
                   8743: }
                   8744: 
1.315     albertel 8745: sub validate_page {
                   8746:     if (  exists($env{'internal.start_page'})
1.316     albertel 8747: 	  &&     $env{'internal.start_page'} > 1) {
                   8748: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8749: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8750: 				 $ENV{'request.filename'});
1.315     albertel 8751:     }
                   8752:     if (  exists($env{'internal.end_page'})
1.316     albertel 8753: 	  &&     $env{'internal.end_page'} > 1) {
                   8754: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8755: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8756: 				 $env{'request.filename'});
1.315     albertel 8757:     }
                   8758:     if (     exists($env{'internal.start_page'})
                   8759: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8760: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8761: 				 $env{'request.filename'});
1.315     albertel 8762:     }
                   8763:     if (   ! exists($env{'internal.start_page'})
                   8764: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8765: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8766: 				 $env{'request.filename'});
1.315     albertel 8767:     }
1.306     albertel 8768: }
1.315     albertel 8769: 
1.996     www      8770: 
                   8771: sub start_scrollbox {
1.1075.2.56  raeburn  8772:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8773:     unless ($outerwidth) { $outerwidth='520px'; }
                   8774:     unless ($width) { $width='500px'; }
                   8775:     unless ($height) { $height='200px'; }
1.1075    raeburn  8776:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8777:     if ($id ne '') {
1.1075.2.42  raeburn  8778:         $table_id = ' id="table_'.$id.'"';
                   8779:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8780:     }
1.1075    raeburn  8781:     if ($bgcolor ne '') {
                   8782:         $tdcol = "background-color: $bgcolor;";
                   8783:     }
1.1075.2.42  raeburn  8784:     my $nicescroll_js;
                   8785:     if ($env{'browser.mobile'}) {
                   8786:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8787:     }
1.1075    raeburn  8788:     return <<"END";
1.1075.2.42  raeburn  8789: $nicescroll_js
                   8790: 
                   8791: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8792: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8793: END
1.996     www      8794: }
                   8795: 
                   8796: sub end_scrollbox {
1.1036    www      8797:     return '</div></td></tr></table>';
1.996     www      8798: }
                   8799: 
1.1075.2.42  raeburn  8800: sub nicescroll_javascript {
                   8801:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8802:     my %options;
                   8803:     if (ref($cursor) eq 'HASH') {
                   8804:         %options = %{$cursor};
                   8805:     }
                   8806:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8807:         $options{'railalign'} = 'left';
                   8808:     }
                   8809:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8810:         my $function  = &get_users_function();
                   8811:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8812:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8813:             $options{'cursorcolor'} = '#00F';
                   8814:         }
                   8815:     }
                   8816:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8817:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8818:             $options{'cursoropacity'}='1.0';
                   8819:         }
                   8820:     } else {
                   8821:         $options{'cursoropacity'}='1.0';
                   8822:     }
                   8823:     if ($options{'cursorfixedheight'} eq 'none') {
                   8824:         delete($options{'cursorfixedheight'});
                   8825:     } else {
                   8826:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8827:     }
                   8828:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8829:         delete($options{'railoffset'});
                   8830:     }
                   8831:     my @niceoptions;
                   8832:     while (my($key,$value) = each(%options)) {
                   8833:         if ($value =~ /^\{.+\}$/) {
                   8834:             push(@niceoptions,$key.':'.$value);
                   8835:         } else {
                   8836:             push(@niceoptions,$key.':"'.$value.'"');
                   8837:         }
                   8838:     }
                   8839:     my $nicescroll_js = '
                   8840: $(document).ready(
                   8841:       function() {
                   8842:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8843:       }
                   8844: );
                   8845: ';
                   8846:     if ($framecheck) {
                   8847:         $nicescroll_js .= '
                   8848: function expand_div(caller) {
                   8849:     if (top === self) {
                   8850:         document.getElementById("'.$id.'").style.width = "auto";
                   8851:         document.getElementById("'.$id.'").style.height = "auto";
                   8852:     } else {
                   8853:         try {
                   8854:             if (parent.frames) {
                   8855:                 if (parent.frames.length > 1) {
                   8856:                     var framesrc = parent.frames[1].location.href;
                   8857:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8858:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8859:                         document.getElementById("'.$id.'").style.width = "auto";
                   8860:                         document.getElementById("'.$id.'").style.height = "auto";
                   8861:                     }
                   8862:                 }
                   8863:             }
                   8864:         } catch (e) {
                   8865:             return;
                   8866:         }
                   8867:     }
                   8868:     return;
                   8869: }
                   8870: ';
                   8871:     }
                   8872:     if ($needjsready) {
                   8873:         $nicescroll_js = '
                   8874: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8875:     } else {
                   8876:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8877:     }
                   8878:     return $nicescroll_js;
                   8879: }
                   8880: 
1.318     albertel 8881: sub simple_error_page {
1.1075.2.49  raeburn  8882:     my ($r,$title,$msg,$args) = @_;
                   8883:     if (ref($args) eq 'HASH') {
                   8884:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8885:     } else {
                   8886:         $msg = &mt($msg);
                   8887:     }
                   8888: 
1.318     albertel 8889:     my $page =
                   8890: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8891: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8892: 	&Apache::loncommon::end_page();
                   8893:     if (ref($r)) {
                   8894: 	$r->print($page);
1.327     albertel 8895: 	return;
1.318     albertel 8896:     }
                   8897:     return $page;
                   8898: }
1.347     albertel 8899: 
                   8900: {
1.610     albertel 8901:     my @row_count;
1.961     onken    8902: 
                   8903:     sub start_data_table_count {
                   8904:         unshift(@row_count, 0);
                   8905:         return;
                   8906:     }
                   8907: 
                   8908:     sub end_data_table_count {
                   8909:         shift(@row_count);
                   8910:         return;
                   8911:     }
                   8912: 
1.347     albertel 8913:     sub start_data_table {
1.1018    raeburn  8914: 	my ($add_class,$id) = @_;
1.422     albertel 8915: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8916:         my $table_id;
                   8917:         if (defined($id)) {
                   8918:             $table_id = ' id="'.$id.'"';
                   8919:         }
1.961     onken    8920: 	&start_data_table_count();
1.1018    raeburn  8921: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8922:     }
                   8923: 
                   8924:     sub end_data_table {
1.961     onken    8925: 	&end_data_table_count();
1.389     albertel 8926: 	return '</table>'."\n";;
1.347     albertel 8927:     }
                   8928: 
                   8929:     sub start_data_table_row {
1.974     wenzelju 8930: 	my ($add_class, $id) = @_;
1.610     albertel 8931: 	$row_count[0]++;
                   8932: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8933: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8934:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8935:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8936:     }
1.471     banghart 8937:     
                   8938:     sub continue_data_table_row {
1.974     wenzelju 8939: 	my ($add_class, $id) = @_;
1.610     albertel 8940: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8941: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8942:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8943:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8944:     }
1.347     albertel 8945: 
                   8946:     sub end_data_table_row {
1.389     albertel 8947: 	return '</tr>'."\n";;
1.347     albertel 8948:     }
1.367     www      8949: 
1.421     albertel 8950:     sub start_data_table_empty_row {
1.707     bisitz   8951: #	$row_count[0]++;
1.421     albertel 8952: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8953:     }
                   8954: 
                   8955:     sub end_data_table_empty_row {
                   8956: 	return '</tr>'."\n";;
                   8957:     }
                   8958: 
1.367     www      8959:     sub start_data_table_header_row {
1.389     albertel 8960: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8961:     }
                   8962: 
                   8963:     sub end_data_table_header_row {
1.389     albertel 8964: 	return '</tr>'."\n";;
1.367     www      8965:     }
1.890     droeschl 8966: 
                   8967:     sub data_table_caption {
                   8968:         my $caption = shift;
                   8969:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8970:     }
1.347     albertel 8971: }
                   8972: 
1.548     albertel 8973: =pod
                   8974: 
                   8975: =item * &inhibit_menu_check($arg)
                   8976: 
                   8977: Checks for a inhibitmenu state and generates output to preserve it
                   8978: 
                   8979: Inputs:         $arg - can be any of
                   8980:                      - undef - in which case the return value is a string 
                   8981:                                to add  into arguments list of a uri
                   8982:                      - 'input' - in which case the return value is a HTML
                   8983:                                  <form> <input> field of type hidden to
                   8984:                                  preserve the value
                   8985:                      - a url - in which case the return value is the url with
                   8986:                                the neccesary cgi args added to preserve the
                   8987:                                inhibitmenu state
                   8988:                      - a ref to a url - no return value, but the string is
                   8989:                                         updated to include the neccessary cgi
                   8990:                                         args to preserve the inhibitmenu state
                   8991: 
                   8992: =cut
                   8993: 
                   8994: sub inhibit_menu_check {
                   8995:     my ($arg) = @_;
                   8996:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8997:     if ($arg eq 'input') {
                   8998: 	if ($env{'form.inhibitmenu'}) {
                   8999: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9000: 	} else {
                   9001: 	    return
                   9002: 	}
                   9003:     }
                   9004:     if ($env{'form.inhibitmenu'}) {
                   9005: 	if (ref($arg)) {
                   9006: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9007: 	} elsif ($arg eq '') {
                   9008: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9009: 	} else {
                   9010: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9011: 	}
                   9012:     }
                   9013:     if (!ref($arg)) {
                   9014: 	return $arg;
                   9015:     }
                   9016: }
                   9017: 
1.251     albertel 9018: ###############################################
1.182     matthew  9019: 
                   9020: =pod
                   9021: 
1.549     albertel 9022: =back
                   9023: 
                   9024: =head1 User Information Routines
                   9025: 
                   9026: =over 4
                   9027: 
1.405     albertel 9028: =item * &get_users_function()
1.182     matthew  9029: 
                   9030: Used by &bodytag to determine the current users primary role.
                   9031: Returns either 'student','coordinator','admin', or 'author'.
                   9032: 
                   9033: =cut
                   9034: 
                   9035: ###############################################
                   9036: sub get_users_function {
1.815     tempelho 9037:     my $function = 'norole';
1.818     tempelho 9038:     if ($env{'request.role'}=~/^(st)/) {
                   9039:         $function='student';
                   9040:     }
1.907     raeburn  9041:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9042:         $function='coordinator';
                   9043:     }
1.258     albertel 9044:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9045:         $function='admin';
                   9046:     }
1.826     bisitz   9047:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9048:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9049:         $function='author';
                   9050:     }
                   9051:     return $function;
1.54      www      9052: }
1.99      www      9053: 
                   9054: ###############################################
                   9055: 
1.233     raeburn  9056: =pod
                   9057: 
1.821     raeburn  9058: =item * &show_course()
                   9059: 
                   9060: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9061: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9062: 
                   9063: Inputs:
                   9064: None
                   9065: 
                   9066: Outputs:
                   9067: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9068: 
                   9069: =cut
                   9070: 
                   9071: ###############################################
                   9072: sub show_course {
                   9073:     my $course = !$env{'user.adv'};
                   9074:     if (!$env{'user.adv'}) {
                   9075:         foreach my $env (keys(%env)) {
                   9076:             next if ($env !~ m/^user\.priv\./);
                   9077:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9078:                 $course = 0;
                   9079:                 last;
                   9080:             }
                   9081:         }
                   9082:     }
                   9083:     return $course;
                   9084: }
                   9085: 
                   9086: ###############################################
                   9087: 
                   9088: =pod
                   9089: 
1.542     raeburn  9090: =item * &check_user_status()
1.274     raeburn  9091: 
                   9092: Determines current status of supplied role for a
                   9093: specific user. Roles can be active, previous or future.
                   9094: 
                   9095: Inputs: 
                   9096: user's domain, user's username, course's domain,
1.375     raeburn  9097: course's number, optional section ID.
1.274     raeburn  9098: 
                   9099: Outputs:
                   9100: role status: active, previous or future. 
                   9101: 
                   9102: =cut
                   9103: 
                   9104: sub check_user_status {
1.412     raeburn  9105:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9106:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9107:     my @uroles = keys(%userinfo);
1.274     raeburn  9108:     my $srchstr;
                   9109:     my $active_chk = 'none';
1.412     raeburn  9110:     my $now = time;
1.274     raeburn  9111:     if (@uroles > 0) {
1.908     raeburn  9112:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9113:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9114:         } else {
1.412     raeburn  9115:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9116:         }
                   9117:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9118:             my $role_end = 0;
                   9119:             my $role_start = 0;
                   9120:             $active_chk = 'active';
1.412     raeburn  9121:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9122:                 $role_end = $1;
                   9123:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9124:                     $role_start = $1;
1.274     raeburn  9125:                 }
                   9126:             }
                   9127:             if ($role_start > 0) {
1.412     raeburn  9128:                 if ($now < $role_start) {
1.274     raeburn  9129:                     $active_chk = 'future';
                   9130:                 }
                   9131:             }
                   9132:             if ($role_end > 0) {
1.412     raeburn  9133:                 if ($now > $role_end) {
1.274     raeburn  9134:                     $active_chk = 'previous';
                   9135:                 }
                   9136:             }
                   9137:         }
                   9138:     }
                   9139:     return $active_chk;
                   9140: }
                   9141: 
                   9142: ###############################################
                   9143: 
                   9144: =pod
                   9145: 
1.405     albertel 9146: =item * &get_sections()
1.233     raeburn  9147: 
                   9148: Determines all the sections for a course including
                   9149: sections with students and sections containing other roles.
1.419     raeburn  9150: Incoming parameters: 
                   9151: 
                   9152: 1. domain
                   9153: 2. course number 
                   9154: 3. reference to array containing roles for which sections should 
                   9155: be gathered (optional).
                   9156: 4. reference to array containing status types for which sections 
                   9157: should be gathered (optional).
                   9158: 
                   9159: If the third argument is undefined, sections are gathered for any role. 
                   9160: If the fourth argument is undefined, sections are gathered for any status.
                   9161: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9162:  
1.374     raeburn  9163: Returns section hash (keys are section IDs, values are
                   9164: number of users in each section), subject to the
1.419     raeburn  9165: optional roles filter, optional status filter 
1.233     raeburn  9166: 
                   9167: =cut
                   9168: 
                   9169: ###############################################
                   9170: sub get_sections {
1.419     raeburn  9171:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9172:     if (!defined($cdom) || !defined($cnum)) {
                   9173:         my $cid =  $env{'request.course.id'};
                   9174: 
                   9175: 	return if (!defined($cid));
                   9176: 
                   9177:         $cdom = $env{'course.'.$cid.'.domain'};
                   9178:         $cnum = $env{'course.'.$cid.'.num'};
                   9179:     }
                   9180: 
                   9181:     my %sectioncount;
1.419     raeburn  9182:     my $now = time;
1.240     albertel 9183: 
1.1075.2.33  raeburn  9184:     my $check_students = 1;
                   9185:     my $only_students = 0;
                   9186:     if (ref($possible_roles) eq 'ARRAY') {
                   9187:         if (grep(/^st$/,@{$possible_roles})) {
                   9188:             if (@{$possible_roles} == 1) {
                   9189:                 $only_students = 1;
                   9190:             }
                   9191:         } else {
                   9192:             $check_students = 0;
                   9193:         }
                   9194:     }
                   9195: 
                   9196:     if ($check_students) {
1.276     albertel 9197: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9198: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9199: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9200:         my $start_index = &Apache::loncoursedata::CL_START();
                   9201:         my $end_index = &Apache::loncoursedata::CL_END();
                   9202:         my $status;
1.366     albertel 9203: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9204: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9205: 				                     $data->[$status_index],
                   9206:                                                      $data->[$start_index],
                   9207:                                                      $data->[$end_index]);
                   9208:             if ($stu_status eq 'Active') {
                   9209:                 $status = 'active';
                   9210:             } elsif ($end < $now) {
                   9211:                 $status = 'previous';
                   9212:             } elsif ($start > $now) {
                   9213:                 $status = 'future';
                   9214:             } 
                   9215: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9216:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9217:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9218: 		    $sectioncount{$section}++;
                   9219:                 }
1.240     albertel 9220: 	    }
                   9221: 	}
                   9222:     }
1.1075.2.33  raeburn  9223:     if ($only_students) {
                   9224:         return %sectioncount;
                   9225:     }
1.240     albertel 9226:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9227:     foreach my $user (sort(keys(%courseroles))) {
                   9228: 	if ($user !~ /^(\w{2})/) { next; }
                   9229: 	my ($role) = ($user =~ /^(\w{2})/);
                   9230: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9231: 	my ($section,$status);
1.240     albertel 9232: 	if ($role eq 'cr' &&
                   9233: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9234: 	    $section=$1;
                   9235: 	}
                   9236: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9237: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9238:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9239:         if ($end == -1 && $start == -1) {
                   9240:             next; #deleted role
                   9241:         }
                   9242:         if (!defined($possible_status)) { 
                   9243:             $sectioncount{$section}++;
                   9244:         } else {
                   9245:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9246:                 $status = 'active';
                   9247:             } elsif ($end < $now) {
                   9248:                 $status = 'future';
                   9249:             } elsif ($start > $now) {
                   9250:                 $status = 'previous';
                   9251:             }
                   9252:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9253:                 $sectioncount{$section}++;
                   9254:             }
                   9255:         }
1.233     raeburn  9256:     }
1.366     albertel 9257:     return %sectioncount;
1.233     raeburn  9258: }
                   9259: 
1.274     raeburn  9260: ###############################################
1.294     raeburn  9261: 
                   9262: =pod
1.405     albertel 9263: 
                   9264: =item * &get_course_users()
                   9265: 
1.275     raeburn  9266: Retrieves usernames:domains for users in the specified course
                   9267: with specific role(s), and access status. 
                   9268: 
                   9269: Incoming parameters:
1.277     albertel 9270: 1. course domain
                   9271: 2. course number
                   9272: 3. access status: users must have - either active, 
1.275     raeburn  9273: previous, future, or all.
1.277     albertel 9274: 4. reference to array of permissible roles
1.288     raeburn  9275: 5. reference to array of section restrictions (optional)
                   9276: 6. reference to results object (hash of hashes).
                   9277: 7. reference to optional userdata hash
1.609     raeburn  9278: 8. reference to optional statushash
1.630     raeburn  9279: 9. flag if privileged users (except those set to unhide in
                   9280:    course settings) should be excluded    
1.609     raeburn  9281: Keys of top level results hash are roles.
1.275     raeburn  9282: Keys of inner hashes are username:domain, with 
                   9283: values set to access type.
1.288     raeburn  9284: Optional userdata hash returns an array with arguments in the 
                   9285: same order as loncoursedata::get_classlist() for student data.
                   9286: 
1.609     raeburn  9287: Optional statushash returns
                   9288: 
1.288     raeburn  9289: Entries for end, start, section and status are blank because
                   9290: of the possibility of multiple values for non-student roles.
                   9291: 
1.275     raeburn  9292: =cut
1.405     albertel 9293: 
1.275     raeburn  9294: ###############################################
1.405     albertel 9295: 
1.275     raeburn  9296: sub get_course_users {
1.630     raeburn  9297:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9298:     my %idx = ();
1.419     raeburn  9299:     my %seclists;
1.288     raeburn  9300: 
                   9301:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9302:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9303:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9304:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9305:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9306:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9307:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9308:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9309: 
1.290     albertel 9310:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9311:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9312:         my $now = time;
1.277     albertel 9313:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9314:             my $match = 0;
1.412     raeburn  9315:             my $secmatch = 0;
1.419     raeburn  9316:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9317:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9318:             if ($section eq '') {
                   9319:                 $section = 'none';
                   9320:             }
1.291     albertel 9321:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9322:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9323:                     $secmatch = 1;
                   9324:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9325:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9326:                         $secmatch = 1;
                   9327:                     }
                   9328:                 } else {  
1.419     raeburn  9329: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9330: 		        $secmatch = 1;
                   9331:                     }
1.290     albertel 9332: 		}
1.412     raeburn  9333:                 if (!$secmatch) {
                   9334:                     next;
                   9335:                 }
1.419     raeburn  9336:             }
1.275     raeburn  9337:             if (defined($$types{'active'})) {
1.288     raeburn  9338:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9339:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9340:                     $match = 1;
1.275     raeburn  9341:                 }
                   9342:             }
                   9343:             if (defined($$types{'previous'})) {
1.609     raeburn  9344:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9345:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9346:                     $match = 1;
1.275     raeburn  9347:                 }
                   9348:             }
                   9349:             if (defined($$types{'future'})) {
1.609     raeburn  9350:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9351:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9352:                     $match = 1;
1.275     raeburn  9353:                 }
                   9354:             }
1.609     raeburn  9355:             if ($match) {
                   9356:                 push(@{$seclists{$student}},$section);
                   9357:                 if (ref($userdata) eq 'HASH') {
                   9358:                     $$userdata{$student} = $$classlist{$student};
                   9359:                 }
                   9360:                 if (ref($statushash) eq 'HASH') {
                   9361:                     $statushash->{$student}{'st'}{$section} = $status;
                   9362:                 }
1.288     raeburn  9363:             }
1.275     raeburn  9364:         }
                   9365:     }
1.412     raeburn  9366:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9367:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9368:         my $now = time;
1.609     raeburn  9369:         my %displaystatus = ( previous => 'Expired',
                   9370:                               active   => 'Active',
                   9371:                               future   => 'Future',
                   9372:                             );
1.1075.2.36  raeburn  9373:         my (%nothide,@possdoms);
1.630     raeburn  9374:         if ($hidepriv) {
                   9375:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9376:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9377:                 if ($user !~ /:/) {
                   9378:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9379:                 } else {
                   9380:                     $nothide{$user} = 1;
                   9381:                 }
                   9382:             }
1.1075.2.36  raeburn  9383:             my @possdoms = ($cdom);
                   9384:             if ($coursehash{'checkforpriv'}) {
                   9385:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9386:             }
1.630     raeburn  9387:         }
1.439     raeburn  9388:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9389:             my $match = 0;
1.412     raeburn  9390:             my $secmatch = 0;
1.439     raeburn  9391:             my $status;
1.412     raeburn  9392:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9393:             $user =~ s/:$//;
1.439     raeburn  9394:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9395:             if ($end == -1 || $start == -1) {
                   9396:                 next;
                   9397:             }
                   9398:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9399:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9400:                 my ($uname,$udom) = split(/:/,$user);
                   9401:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9402:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9403:                         $secmatch = 1;
                   9404:                     } elsif ($usec eq '') {
1.420     albertel 9405:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9406:                             $secmatch = 1;
                   9407:                         }
                   9408:                     } else {
                   9409:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9410:                             $secmatch = 1;
                   9411:                         }
                   9412:                     }
                   9413:                     if (!$secmatch) {
                   9414:                         next;
                   9415:                     }
1.288     raeburn  9416:                 }
1.419     raeburn  9417:                 if ($usec eq '') {
                   9418:                     $usec = 'none';
                   9419:                 }
1.275     raeburn  9420:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9421:                     if ($hidepriv) {
1.1075.2.36  raeburn  9422:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9423:                             (!$nothide{$uname.':'.$udom})) {
                   9424:                             next;
                   9425:                         }
                   9426:                     }
1.503     raeburn  9427:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9428:                         $status = 'previous';
                   9429:                     } elsif ($start > $now) {
                   9430:                         $status = 'future';
                   9431:                     } else {
                   9432:                         $status = 'active';
                   9433:                     }
1.277     albertel 9434:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9435:                         if ($status eq $type) {
1.420     albertel 9436:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9437:                                 push(@{$$users{$role}{$user}},$type);
                   9438:                             }
1.288     raeburn  9439:                             $match = 1;
                   9440:                         }
                   9441:                     }
1.419     raeburn  9442:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9443:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9444: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9445:                         }
1.420     albertel 9446:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9447:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9448:                         }
1.609     raeburn  9449:                         if (ref($statushash) eq 'HASH') {
                   9450:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9451:                         }
1.275     raeburn  9452:                     }
                   9453:                 }
                   9454:             }
                   9455:         }
1.290     albertel 9456:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9457:             if ((defined($cdom)) && (defined($cnum))) {
                   9458:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9459:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9460:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9461:                     next if ($owner eq '');
                   9462:                     my ($ownername,$ownerdom);
                   9463:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9464:                         $ownername = $1;
                   9465:                         $ownerdom = $2;
                   9466:                     } else {
                   9467:                         $ownername = $owner;
                   9468:                         $ownerdom = $cdom;
                   9469:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9470:                     }
                   9471:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9472:                     if (defined($userdata) && 
1.609     raeburn  9473: 			!exists($$userdata{$owner})) {
                   9474: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9475:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9476:                             push(@{$seclists{$owner}},'none');
                   9477:                         }
                   9478:                         if (ref($statushash) eq 'HASH') {
                   9479:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9480:                         }
1.290     albertel 9481: 		    }
1.279     raeburn  9482:                 }
                   9483:             }
                   9484:         }
1.419     raeburn  9485:         foreach my $user (keys(%seclists)) {
                   9486:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9487:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9488:         }
1.275     raeburn  9489:     }
                   9490:     return;
                   9491: }
                   9492: 
1.288     raeburn  9493: sub get_user_info {
                   9494:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9495:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9496: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9497:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9498:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9499:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9500:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9501:     return;
                   9502: }
1.275     raeburn  9503: 
1.472     raeburn  9504: ###############################################
                   9505: 
                   9506: =pod
                   9507: 
                   9508: =item * &get_user_quota()
                   9509: 
1.1075.2.41  raeburn  9510: Retrieves quota assigned for storage of user files.
                   9511: Default is to report quota for portfolio files.
1.472     raeburn  9512: 
                   9513: Incoming parameters:
                   9514: 1. user's username
                   9515: 2. user's domain
1.1075.2.41  raeburn  9516: 3. quota name - portfolio, author, or course
                   9517:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9518: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9519:    course
1.472     raeburn  9520: 
                   9521: Returns:
1.1075.2.58  raeburn  9522: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9523: 2. (Optional) Type of setting: custom or default
                   9524:    (individually assigned or default for user's 
                   9525:    institutional status).
                   9526: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9527:    or student - types as defined in localenroll::inst_usertypes 
                   9528:    for user's domain, which determines default quota for user.
                   9529: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9530: 
                   9531: If a value has been stored in the user's environment, 
1.536     raeburn  9532: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9533: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9534: 
                   9535: =cut
                   9536: 
                   9537: ###############################################
                   9538: 
                   9539: 
                   9540: sub get_user_quota {
1.1075.2.42  raeburn  9541:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9542:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9543:     if (!defined($udom)) {
                   9544:         $udom = $env{'user.domain'};
                   9545:     }
                   9546:     if (!defined($uname)) {
                   9547:         $uname = $env{'user.name'};
                   9548:     }
                   9549:     if (($udom eq '' || $uname eq '') ||
                   9550:         ($udom eq 'public') && ($uname eq 'public')) {
                   9551:         $quota = 0;
1.536     raeburn  9552:         $quotatype = 'default';
                   9553:         $defquota = 0; 
1.472     raeburn  9554:     } else {
1.536     raeburn  9555:         my $inststatus;
1.1075.2.41  raeburn  9556:         if ($quotaname eq 'course') {
                   9557:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9558:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9559:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9560:             } else {
                   9561:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9562:                 $quota = $cenv{'internal.uploadquota'};
                   9563:             }
1.536     raeburn  9564:         } else {
1.1075.2.41  raeburn  9565:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9566:                 if ($quotaname eq 'author') {
                   9567:                     $quota = $env{'environment.authorquota'};
                   9568:                 } else {
                   9569:                     $quota = $env{'environment.portfolioquota'};
                   9570:                 }
                   9571:                 $inststatus = $env{'environment.inststatus'};
                   9572:             } else {
                   9573:                 my %userenv = 
                   9574:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9575:                                          'authorquota','inststatus'],$udom,$uname);
                   9576:                 my ($tmp) = keys(%userenv);
                   9577:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9578:                     if ($quotaname eq 'author') {
                   9579:                         $quota = $userenv{'authorquota'};
                   9580:                     } else {
                   9581:                         $quota = $userenv{'portfolioquota'};
                   9582:                     }
                   9583:                     $inststatus = $userenv{'inststatus'};
                   9584:                 } else {
                   9585:                     undef(%userenv);
                   9586:                 }
                   9587:             }
                   9588:         }
                   9589:         if ($quota eq '' || wantarray) {
                   9590:             if ($quotaname eq 'course') {
                   9591:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9592:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9593:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9594:                     $defquota = $domdefs{$crstype.'quota'};
                   9595:                 }
                   9596:                 if ($defquota eq '') {
                   9597:                     $defquota = 500;
                   9598:                 }
1.1075.2.41  raeburn  9599:             } else {
                   9600:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9601:             }
                   9602:             if ($quota eq '') {
                   9603:                 $quota = $defquota;
                   9604:                 $quotatype = 'default';
                   9605:             } else {
                   9606:                 $quotatype = 'custom';
                   9607:             }
1.472     raeburn  9608:         }
                   9609:     }
1.536     raeburn  9610:     if (wantarray) {
                   9611:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9612:     } else {
                   9613:         return $quota;
                   9614:     }
1.472     raeburn  9615: }
                   9616: 
                   9617: ###############################################
                   9618: 
                   9619: =pod
                   9620: 
                   9621: =item * &default_quota()
                   9622: 
1.536     raeburn  9623: Retrieves default quota assigned for storage of user portfolio files,
                   9624: given an (optional) user's institutional status.
1.472     raeburn  9625: 
                   9626: Incoming parameters:
1.1075.2.42  raeburn  9627: 
1.472     raeburn  9628: 1. domain
1.536     raeburn  9629: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9630:    status types (e.g., faculty, staff, student etc.)
                   9631:    which apply to the user for whom the default is being retrieved.
                   9632:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9633:    default quota will be returned.
                   9634: 3.  quota name - portfolio, author, or course
                   9635:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9636: 
                   9637: Returns:
1.1075.2.42  raeburn  9638: 
1.1075.2.58  raeburn  9639: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9640: 2. (Optional) institutional type which determined the value of the
                   9641:    default quota.
1.472     raeburn  9642: 
                   9643: If a value has been stored in the domain's configuration db,
                   9644: it will return that, otherwise it returns 20 (for backwards 
                   9645: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9646: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9647: 
1.536     raeburn  9648: If the user's status includes multiple types (e.g., staff and student),
                   9649: the largest default quota which applies to the user determines the
                   9650: default quota returned.
                   9651: 
1.472     raeburn  9652: =cut
                   9653: 
                   9654: ###############################################
                   9655: 
                   9656: 
                   9657: sub default_quota {
1.1075.2.41  raeburn  9658:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9659:     my ($defquota,$settingstatus);
                   9660:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9661:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9662:     my $key = 'defaultquota';
                   9663:     if ($quotaname eq 'author') {
                   9664:         $key = 'authorquota';
                   9665:     }
1.622     raeburn  9666:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9667:         if ($inststatus ne '') {
1.765     raeburn  9668:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9669:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9670:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9671:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9672:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9673:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9674:                             $settingstatus = $item;
1.1075.2.41  raeburn  9675:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9676:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9677:                             $settingstatus = $item;
                   9678:                         }
                   9679:                     }
1.1075.2.41  raeburn  9680:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9681:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9682:                         if ($defquota eq '') {
                   9683:                             $defquota = $quotahash{'quotas'}{$item};
                   9684:                             $settingstatus = $item;
                   9685:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9686:                             $defquota = $quotahash{'quotas'}{$item};
                   9687:                             $settingstatus = $item;
                   9688:                         }
1.536     raeburn  9689:                     }
                   9690:                 }
                   9691:             }
                   9692:         }
                   9693:         if ($defquota eq '') {
1.1075.2.41  raeburn  9694:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9695:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9696:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9697:                 $defquota = $quotahash{'quotas'}{'default'};
                   9698:             }
1.536     raeburn  9699:             $settingstatus = 'default';
1.1075.2.42  raeburn  9700:             if ($defquota eq '') {
                   9701:                 if ($quotaname eq 'author') {
                   9702:                     $defquota = 500;
                   9703:                 }
                   9704:             }
1.536     raeburn  9705:         }
                   9706:     } else {
                   9707:         $settingstatus = 'default';
1.1075.2.41  raeburn  9708:         if ($quotaname eq 'author') {
                   9709:             $defquota = 500;
                   9710:         } else {
                   9711:             $defquota = 20;
                   9712:         }
1.536     raeburn  9713:     }
                   9714:     if (wantarray) {
                   9715:         return ($defquota,$settingstatus);
1.472     raeburn  9716:     } else {
1.536     raeburn  9717:         return $defquota;
1.472     raeburn  9718:     }
                   9719: }
                   9720: 
1.1075.2.41  raeburn  9721: ###############################################
                   9722: 
                   9723: =pod
                   9724: 
1.1075.2.42  raeburn  9725: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9726: 
                   9727: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9728: of existing file within authoring space will cause quota for the authoring
                   9729: space to be exceeded.
                   9730: 
                   9731: Same, if upload of a file directly to a course/community via Course Editor
                   9732: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9733: 
1.1075.2.61  raeburn  9734: Inputs: 7 
1.1075.2.42  raeburn  9735: 1. username or coursenum
1.1075.2.41  raeburn  9736: 2. domain
1.1075.2.42  raeburn  9737: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9738: 4. filename of file for which action is being requested
                   9739: 5. filesize (kB) of file
                   9740: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9741: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9742: 
                   9743: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9744:          otherwise return null.
                   9745: 
1.1075.2.42  raeburn  9746: =back
                   9747: 
1.1075.2.41  raeburn  9748: =cut
                   9749: 
1.1075.2.42  raeburn  9750: sub excess_filesize_warning {
1.1075.2.59  raeburn  9751:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9752:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9753:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9754:     if ($context eq 'author') {
                   9755:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9756:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9757:     } else {
                   9758:         foreach my $subdir ('docs','supplemental') {
                   9759:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9760:         }
                   9761:     }
1.1075.2.41  raeburn  9762:     $disk_quota = int($disk_quota * 1000);
                   9763:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9764:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9765:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9766:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9767:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9768:                             $disk_quota,$current_disk_usage).
                   9769:                '</p>';
                   9770:     }
                   9771:     return;
                   9772: }
                   9773: 
                   9774: ###############################################
                   9775: 
                   9776: 
1.384     raeburn  9777: sub get_secgrprole_info {
                   9778:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9779:     my %sections_count = &get_sections($cdom,$cnum);
                   9780:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9781:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9782:     my @groups = sort(keys(%curr_groups));
                   9783:     my $allroles = [];
                   9784:     my $rolehash;
                   9785:     my $accesshash = {
                   9786:                      active => 'Currently has access',
                   9787:                      future => 'Will have future access',
                   9788:                      previous => 'Previously had access',
                   9789:                   };
                   9790:     if ($needroles) {
                   9791:         $rolehash = {'all' => 'all'};
1.385     albertel 9792:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9793: 	if (&Apache::lonnet::error(%user_roles)) {
                   9794: 	    undef(%user_roles);
                   9795: 	}
                   9796:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9797:             my ($role)=split(/\:/,$item,2);
                   9798:             if ($role eq 'cr') { next; }
                   9799:             if ($role =~ /^cr/) {
                   9800:                 $$rolehash{$role} = (split('/',$role))[3];
                   9801:             } else {
                   9802:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9803:             }
                   9804:         }
                   9805:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9806:             push(@{$allroles},$key);
                   9807:         }
                   9808:         push (@{$allroles},'st');
                   9809:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9810:     }
                   9811:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9812: }
                   9813: 
1.555     raeburn  9814: sub user_picker {
1.1075.2.127  raeburn  9815:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9816:     my $currdom = $dom;
1.1075.2.114  raeburn  9817:     my @alldoms = &Apache::lonnet::all_domains();
                   9818:     if (@alldoms == 1) {
                   9819:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9820:                                                ['directorysrch'],$alldoms[0]);
                   9821:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9822:         my $showdom = $domdesc;
                   9823:         if ($showdom eq '') {
                   9824:             $showdom = $dom;
                   9825:         }
                   9826:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9827:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9828:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9829:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9830:             }
                   9831:         }
                   9832:     }
1.555     raeburn  9833:     my %curr_selected = (
                   9834:                         srchin => 'dom',
1.580     raeburn  9835:                         srchby => 'lastname',
1.555     raeburn  9836:                       );
                   9837:     my $srchterm;
1.625     raeburn  9838:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9839:         if ($srch->{'srchby'} ne '') {
                   9840:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9841:         }
                   9842:         if ($srch->{'srchin'} ne '') {
                   9843:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9844:         }
                   9845:         if ($srch->{'srchtype'} ne '') {
                   9846:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9847:         }
                   9848:         if ($srch->{'srchdomain'} ne '') {
                   9849:             $currdom = $srch->{'srchdomain'};
                   9850:         }
                   9851:         $srchterm = $srch->{'srchterm'};
                   9852:     }
1.1075.2.98  raeburn  9853:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9854:                     'usr'       => 'Search criteria',
1.563     raeburn  9855:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9856:                     'uname'     => 'username',
                   9857:                     'lastname'  => 'last name',
1.555     raeburn  9858:                     'lastfirst' => 'last name, first name',
1.558     albertel 9859:                     'crs'       => 'in this course',
1.576     raeburn  9860:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9861:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9862:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9863:                     'exact'     => 'is',
                   9864:                     'contains'  => 'contains',
1.569     raeburn  9865:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9866:                                        );
                   9867:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9868:                     'youm'      => "You must include some text to search for.",
                   9869:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9870:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9871:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9872:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9873:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9874:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9875:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9876:                                        );
1.1075.2.98  raeburn  9877:     &html_escape(\%html_lt);
                   9878:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9879:     my $domform;
1.1075.2.126  raeburn  9880:     my $allow_blank = 1;
1.1075.2.115  raeburn  9881:     if ($fixeddom) {
1.1075.2.126  raeburn  9882:         $allow_blank = 0;
                   9883:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9884:     } else {
1.1075.2.126  raeburn  9885:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9886:     }
1.563     raeburn  9887:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9888: 
                   9889:     my @srchins = ('crs','dom','alc','instd');
                   9890: 
                   9891:     foreach my $option (@srchins) {
                   9892:         # FIXME 'alc' option unavailable until 
                   9893:         #       loncreateuser::print_user_query_page()
                   9894:         #       has been completed.
                   9895:         next if ($option eq 'alc');
1.880     raeburn  9896:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9897:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9898:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9899:         if ($curr_selected{'srchin'} eq $option) {
                   9900:             $srchinsel .= ' 
1.1075.2.98  raeburn  9901:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9902:         } else {
                   9903:             $srchinsel .= '
1.1075.2.98  raeburn  9904:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9905:         }
1.555     raeburn  9906:     }
1.563     raeburn  9907:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9908: 
                   9909:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9910:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9911:         if ($curr_selected{'srchby'} eq $option) {
                   9912:             $srchbysel .= '
1.1075.2.98  raeburn  9913:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9914:         } else {
                   9915:             $srchbysel .= '
1.1075.2.98  raeburn  9916:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9917:          }
                   9918:     }
                   9919:     $srchbysel .= "\n  </select>\n";
                   9920: 
                   9921:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9922:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9923:         if ($curr_selected{'srchtype'} eq $option) {
                   9924:             $srchtypesel .= '
1.1075.2.98  raeburn  9925:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9926:         } else {
                   9927:             $srchtypesel .= '
1.1075.2.98  raeburn  9928:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9929:         }
                   9930:     }
                   9931:     $srchtypesel .= "\n  </select>\n";
                   9932: 
1.558     albertel 9933:     my ($newuserscript,$new_user_create);
1.994     raeburn  9934:     my $context_dom = $env{'request.role.domain'};
                   9935:     if ($context eq 'requestcrs') {
                   9936:         if ($env{'form.coursedom'} ne '') { 
                   9937:             $context_dom = $env{'form.coursedom'};
                   9938:         }
                   9939:     }
1.556     raeburn  9940:     if ($forcenewuser) {
1.576     raeburn  9941:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9942:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9943:                 if ($cancreate) {
                   9944:                     $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>';
                   9945:                 } else {
1.799     bisitz   9946:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9947:                     my %usertypetext = (
                   9948:                         official   => 'institutional',
                   9949:                         unofficial => 'non-institutional',
                   9950:                     );
1.799     bisitz   9951:                     $new_user_create = '<p class="LC_warning">'
                   9952:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9953:                                       .' '
                   9954:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9955:                                           ,'<a href="'.$helplink.'">','</a>')
                   9956:                                       .'</p><br />';
1.627     raeburn  9957:                 }
1.576     raeburn  9958:             }
                   9959:         }
                   9960: 
1.556     raeburn  9961:         $newuserscript = <<"ENDSCRIPT";
                   9962: 
1.570     raeburn  9963: function setSearch(createnew,callingForm) {
1.556     raeburn  9964:     if (createnew == 1) {
1.570     raeburn  9965:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9966:             if (callingForm.srchby.options[i].value == 'uname') {
                   9967:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9968:             }
                   9969:         }
1.570     raeburn  9970:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9971:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9972: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9973:             }
                   9974:         }
1.570     raeburn  9975:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9976:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9977:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9978:             }
                   9979:         }
1.570     raeburn  9980:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9981:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9982:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9983:             }
                   9984:         }
                   9985:     }
                   9986: }
                   9987: ENDSCRIPT
1.558     albertel 9988: 
1.556     raeburn  9989:     }
                   9990: 
1.555     raeburn  9991:     my $output = <<"END_BLOCK";
1.556     raeburn  9992: <script type="text/javascript">
1.824     bisitz   9993: // <![CDATA[
1.570     raeburn  9994: function validateEntry(callingForm) {
1.558     albertel 9995: 
1.556     raeburn  9996:     var checkok = 1;
1.558     albertel 9997:     var srchin;
1.570     raeburn  9998:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9999: 	if ( callingForm.srchin[i].checked ) {
                   10000: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10001: 	}
                   10002:     }
                   10003: 
1.570     raeburn  10004:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10005:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10006:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10007:     var srchterm =  callingForm.srchterm.value;
                   10008:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10009:     var msg = "";
                   10010: 
                   10011:     if (srchterm == "") {
                   10012:         checkok = 0;
1.1075.2.98  raeburn  10013:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10014:     }
                   10015: 
1.569     raeburn  10016:     if (srchtype== 'begins') {
                   10017:         if (srchterm.length < 2) {
                   10018:             checkok = 0;
1.1075.2.98  raeburn  10019:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10020:         }
                   10021:     }
                   10022: 
1.556     raeburn  10023:     if (srchtype== 'contains') {
                   10024:         if (srchterm.length < 3) {
                   10025:             checkok = 0;
1.1075.2.98  raeburn  10026:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10027:         }
                   10028:     }
                   10029:     if (srchin == 'instd') {
                   10030:         if (srchdomain == '') {
                   10031:             checkok = 0;
1.1075.2.98  raeburn  10032:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10033:         }
                   10034:     }
                   10035:     if (srchin == 'dom') {
                   10036:         if (srchdomain == '') {
                   10037:             checkok = 0;
1.1075.2.98  raeburn  10038:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10039:         }
                   10040:     }
                   10041:     if (srchby == 'lastfirst') {
                   10042:         if (srchterm.indexOf(",") == -1) {
                   10043:             checkok = 0;
1.1075.2.98  raeburn  10044:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10045:         }
                   10046:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10047:             checkok = 0;
1.1075.2.98  raeburn  10048:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10049:         }
                   10050:     }
                   10051:     if (checkok == 0) {
1.1075.2.98  raeburn  10052:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10053:         return;
                   10054:     }
                   10055:     if (checkok == 1) {
1.570     raeburn  10056:         callingForm.submit();
1.556     raeburn  10057:     }
                   10058: }
                   10059: 
                   10060: $newuserscript
                   10061: 
1.824     bisitz   10062: // ]]>
1.556     raeburn  10063: </script>
1.558     albertel 10064: 
                   10065: $new_user_create
                   10066: 
1.555     raeburn  10067: END_BLOCK
1.558     albertel 10068: 
1.876     raeburn  10069:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10070:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10071:                $domform.
                   10072:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10073:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10074:                $srchbysel.
                   10075:                $srchtypesel. 
                   10076:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10077:                $srchinsel.
                   10078:                &Apache::lonhtmlcommon::row_closure(1). 
                   10079:                &Apache::lonhtmlcommon::end_pick_box().
                   10080:                '<br />';
1.1075.2.114  raeburn  10081:     return ($output,1);
1.555     raeburn  10082: }
                   10083: 
1.612     raeburn  10084: sub user_rule_check {
1.615     raeburn  10085:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10086:     my ($response,%inst_response);
1.612     raeburn  10087:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10088:         if (keys(%{$usershash}) > 1) {
                   10089:             my (%by_username,%by_id,%userdoms);
                   10090:             my $checkid;
1.612     raeburn  10091:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10092:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10093:                     $checkid = 1;
                   10094:                 }
                   10095:             }
                   10096:             foreach my $user (keys(%{$usershash})) {
                   10097:                 my ($uname,$udom) = split(/:/,$user);
                   10098:                 if ($checkid) {
                   10099:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10100:                         if ($usershash->{$user}->{'id'} ne '') {
                   10101:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10102:                             $userdoms{$udom} = 1;
                   10103:                             if (ref($inst_results) eq 'HASH') {
                   10104:                                 $inst_results->{$uname.':'.$udom} = {};
                   10105:                             }
                   10106:                         }
                   10107:                     }
                   10108:                 } else {
                   10109:                     $by_username{$udom}{$uname} = 1;
                   10110:                     $userdoms{$udom} = 1;
                   10111:                     if (ref($inst_results) eq 'HASH') {
                   10112:                         $inst_results->{$uname.':'.$udom} = {};
                   10113:                     }
                   10114:                 }
                   10115:             }
                   10116:             foreach my $udom (keys(%userdoms)) {
                   10117:                 if (!$got_rules->{$udom}) {
                   10118:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10119:                                                              ['usercreation'],$udom);
                   10120:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10121:                         foreach my $item ('username','id') {
                   10122:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10123:                                 $$curr_rules{$udom}{$item} =
                   10124:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10125:                             }
                   10126:                         }
                   10127:                     }
                   10128:                     $got_rules->{$udom} = 1;
                   10129:                 }
                   10130:             }
                   10131:             if ($checkid) {
                   10132:                 foreach my $udom (keys(%by_id)) {
                   10133:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10134:                     if ($outcome eq 'ok') {
                   10135:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10136:                             my $uname = $by_id{$udom}{$id};
                   10137:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10138:                         }
                   10139:                         if (ref($results) eq 'HASH') {
                   10140:                             foreach my $uname (keys(%{$results})) {
                   10141:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10142:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10143:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10144:                                 }
                   10145:                             }
                   10146:                         }
                   10147:                     }
1.612     raeburn  10148:                 }
1.615     raeburn  10149:             } else {
1.1075.2.99  raeburn  10150:                 foreach my $udom (keys(%by_username)) {
                   10151:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10152:                     if ($outcome eq 'ok') {
                   10153:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10154:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10155:                         }
                   10156:                         if (ref($results) eq 'HASH') {
                   10157:                             foreach my $uname (keys(%{$results})) {
                   10158:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10159:                             }
                   10160:                         }
                   10161:                     }
                   10162:                 }
1.612     raeburn  10163:             }
1.1075.2.99  raeburn  10164:         } elsif (keys(%{$usershash}) == 1) {
                   10165:             my $user = (keys(%{$usershash}))[0];
                   10166:             my ($uname,$udom) = split(/:/,$user);
                   10167:             if (($udom ne '') && ($uname ne '')) {
                   10168:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10169:                     if (ref($checks) eq 'HASH') {
                   10170:                         if (defined($checks->{'username'})) {
                   10171:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10172:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10173:                         } elsif (defined($checks->{'id'})) {
                   10174:                             if ($usershash->{$user}->{'id'} ne '') {
                   10175:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10176:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10177:                                                                   $usershash->{$user}->{'id'});
                   10178:                             } else {
                   10179:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10180:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10181:                             }
                   10182:                         }
                   10183:                     } else {
                   10184:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10185:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10186:                        return;
                   10187:                     }
                   10188:                     if (!$got_rules->{$udom}) {
                   10189:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10190:                                                                  ['usercreation'],$udom);
                   10191:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10192:                             foreach my $item ('username','id') {
                   10193:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10194:                                    $$curr_rules{$udom}{$item} =
                   10195:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10196:                                 }
                   10197:                             }
1.585     raeburn  10198:                         }
1.1075.2.99  raeburn  10199:                         $got_rules->{$udom} = 1;
1.585     raeburn  10200:                     }
                   10201:                 }
1.1075.2.99  raeburn  10202:             } else {
                   10203:                 return;
                   10204:             }
                   10205:         } else {
                   10206:             return;
                   10207:         }
                   10208:         foreach my $user (keys(%{$usershash})) {
                   10209:             my ($uname,$udom) = split(/:/,$user);
                   10210:             next if (($udom eq '') || ($uname eq ''));
                   10211:             my $id;
                   10212:             if (ref($inst_results) eq 'HASH') {
                   10213:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10214:                     $id = $inst_results->{$user}->{'id'};
                   10215:                 }
                   10216:             }
                   10217:             if ($id eq '') {
                   10218:                 if (ref($usershash->{$user})) {
                   10219:                     $id = $usershash->{$user}->{'id'};
                   10220:                 }
1.585     raeburn  10221:             }
1.612     raeburn  10222:             foreach my $item (keys(%{$checks})) {
                   10223:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10224:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10225:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10226:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10227:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10228:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10229:                                 if ($rule_check{$rule}) {
                   10230:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10231:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10232:                                         if (ref($inst_results) eq 'HASH') {
                   10233:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10234:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10235:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10236:                                                 } elsif ($item eq 'id') {
                   10237:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10238:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10239:                                                     }
1.615     raeburn  10240:                                                 }
1.612     raeburn  10241:                                             }
                   10242:                                         }
1.615     raeburn  10243:                                     }
                   10244:                                     last;
1.585     raeburn  10245:                                 }
                   10246:                             }
                   10247:                         }
                   10248:                     }
                   10249:                 }
                   10250:             }
                   10251:         }
                   10252:     }
1.612     raeburn  10253:     return;
                   10254: }
                   10255: 
                   10256: sub user_rule_formats {
                   10257:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10258:     my %text = ( 
                   10259:                  'username' => 'Usernames',
                   10260:                  'id'       => 'IDs',
                   10261:                );
                   10262:     my $output;
                   10263:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10264:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10265:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10266:             $output = '<br />'.
                   10267:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10268:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10269:                       ' <ul>';
1.612     raeburn  10270:             foreach my $rule (@{$ruleorder}) {
                   10271:                 if (ref($curr_rules) eq 'ARRAY') {
                   10272:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10273:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10274:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10275:                                         $rules->{$rule}{'desc'}.'</li>';
                   10276:                         }
                   10277:                     }
                   10278:                 }
                   10279:             }
                   10280:             $output .= '</ul>';
                   10281:         }
                   10282:     }
                   10283:     return $output;
                   10284: }
                   10285: 
                   10286: sub instrule_disallow_msg {
1.615     raeburn  10287:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10288:     my $response;
                   10289:     my %text = (
                   10290:                   item   => 'username',
                   10291:                   items  => 'usernames',
                   10292:                   match  => 'matches',
                   10293:                   do     => 'does',
                   10294:                   action => 'a username',
                   10295:                   one    => 'one',
                   10296:                );
                   10297:     if ($count > 1) {
                   10298:         $text{'item'} = 'usernames';
                   10299:         $text{'match'} ='match';
                   10300:         $text{'do'} = 'do';
                   10301:         $text{'action'} = 'usernames',
                   10302:         $text{'one'} = 'ones';
                   10303:     }
                   10304:     if ($checkitem eq 'id') {
                   10305:         $text{'items'} = 'IDs';
                   10306:         $text{'item'} = 'ID';
                   10307:         $text{'action'} = 'an ID';
1.615     raeburn  10308:         if ($count > 1) {
                   10309:             $text{'item'} = 'IDs';
                   10310:             $text{'action'} = 'IDs';
                   10311:         }
1.612     raeburn  10312:     }
1.674     bisitz   10313:     $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  10314:     if ($mode eq 'upload') {
                   10315:         if ($checkitem eq 'username') {
                   10316:             $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'}.");
                   10317:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10318:             $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  10319:         }
1.669     raeburn  10320:     } elsif ($mode eq 'selfcreate') {
                   10321:         if ($checkitem eq 'id') {
                   10322:             $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.");
                   10323:         }
1.615     raeburn  10324:     } else {
                   10325:         if ($checkitem eq 'username') {
                   10326:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10327:         } elsif ($checkitem eq 'id') {
                   10328:             $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.");
                   10329:         }
1.612     raeburn  10330:     }
                   10331:     return $response;
1.585     raeburn  10332: }
                   10333: 
1.624     raeburn  10334: sub personal_data_fieldtitles {
                   10335:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10336:                         id => 'Student/Employee ID',
                   10337:                         permanentemail => 'E-mail address',
                   10338:                         lastname => 'Last Name',
                   10339:                         firstname => 'First Name',
                   10340:                         middlename => 'Middle Name',
                   10341:                         generation => 'Generation',
                   10342:                         gen => 'Generation',
1.765     raeburn  10343:                         inststatus => 'Affiliation',
1.624     raeburn  10344:                    );
                   10345:     return %fieldtitles;
                   10346: }
                   10347: 
1.642     raeburn  10348: sub sorted_inst_types {
                   10349:     my ($dom) = @_;
1.1075.2.70  raeburn  10350:     my ($usertypes,$order);
                   10351:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10352:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10353:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10354:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10355:     } else {
                   10356:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10357:     }
1.642     raeburn  10358:     my $othertitle = &mt('All users');
                   10359:     if ($env{'request.course.id'}) {
1.668     raeburn  10360:         $othertitle  = &mt('Any users');
1.642     raeburn  10361:     }
                   10362:     my @types;
                   10363:     if (ref($order) eq 'ARRAY') {
                   10364:         @types = @{$order};
                   10365:     }
                   10366:     if (@types == 0) {
                   10367:         if (ref($usertypes) eq 'HASH') {
                   10368:             @types = sort(keys(%{$usertypes}));
                   10369:         }
                   10370:     }
                   10371:     if (keys(%{$usertypes}) > 0) {
                   10372:         $othertitle = &mt('Other users');
                   10373:     }
                   10374:     return ($othertitle,$usertypes,\@types);
                   10375: }
                   10376: 
1.645     raeburn  10377: sub get_institutional_codes {
                   10378:     my ($settings,$allcourses,$LC_code) = @_;
                   10379: # Get complete list of course sections to update
                   10380:     my @currsections = ();
                   10381:     my @currxlists = ();
                   10382:     my $coursecode = $$settings{'internal.coursecode'};
                   10383: 
                   10384:     if ($$settings{'internal.sectionnums'} ne '') {
                   10385:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10386:     }
                   10387: 
                   10388:     if ($$settings{'internal.crosslistings'} ne '') {
                   10389:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10390:     }
                   10391: 
                   10392:     if (@currxlists > 0) {
                   10393:         foreach (@currxlists) {
                   10394:             if (m/^([^:]+):(\w*)$/) {
                   10395:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10396:                     push(@{$allcourses},$1);
1.645     raeburn  10397:                     $$LC_code{$1} = $2;
                   10398:                 }
                   10399:             }
                   10400:         }
                   10401:     }
                   10402:  
                   10403:     if (@currsections > 0) {
                   10404:         foreach (@currsections) {
                   10405:             if (m/^(\w+):(\w*)$/) {
                   10406:                 my $sec = $coursecode.$1;
                   10407:                 my $lc_sec = $2;
                   10408:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10409:                     push(@{$allcourses},$sec);
1.645     raeburn  10410:                     $$LC_code{$sec} = $lc_sec;
                   10411:                 }
                   10412:             }
                   10413:         }
                   10414:     }
                   10415:     return;
                   10416: }
                   10417: 
1.971     raeburn  10418: sub get_standard_codeitems {
                   10419:     return ('Year','Semester','Department','Number','Section');
                   10420: }
                   10421: 
1.112     bowersj2 10422: =pod
                   10423: 
1.780     raeburn  10424: =head1 Slot Helpers
                   10425: 
                   10426: =over 4
                   10427: 
                   10428: =item * sorted_slots()
                   10429: 
1.1040    raeburn  10430: Sorts an array of slot names in order of an optional sort key,
                   10431: default sort is by slot start time (earliest first). 
1.780     raeburn  10432: 
                   10433: Inputs:
                   10434: 
                   10435: =over 4
                   10436: 
                   10437: slotsarr  - Reference to array of unsorted slot names.
                   10438: 
                   10439: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10440: 
1.1040    raeburn  10441: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10442: 
1.549     albertel 10443: =back
                   10444: 
1.780     raeburn  10445: Returns:
                   10446: 
                   10447: =over 4
                   10448: 
1.1040    raeburn  10449: sorted   - An array of slot names sorted by a specified sort key 
                   10450:            (default sort key is start time of the slot).
1.780     raeburn  10451: 
                   10452: =back
                   10453: 
                   10454: =cut
                   10455: 
                   10456: 
                   10457: sub sorted_slots {
1.1040    raeburn  10458:     my ($slotsarr,$slots,$sortkey) = @_;
                   10459:     if ($sortkey eq '') {
                   10460:         $sortkey = 'starttime';
                   10461:     }
1.780     raeburn  10462:     my @sorted;
                   10463:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10464:         @sorted =
                   10465:             sort {
                   10466:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10467:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10468:                      }
                   10469:                      if (ref($slots->{$a})) { return -1;}
                   10470:                      if (ref($slots->{$b})) { return 1;}
                   10471:                      return 0;
                   10472:                  } @{$slotsarr};
                   10473:     }
                   10474:     return @sorted;
                   10475: }
                   10476: 
1.1040    raeburn  10477: =pod
                   10478: 
                   10479: =item * get_future_slots()
                   10480: 
                   10481: Inputs:
                   10482: 
                   10483: =over 4
                   10484: 
                   10485: cnum - course number
                   10486: 
                   10487: cdom - course domain
                   10488: 
                   10489: now - current UNIX time
                   10490: 
                   10491: symb - optional symb
                   10492: 
                   10493: =back
                   10494: 
                   10495: Returns:
                   10496: 
                   10497: =over 4
                   10498: 
                   10499: sorted_reservable - ref to array of student_schedulable slots currently 
                   10500:                     reservable, ordered by end date of reservation period.
                   10501: 
                   10502: reservable_now - ref to hash of student_schedulable slots currently
                   10503:                  reservable.
                   10504: 
                   10505:     Keys in inner hash are:
                   10506:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10507:     (b) endreserve: end date of reservation period.
                   10508:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10509:         selected.
1.1040    raeburn  10510: 
                   10511: sorted_future - ref to array of student_schedulable slots reservable in
                   10512:                 the future, ordered by start date of reservation period.
                   10513: 
                   10514: future_reservable - ref to hash of student_schedulable slots reservable
                   10515:                     in the future.
                   10516: 
                   10517:     Keys in inner hash are:
                   10518:     (a) symb: either blank or symb to which slot use is restricted.
                   10519:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10520:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10521:         selected.
1.1040    raeburn  10522: 
                   10523: =back
                   10524: 
                   10525: =cut
                   10526: 
                   10527: sub get_future_slots {
                   10528:     my ($cnum,$cdom,$now,$symb) = @_;
                   10529:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10530:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10531:     foreach my $slot (keys(%slots)) {
                   10532:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10533:         if ($symb) {
                   10534:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10535:                      ($slots{$slot}->{'symb'} ne $symb));
                   10536:         }
                   10537:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10538:             ($slots{$slot}->{'endtime'} > $now)) {
                   10539:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10540:                 my $userallowed = 0;
                   10541:                 if ($slots{$slot}->{'allowedsections'}) {
                   10542:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10543:                     if (!defined($env{'request.role.sec'})
                   10544:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10545:                         $userallowed=1;
                   10546:                     } else {
                   10547:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10548:                             $userallowed=1;
                   10549:                         }
                   10550:                     }
                   10551:                     unless ($userallowed) {
                   10552:                         if (defined($env{'request.course.groups'})) {
                   10553:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10554:                             foreach my $group (@groups) {
                   10555:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10556:                                     $userallowed=1;
                   10557:                                     last;
                   10558:                                 }
                   10559:                             }
                   10560:                         }
                   10561:                     }
                   10562:                 }
                   10563:                 if ($slots{$slot}->{'allowedusers'}) {
                   10564:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10565:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10566:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10567:                         $userallowed = 1;
                   10568:                     }
                   10569:                 }
                   10570:                 next unless($userallowed);
                   10571:             }
                   10572:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10573:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10574:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10575:             my $uniqueperiod;
                   10576:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10577:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10578:             }
1.1040    raeburn  10579:             if (($startreserve < $now) &&
                   10580:                 (!$endreserve || $endreserve > $now)) {
                   10581:                 my $lastres = $endreserve;
                   10582:                 if (!$lastres) {
                   10583:                     $lastres = $slots{$slot}->{'starttime'};
                   10584:                 }
                   10585:                 $reservable_now{$slot} = {
                   10586:                                            symb       => $symb,
1.1075.2.104  raeburn  10587:                                            endreserve => $lastres,
                   10588:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10589:                                          };
                   10590:             } elsif (($startreserve > $now) &&
                   10591:                      (!$endreserve || $endreserve > $startreserve)) {
                   10592:                 $future_reservable{$slot} = {
                   10593:                                               symb         => $symb,
1.1075.2.104  raeburn  10594:                                               startreserve => $startreserve,
                   10595:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10596:                                             };
                   10597:             }
                   10598:         }
                   10599:     }
                   10600:     my @unsorted_reservable = keys(%reservable_now);
                   10601:     if (@unsorted_reservable > 0) {
                   10602:         @sorted_reservable = 
                   10603:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10604:     }
                   10605:     my @unsorted_future = keys(%future_reservable);
                   10606:     if (@unsorted_future > 0) {
                   10607:         @sorted_future =
                   10608:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10609:     }
                   10610:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10611: }
1.780     raeburn  10612: 
                   10613: =pod
                   10614: 
1.1057    foxr     10615: =back
                   10616: 
1.549     albertel 10617: =head1 HTTP Helpers
                   10618: 
                   10619: =over 4
                   10620: 
1.648     raeburn  10621: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10622: 
1.258     albertel 10623: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10624: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10625: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10626: 
                   10627: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10628: $possible_names is an ref to an array of form element names.  As an example:
                   10629: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10630: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10631: 
                   10632: =cut
1.1       albertel 10633: 
1.6       albertel 10634: sub get_unprocessed_cgi {
1.25      albertel 10635:   my ($query,$possible_names)= @_;
1.26      matthew  10636:   # $Apache::lonxml::debug=1;
1.356     albertel 10637:   foreach my $pair (split(/&/,$query)) {
                   10638:     my ($name, $value) = split(/=/,$pair);
1.369     www      10639:     $name = &unescape($name);
1.25      albertel 10640:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10641:       $value =~ tr/+/ /;
                   10642:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10643:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10644:     }
1.16      harris41 10645:   }
1.6       albertel 10646: }
                   10647: 
1.112     bowersj2 10648: =pod
                   10649: 
1.648     raeburn  10650: =item * &cacheheader() 
1.112     bowersj2 10651: 
                   10652: returns cache-controlling header code
                   10653: 
                   10654: =cut
                   10655: 
1.7       albertel 10656: sub cacheheader {
1.258     albertel 10657:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10658:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10659:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10660:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10661:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10662:     return $output;
1.7       albertel 10663: }
                   10664: 
1.112     bowersj2 10665: =pod
                   10666: 
1.648     raeburn  10667: =item * &no_cache($r) 
1.112     bowersj2 10668: 
                   10669: specifies header code to not have cache
                   10670: 
                   10671: =cut
                   10672: 
1.9       albertel 10673: sub no_cache {
1.216     albertel 10674:     my ($r) = @_;
                   10675:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10676: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10677:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10678:     $r->no_cache(1);
                   10679:     $r->header_out("Expires" => $date);
                   10680:     $r->header_out("Pragma" => "no-cache");
1.123     www      10681: }
                   10682: 
                   10683: sub content_type {
1.181     albertel 10684:     my ($r,$type,$charset) = @_;
1.299     foxr     10685:     if ($r) {
                   10686: 	#  Note that printout.pl calls this with undef for $r.
                   10687: 	&no_cache($r);
                   10688:     }
1.258     albertel 10689:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10690:     unless ($charset) {
                   10691: 	$charset=&Apache::lonlocal::current_encoding;
                   10692:     }
                   10693:     if ($charset) { $type.='; charset='.$charset; }
                   10694:     if ($r) {
                   10695: 	$r->content_type($type);
                   10696:     } else {
                   10697: 	print("Content-type: $type\n\n");
                   10698:     }
1.9       albertel 10699: }
1.25      albertel 10700: 
1.112     bowersj2 10701: =pod
                   10702: 
1.648     raeburn  10703: =item * &add_to_env($name,$value) 
1.112     bowersj2 10704: 
1.258     albertel 10705: adds $name to the %env hash with value
1.112     bowersj2 10706: $value, if $name already exists, the entry is converted to an array
                   10707: reference and $value is added to the array.
                   10708: 
                   10709: =cut
                   10710: 
1.25      albertel 10711: sub add_to_env {
                   10712:   my ($name,$value)=@_;
1.258     albertel 10713:   if (defined($env{$name})) {
                   10714:     if (ref($env{$name})) {
1.25      albertel 10715:       #already have multiple values
1.258     albertel 10716:       push(@{ $env{$name} },$value);
1.25      albertel 10717:     } else {
                   10718:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10719:       my $first=$env{$name};
                   10720:       undef($env{$name});
                   10721:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10722:     }
                   10723:   } else {
1.258     albertel 10724:     $env{$name}=$value;
1.25      albertel 10725:   }
1.31      albertel 10726: }
1.149     albertel 10727: 
                   10728: =pod
                   10729: 
1.648     raeburn  10730: =item * &get_env_multiple($name) 
1.149     albertel 10731: 
1.258     albertel 10732: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10733: values may be defined and end up as an array ref.
                   10734: 
                   10735: returns an array of values
                   10736: 
                   10737: =cut
                   10738: 
                   10739: sub get_env_multiple {
                   10740:     my ($name) = @_;
                   10741:     my @values;
1.258     albertel 10742:     if (defined($env{$name})) {
1.149     albertel 10743:         # exists is it an array
1.258     albertel 10744:         if (ref($env{$name})) {
                   10745:             @values=@{ $env{$name} };
1.149     albertel 10746:         } else {
1.258     albertel 10747:             $values[0]=$env{$name};
1.149     albertel 10748:         }
                   10749:     }
                   10750:     return(@values);
                   10751: }
                   10752: 
1.660     raeburn  10753: sub ask_for_embedded_content {
                   10754:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10755:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10756:         %currsubfile,%unused,$rem);
1.1071    raeburn  10757:     my $counter = 0;
                   10758:     my $numnew = 0;
1.987     raeburn  10759:     my $numremref = 0;
                   10760:     my $numinvalid = 0;
                   10761:     my $numpathchg = 0;
                   10762:     my $numexisting = 0;
1.1071    raeburn  10763:     my $numunused = 0;
                   10764:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10765:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10766:     my $heading = &mt('Upload embedded files');
                   10767:     my $buttontext = &mt('Upload');
                   10768: 
1.1075.2.11  raeburn  10769:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10770:         if ($actionurl eq '/adm/dependencies') {
                   10771:             $navmap = Apache::lonnavmaps::navmap->new();
                   10772:         }
                   10773:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10774:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10775:     }
1.1075.2.35  raeburn  10776:     if (($actionurl eq '/adm/portfolio') ||
                   10777:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10778:         my $current_path='/';
                   10779:         if ($env{'form.currentpath'}) {
                   10780:             $current_path = $env{'form.currentpath'};
                   10781:         }
                   10782:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10783:             $udom = $cdom;
                   10784:             $uname = $cnum;
1.984     raeburn  10785:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10786:         } else {
                   10787:             $udom = $env{'user.domain'};
                   10788:             $uname = $env{'user.name'};
                   10789:             $url = '/userfiles/portfolio';
                   10790:         }
1.987     raeburn  10791:         $toplevel = $url.'/';
1.984     raeburn  10792:         $url .= $current_path;
                   10793:         $getpropath = 1;
1.987     raeburn  10794:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10795:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10796:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10797:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10798:         $toplevel = $url;
1.984     raeburn  10799:         if ($rest ne '') {
1.987     raeburn  10800:             $url .= $rest;
                   10801:         }
                   10802:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10803:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10804:             $url = $args->{'docs_url'};
                   10805:             $toplevel = $url;
1.1075.2.11  raeburn  10806:             if ($args->{'context'} eq 'paste') {
                   10807:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10808:                 ($path) =
                   10809:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10810:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10811:                 $fileloc =~ s{^/}{};
                   10812:             }
1.1071    raeburn  10813:         }
                   10814:     } elsif ($actionurl eq '/adm/dependencies') {
                   10815:         if ($env{'request.course.id'} ne '') {
                   10816:             if (ref($args) eq 'HASH') {
                   10817:                 $url = $args->{'docs_url'};
                   10818:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10819:                 $toplevel = $url;
                   10820:                 unless ($toplevel =~ m{^/}) {
                   10821:                     $toplevel = "/$url";
                   10822:                 }
1.1075.2.11  raeburn  10823:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10824:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10825:                     $path = $1;
                   10826:                 } else {
                   10827:                     ($path) =
                   10828:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10829:                 }
1.1075.2.79  raeburn  10830:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10831:                     $fileloc = $toplevel;
                   10832:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10833:                     my ($udom,$uname,$fname) =
                   10834:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10835:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10836:                 } else {
                   10837:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10838:                 }
1.1071    raeburn  10839:                 $fileloc =~ s{^/}{};
                   10840:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10841:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10842:             }
1.987     raeburn  10843:         }
1.1075.2.35  raeburn  10844:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10845:         $udom = $cdom;
                   10846:         $uname = $cnum;
                   10847:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10848:         $toplevel = $url;
                   10849:         $path = $url;
                   10850:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10851:         $fileloc =~ s{^/}{};
                   10852:     }
                   10853:     foreach my $file (keys(%{$allfiles})) {
                   10854:         my $embed_file;
                   10855:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10856:             $embed_file = $1;
                   10857:         } else {
                   10858:             $embed_file = $file;
                   10859:         }
1.1075.2.55  raeburn  10860:         my ($absolutepath,$cleaned_file);
                   10861:         if ($embed_file =~ m{^\w+://}) {
                   10862:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10863:             $newfiles{$cleaned_file} = 1;
                   10864:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10865:         } else {
1.1075.2.55  raeburn  10866:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10867:             if ($embed_file =~ m{^/}) {
                   10868:                 $absolutepath = $embed_file;
                   10869:             }
1.1075.2.47  raeburn  10870:             if ($cleaned_file =~ m{/}) {
                   10871:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10872:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10873:                 my $item = $fname;
                   10874:                 if ($path ne '') {
                   10875:                     $item = $path.'/'.$fname;
                   10876:                     $subdependencies{$path}{$fname} = 1;
                   10877:                 } else {
                   10878:                     $dependencies{$item} = 1;
                   10879:                 }
                   10880:                 if ($absolutepath) {
                   10881:                     $mapping{$item} = $absolutepath;
                   10882:                 } else {
                   10883:                     $mapping{$item} = $embed_file;
                   10884:                 }
                   10885:             } else {
                   10886:                 $dependencies{$embed_file} = 1;
                   10887:                 if ($absolutepath) {
1.1075.2.47  raeburn  10888:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10889:                 } else {
1.1075.2.47  raeburn  10890:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10891:                 }
                   10892:             }
1.984     raeburn  10893:         }
                   10894:     }
1.1071    raeburn  10895:     my $dirptr = 16384;
1.984     raeburn  10896:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10897:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10898:         if (($actionurl eq '/adm/portfolio') ||
                   10899:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10900:             my ($sublistref,$listerror) =
                   10901:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10902:             if (ref($sublistref) eq 'ARRAY') {
                   10903:                 foreach my $line (@{$sublistref}) {
                   10904:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10905:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10906:                 }
1.984     raeburn  10907:             }
1.987     raeburn  10908:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10909:             if (opendir(my $dir,$url.'/'.$path)) {
                   10910:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10911:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10912:             }
1.1075.2.11  raeburn  10913:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10914:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10915:                   ($args->{'context'} eq 'paste')) ||
                   10916:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10917:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10918:                 my $dir;
                   10919:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10920:                     $dir = $fileloc;
                   10921:                 } else {
                   10922:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10923:                 }
1.1071    raeburn  10924:                 if ($dir ne '') {
                   10925:                     my ($sublistref,$listerror) =
                   10926:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10927:                     if (ref($sublistref) eq 'ARRAY') {
                   10928:                         foreach my $line (@{$sublistref}) {
                   10929:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10930:                                 undef,$mtime)=split(/\&/,$line,12);
                   10931:                             unless (($testdir&$dirptr) ||
                   10932:                                     ($file_name =~ /^\.\.?$/)) {
                   10933:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10934:                             }
                   10935:                         }
                   10936:                     }
                   10937:                 }
1.984     raeburn  10938:             }
                   10939:         }
                   10940:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10941:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10942:                 my $item = $path.'/'.$file;
                   10943:                 unless ($mapping{$item} eq $item) {
                   10944:                     $pathchanges{$item} = 1;
                   10945:                 }
                   10946:                 $existing{$item} = 1;
                   10947:                 $numexisting ++;
                   10948:             } else {
                   10949:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10950:             }
                   10951:         }
1.1071    raeburn  10952:         if ($actionurl eq '/adm/dependencies') {
                   10953:             foreach my $path (keys(%currsubfile)) {
                   10954:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10955:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10956:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10957:                              next if (($rem ne '') &&
                   10958:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10959:                                        (ref($navmap) &&
                   10960:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10961:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10962:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10963:                              $unused{$path.'/'.$file} = 1; 
                   10964:                          }
                   10965:                     }
                   10966:                 }
                   10967:             }
                   10968:         }
1.984     raeburn  10969:     }
1.987     raeburn  10970:     my %currfile;
1.1075.2.35  raeburn  10971:     if (($actionurl eq '/adm/portfolio') ||
                   10972:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10973:         my ($dirlistref,$listerror) =
                   10974:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10975:         if (ref($dirlistref) eq 'ARRAY') {
                   10976:             foreach my $line (@{$dirlistref}) {
                   10977:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10978:                 $currfile{$file_name} = 1;
                   10979:             }
1.984     raeburn  10980:         }
1.987     raeburn  10981:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10982:         if (opendir(my $dir,$url)) {
1.987     raeburn  10983:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10984:             map {$currfile{$_} = 1;} @dir_list;
                   10985:         }
1.1075.2.11  raeburn  10986:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10987:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10988:               ($args->{'context'} eq 'paste')) ||
                   10989:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10990:         if ($env{'request.course.id'} ne '') {
                   10991:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10992:             if ($dir ne '') {
                   10993:                 my ($dirlistref,$listerror) =
                   10994:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10995:                 if (ref($dirlistref) eq 'ARRAY') {
                   10996:                     foreach my $line (@{$dirlistref}) {
                   10997:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10998:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10999:                         unless (($testdir&$dirptr) ||
                   11000:                                 ($file_name =~ /^\.\.?$/)) {
                   11001:                             $currfile{$file_name} = [$size,$mtime];
                   11002:                         }
                   11003:                     }
                   11004:                 }
                   11005:             }
                   11006:         }
1.984     raeburn  11007:     }
                   11008:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11009:         if (exists($currfile{$file})) {
1.987     raeburn  11010:             unless ($mapping{$file} eq $file) {
                   11011:                 $pathchanges{$file} = 1;
                   11012:             }
                   11013:             $existing{$file} = 1;
                   11014:             $numexisting ++;
                   11015:         } else {
1.984     raeburn  11016:             $newfiles{$file} = 1;
                   11017:         }
                   11018:     }
1.1071    raeburn  11019:     foreach my $file (keys(%currfile)) {
                   11020:         unless (($file eq $filename) ||
                   11021:                 ($file eq $filename.'.bak') ||
                   11022:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11023:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11024:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11025:                     next if (($rem ne '') &&
                   11026:                              (($env{"httpref.$rem".$file} ne '') ||
                   11027:                               (ref($navmap) &&
                   11028:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11029:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11030:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11031:                 }
1.1075.2.11  raeburn  11032:             }
1.1071    raeburn  11033:             $unused{$file} = 1;
                   11034:         }
                   11035:     }
1.1075.2.11  raeburn  11036:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11037:         ($args->{'context'} eq 'paste')) {
                   11038:         $counter = scalar(keys(%existing));
                   11039:         $numpathchg = scalar(keys(%pathchanges));
                   11040:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11041:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11042:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11043:         $counter = scalar(keys(%existing));
                   11044:         $numpathchg = scalar(keys(%pathchanges));
                   11045:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11046:     }
1.984     raeburn  11047:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11048:         if ($actionurl eq '/adm/dependencies') {
                   11049:             next if ($embed_file =~ m{^\w+://});
                   11050:         }
1.660     raeburn  11051:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11052:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11053:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11054:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11055:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11056:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11057:         }
1.1075.2.35  raeburn  11058:         $upload_output .= '</td>';
1.1071    raeburn  11059:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11060:             $upload_output.='<td align="right">'.
                   11061:                             '<span class="LC_info LC_fontsize_medium">'.
                   11062:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11063:             $numremref++;
1.660     raeburn  11064:         } elsif ($args->{'error_on_invalid_names'}
                   11065:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11066:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11067:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11068:             $numinvalid++;
1.660     raeburn  11069:         } else {
1.1075.2.35  raeburn  11070:             $upload_output .= '<td>'.
                   11071:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11072:                                                      $embed_file,\%mapping,
1.1071    raeburn  11073:                                                      $allfiles,$codebase,'upload');
                   11074:             $counter ++;
                   11075:             $numnew ++;
1.987     raeburn  11076:         }
                   11077:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11078:     }
                   11079:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11080:         if ($actionurl eq '/adm/dependencies') {
                   11081:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11082:             $modify_output .= &start_data_table_row().
                   11083:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11084:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11085:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11086:                               '<td>'.$size.'</td>'.
                   11087:                               '<td>'.$mtime.'</td>'.
                   11088:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11089:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11090:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11091:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11092:                               &embedded_file_element('upload_embedded',$counter,
                   11093:                                                      $embed_file,\%mapping,
                   11094:                                                      $allfiles,$codebase,'modify').
                   11095:                               '</div></td>'.
                   11096:                               &end_data_table_row()."\n";
                   11097:             $counter ++;
                   11098:         } else {
                   11099:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11100:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11101:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11102:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11103:                               &Apache::loncommon::end_data_table_row()."\n";
                   11104:         }
                   11105:     }
                   11106:     my $delidx = $counter;
                   11107:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11108:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11109:         $delete_output .= &start_data_table_row().
                   11110:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11111:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11112:                           '<td>'.$size.'</td>'.
                   11113:                           '<td>'.$mtime.'</td>'.
                   11114:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11115:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11116:                           &embedded_file_element('upload_embedded',$delidx,
                   11117:                                                  $oldfile,\%mapping,$allfiles,
                   11118:                                                  $codebase,'delete').'</td>'.
                   11119:                           &end_data_table_row()."\n"; 
                   11120:         $numunused ++;
                   11121:         $delidx ++;
1.987     raeburn  11122:     }
                   11123:     if ($upload_output) {
                   11124:         $upload_output = &start_data_table().
                   11125:                          $upload_output.
                   11126:                          &end_data_table()."\n";
                   11127:     }
1.1071    raeburn  11128:     if ($modify_output) {
                   11129:         $modify_output = &start_data_table().
                   11130:                          &start_data_table_header_row().
                   11131:                          '<th>'.&mt('File').'</th>'.
                   11132:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11133:                          '<th>'.&mt('Modified').'</th>'.
                   11134:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11135:                          &end_data_table_header_row().
                   11136:                          $modify_output.
                   11137:                          &end_data_table()."\n";
                   11138:     }
                   11139:     if ($delete_output) {
                   11140:         $delete_output = &start_data_table().
                   11141:                          &start_data_table_header_row().
                   11142:                          '<th>'.&mt('File').'</th>'.
                   11143:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11144:                          '<th>'.&mt('Modified').'</th>'.
                   11145:                          '<th>'.&mt('Delete?').'</th>'.
                   11146:                          &end_data_table_header_row().
                   11147:                          $delete_output.
                   11148:                          &end_data_table()."\n";
                   11149:     }
1.987     raeburn  11150:     my $applies = 0;
                   11151:     if ($numremref) {
                   11152:         $applies ++;
                   11153:     }
                   11154:     if ($numinvalid) {
                   11155:         $applies ++;
                   11156:     }
                   11157:     if ($numexisting) {
                   11158:         $applies ++;
                   11159:     }
1.1071    raeburn  11160:     if ($counter || $numunused) {
1.987     raeburn  11161:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11162:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11163:                   $state.'<h3>'.$heading.'</h3>'; 
                   11164:         if ($actionurl eq '/adm/dependencies') {
                   11165:             if ($numnew) {
                   11166:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11167:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11168:                            $upload_output.'<br />'."\n";
                   11169:             }
                   11170:             if ($numexisting) {
                   11171:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11172:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11173:                            $modify_output.'<br />'."\n";
                   11174:                            $buttontext = &mt('Save changes');
                   11175:             }
                   11176:             if ($numunused) {
                   11177:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11178:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11179:                            $delete_output.'<br />'."\n";
                   11180:                            $buttontext = &mt('Save changes');
                   11181:             }
                   11182:         } else {
                   11183:             $output .= $upload_output.'<br />'."\n";
                   11184:         }
                   11185:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11186:                    $counter.'" />'."\n";
                   11187:         if ($actionurl eq '/adm/dependencies') { 
                   11188:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11189:                        $numnew.'" />'."\n";
                   11190:         } elsif ($actionurl eq '') {
1.987     raeburn  11191:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11192:         }
                   11193:     } elsif ($applies) {
                   11194:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11195:         if ($applies > 1) {
                   11196:             $output .=  
1.1075.2.35  raeburn  11197:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11198:             if ($numremref) {
                   11199:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11200:             }
                   11201:             if ($numinvalid) {
                   11202:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11203:             }
                   11204:             if ($numexisting) {
                   11205:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11206:             }
                   11207:             $output .= '</ul><br />';
                   11208:         } elsif ($numremref) {
                   11209:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11210:         } elsif ($numinvalid) {
                   11211:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11212:         } elsif ($numexisting) {
                   11213:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11214:         }
                   11215:         $output .= $upload_output.'<br />';
                   11216:     }
                   11217:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11218:     $chgcount = $counter;
1.987     raeburn  11219:     if (keys(%pathchanges) > 0) {
                   11220:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11221:             if ($counter) {
1.987     raeburn  11222:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11223:                                                   $embed_file,\%mapping,
1.1071    raeburn  11224:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11225:             } else {
                   11226:                 $pathchange_output .= 
                   11227:                     &start_data_table_row().
                   11228:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11229:                     $chgcount.'" checked="checked" /></td>'.
                   11230:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11231:                     '<td>'.$embed_file.
                   11232:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11233:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11234:                     '</td>'.&end_data_table_row();
1.660     raeburn  11235:             }
1.987     raeburn  11236:             $numpathchg ++;
                   11237:             $chgcount ++;
1.660     raeburn  11238:         }
                   11239:     }
1.1075.2.35  raeburn  11240:     if (($counter) || ($numunused)) {
1.987     raeburn  11241:         if ($numpathchg) {
                   11242:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11243:                        $numpathchg.'" />'."\n";
                   11244:         }
                   11245:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11246:             ($actionurl eq '/adm/imsimport')) {
                   11247:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11248:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11249:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11250:         } elsif ($actionurl eq '/adm/dependencies') {
                   11251:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11252:         }
1.1075.2.35  raeburn  11253:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11254:     } elsif ($numpathchg) {
                   11255:         my %pathchange = ();
                   11256:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11257:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11258:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11259:         }
1.987     raeburn  11260:     }
1.1071    raeburn  11261:     return ($output,$counter,$numpathchg);
1.987     raeburn  11262: }
                   11263: 
1.1075.2.47  raeburn  11264: =pod
                   11265: 
                   11266: =item * clean_path($name)
                   11267: 
                   11268: Performs clean-up of directories, subdirectories and filename in an
                   11269: embedded object, referenced in an HTML file which is being uploaded
                   11270: to a course or portfolio, where
                   11271: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11272: checked.
                   11273: 
                   11274: Clean-up is similar to replacements in lonnet::clean_filename()
                   11275: except each / between sub-directory and next level is preserved.
                   11276: 
                   11277: =cut
                   11278: 
                   11279: sub clean_path {
                   11280:     my ($embed_file) = @_;
                   11281:     $embed_file =~s{^/+}{};
                   11282:     my @contents;
                   11283:     if ($embed_file =~ m{/}) {
                   11284:         @contents = split(/\//,$embed_file);
                   11285:     } else {
                   11286:         @contents = ($embed_file);
                   11287:     }
                   11288:     my $lastidx = scalar(@contents)-1;
                   11289:     for (my $i=0; $i<=$lastidx; $i++) {
                   11290:         $contents[$i]=~s{\\}{/}g;
                   11291:         $contents[$i]=~s/\s+/\_/g;
                   11292:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11293:         if ($i == $lastidx) {
                   11294:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11295:         }
                   11296:     }
                   11297:     if ($lastidx > 0) {
                   11298:         return join('/',@contents);
                   11299:     } else {
                   11300:         return $contents[0];
                   11301:     }
                   11302: }
                   11303: 
1.987     raeburn  11304: sub embedded_file_element {
1.1071    raeburn  11305:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11306:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11307:                    (ref($codebase) eq 'HASH'));
                   11308:     my $output;
1.1071    raeburn  11309:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11310:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11311:     }
                   11312:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11313:                &escape($embed_file).'" />';
                   11314:     unless (($context eq 'upload_embedded') && 
                   11315:             ($mapping->{$embed_file} eq $embed_file)) {
                   11316:         $output .='
                   11317:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11318:     }
                   11319:     my $attrib;
                   11320:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11321:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11322:     }
                   11323:     $output .=
                   11324:         "\n\t\t".
                   11325:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11326:         $attrib.'" />';
                   11327:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11328:         $output .=
                   11329:             "\n\t\t".
                   11330:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11331:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11332:     }
1.987     raeburn  11333:     return $output;
1.660     raeburn  11334: }
                   11335: 
1.1071    raeburn  11336: sub get_dependency_details {
                   11337:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11338:     my ($size,$mtime,$showsize,$showmtime);
                   11339:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11340:         if ($embed_file =~ m{/}) {
                   11341:             my ($path,$fname) = split(/\//,$embed_file);
                   11342:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11343:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11344:             }
                   11345:         } else {
                   11346:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11347:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11348:             }
                   11349:         }
                   11350:         $showsize = $size/1024.0;
                   11351:         $showsize = sprintf("%.1f",$showsize);
                   11352:         if ($mtime > 0) {
                   11353:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11354:         }
                   11355:     }
                   11356:     return ($showsize,$showmtime);
                   11357: }
                   11358: 
                   11359: sub ask_embedded_js {
                   11360:     return <<"END";
                   11361: <script type="text/javascript"">
                   11362: // <![CDATA[
                   11363: function toggleBrowse(counter) {
                   11364:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11365:     var fileid = document.getElementById('embedded_item_'+counter);
                   11366:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11367:     if (chkboxid.checked == true) {
                   11368:         uploaddivid.style.display='block';
                   11369:     } else {
                   11370:         uploaddivid.style.display='none';
                   11371:         fileid.value = '';
                   11372:     }
                   11373: }
                   11374: // ]]>
                   11375: </script>
                   11376: 
                   11377: END
                   11378: }
                   11379: 
1.661     raeburn  11380: sub upload_embedded {
                   11381:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11382:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11383:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11384:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11385:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11386:         my $orig_uploaded_filename =
                   11387:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11388:         foreach my $type ('orig','ref','attrib','codebase') {
                   11389:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11390:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11391:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11392:             }
                   11393:         }
1.661     raeburn  11394:         my ($path,$fname) =
                   11395:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11396:         # no path, whole string is fname
                   11397:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11398:         $fname = &Apache::lonnet::clean_filename($fname);
                   11399:         # See if there is anything left
                   11400:         next if ($fname eq '');
                   11401: 
                   11402:         # Check if file already exists as a file or directory.
                   11403:         my ($state,$msg);
                   11404:         if ($context eq 'portfolio') {
                   11405:             my $port_path = $dirpath;
                   11406:             if ($group ne '') {
                   11407:                 $port_path = "groups/$group/$port_path";
                   11408:             }
1.987     raeburn  11409:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11410:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11411:                                               $dir_root,$port_path,$disk_quota,
                   11412:                                               $current_disk_usage,$uname,$udom);
                   11413:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11414:                 || $state eq 'file_locked') {
1.661     raeburn  11415:                 $output .= $msg;
                   11416:                 next;
                   11417:             }
                   11418:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11419:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11420:             if ($state eq 'exists') {
                   11421:                 $output .= $msg;
                   11422:                 next;
                   11423:             }
                   11424:         }
                   11425:         # Check if extension is valid
                   11426:         if (($fname =~ /\.(\w+)$/) &&
                   11427:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11428:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11429:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11430:             next;
                   11431:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11432:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11433:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11434:             next;
                   11435:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11436:             $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  11437:             next;
                   11438:         }
                   11439:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11440:         my $subdir = $path;
                   11441:         $subdir =~ s{/+$}{};
1.661     raeburn  11442:         if ($context eq 'portfolio') {
1.984     raeburn  11443:             my $result;
                   11444:             if ($state eq 'existingfile') {
                   11445:                 $result=
                   11446:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11447:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11448:             } else {
1.984     raeburn  11449:                 $result=
                   11450:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11451:                                                     $dirpath.
1.1075.2.35  raeburn  11452:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11453:                 if ($result !~ m|^/uploaded/|) {
                   11454:                     $output .= '<span class="LC_error">'
                   11455:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11456:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11457:                                .'</span><br />';
                   11458:                     next;
                   11459:                 } else {
1.987     raeburn  11460:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11461:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11462:                 }
1.661     raeburn  11463:             }
1.1075.2.35  raeburn  11464:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11465:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11466:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11467:             my $result =
1.1075.2.35  raeburn  11468:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11469:             if ($result !~ m|^/uploaded/|) {
                   11470:                 $output .= '<span class="LC_error">'
                   11471:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11472:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11473:                            .'</span><br />';
                   11474:                     next;
                   11475:             } else {
                   11476:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11477:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11478:                 if ($context eq 'syllabus') {
                   11479:                     &Apache::lonnet::make_public_indefinitely($result);
                   11480:                 }
1.987     raeburn  11481:             }
1.661     raeburn  11482:         } else {
                   11483: # Save the file
                   11484:             my $target = $env{'form.embedded_item_'.$i};
                   11485:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11486:             my $dest = $fullpath.$fname;
                   11487:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11488:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11489:             my $count;
                   11490:             my $filepath = $dir_root;
1.1027    raeburn  11491:             foreach my $subdir (@parts) {
                   11492:                 $filepath .= "/$subdir";
                   11493:                 if (!-e $filepath) {
1.661     raeburn  11494:                     mkdir($filepath,0770);
                   11495:                 }
                   11496:             }
                   11497:             my $fh;
                   11498:             if (!open($fh,'>'.$dest)) {
                   11499:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11500:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11501:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11502:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11503:                            '</span><br />';
                   11504:             } else {
                   11505:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11506:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11507:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11508:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11509:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11510:                               '</span><br />';
                   11511:                 } else {
1.987     raeburn  11512:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11513:                                $url.'</span>').'<br />';
                   11514:                     unless ($context eq 'testbank') {
                   11515:                         $footer .= &mt('View embedded file: [_1]',
                   11516:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11517:                     }
                   11518:                 }
                   11519:                 close($fh);
                   11520:             }
                   11521:         }
                   11522:         if ($env{'form.embedded_ref_'.$i}) {
                   11523:             $pathchange{$i} = 1;
                   11524:         }
                   11525:     }
                   11526:     if ($output) {
                   11527:         $output = '<p>'.$output.'</p>';
                   11528:     }
                   11529:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11530:     $returnflag = 'ok';
1.1071    raeburn  11531:     my $numpathchgs = scalar(keys(%pathchange));
                   11532:     if ($numpathchgs > 0) {
1.987     raeburn  11533:         if ($context eq 'portfolio') {
                   11534:             $output .= '<p>'.&mt('or').'</p>';
                   11535:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11536:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11537:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11538:             $returnflag = 'modify_orightml';
                   11539:         }
                   11540:     }
1.1071    raeburn  11541:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11542: }
                   11543: 
                   11544: sub modify_html_form {
                   11545:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11546:     my $end = 0;
                   11547:     my $modifyform;
                   11548:     if ($context eq 'upload_embedded') {
                   11549:         return unless (ref($pathchange) eq 'HASH');
                   11550:         if ($env{'form.number_embedded_items'}) {
                   11551:             $end += $env{'form.number_embedded_items'};
                   11552:         }
                   11553:         if ($env{'form.number_pathchange_items'}) {
                   11554:             $end += $env{'form.number_pathchange_items'};
                   11555:         }
                   11556:         if ($end) {
                   11557:             for (my $i=0; $i<$end; $i++) {
                   11558:                 if ($i < $env{'form.number_embedded_items'}) {
                   11559:                     next unless($pathchange->{$i});
                   11560:                 }
                   11561:                 $modifyform .=
                   11562:                     &start_data_table_row().
                   11563:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11564:                     'checked="checked" /></td>'.
                   11565:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11566:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11567:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11568:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11569:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11570:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11571:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11572:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11573:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11574:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11575:                     &end_data_table_row();
1.1071    raeburn  11576:             }
1.987     raeburn  11577:         }
                   11578:     } else {
                   11579:         $modifyform = $pathchgtable;
                   11580:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11581:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11582:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11583:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11584:         }
                   11585:     }
                   11586:     if ($modifyform) {
1.1071    raeburn  11587:         if ($actionurl eq '/adm/dependencies') {
                   11588:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11589:         }
1.987     raeburn  11590:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11591:                '<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".
                   11592:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11593:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11594:                '</ol></p>'."\n".'<p>'.
                   11595:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11596:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11597:                &start_data_table()."\n".
                   11598:                &start_data_table_header_row().
                   11599:                '<th>'.&mt('Change?').'</th>'.
                   11600:                '<th>'.&mt('Current reference').'</th>'.
                   11601:                '<th>'.&mt('Required reference').'</th>'.
                   11602:                &end_data_table_header_row()."\n".
                   11603:                $modifyform.
                   11604:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11605:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11606:                '</form>'."\n";
                   11607:     }
                   11608:     return;
                   11609: }
                   11610: 
                   11611: sub modify_html_refs {
1.1075.2.35  raeburn  11612:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11613:     my $container;
                   11614:     if ($context eq 'portfolio') {
                   11615:         $container = $env{'form.container'};
                   11616:     } elsif ($context eq 'coursedoc') {
                   11617:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11618:     } elsif ($context eq 'manage_dependencies') {
                   11619:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11620:         $container = "/$container";
1.1075.2.35  raeburn  11621:     } elsif ($context eq 'syllabus') {
                   11622:         $container = $url;
1.987     raeburn  11623:     } else {
1.1027    raeburn  11624:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11625:     }
                   11626:     my (%allfiles,%codebase,$output,$content);
                   11627:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11628:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11629:         if (wantarray) {
                   11630:             return ('',0,0); 
                   11631:         } else {
                   11632:             return;
                   11633:         }
                   11634:     }
                   11635:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11636:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11637:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11638:             if (wantarray) {
                   11639:                 return ('',0,0);
                   11640:             } else {
                   11641:                 return;
                   11642:             }
                   11643:         } 
1.987     raeburn  11644:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11645:         if ($content eq '-1') {
                   11646:             if (wantarray) {
                   11647:                 return ('',0,0);
                   11648:             } else {
                   11649:                 return;
                   11650:             }
                   11651:         }
1.987     raeburn  11652:     } else {
1.1071    raeburn  11653:         unless ($container =~ /^\Q$dir_root\E/) {
                   11654:             if (wantarray) {
                   11655:                 return ('',0,0);
                   11656:             } else {
                   11657:                 return;
                   11658:             }
                   11659:         } 
1.1075.2.128  raeburn  11660:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11661:             $content = join('', <$fh>);
                   11662:             close($fh);
                   11663:         } else {
1.1071    raeburn  11664:             if (wantarray) {
                   11665:                 return ('',0,0);
                   11666:             } else {
                   11667:                 return;
                   11668:             }
1.987     raeburn  11669:         }
                   11670:     }
                   11671:     my ($count,$codebasecount) = (0,0);
                   11672:     my $mm = new File::MMagic;
                   11673:     my $mime_type = $mm->checktype_contents($content);
                   11674:     if ($mime_type eq 'text/html') {
                   11675:         my $parse_result = 
                   11676:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11677:                                                     \%codebase,\$content);
                   11678:         if ($parse_result eq 'ok') {
                   11679:             foreach my $i (@changes) {
                   11680:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11681:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11682:                 if ($allfiles{$ref}) {
                   11683:                     my $newname =  $orig;
                   11684:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11685:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11686:                     if ($attrib_regexp =~ /:/) {
                   11687:                         $attrib_regexp =~ s/\:/|/g;
                   11688:                     }
                   11689:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11690:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11691:                         $count += $numchg;
1.1075.2.35  raeburn  11692:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11693:                         delete($allfiles{$ref});
1.987     raeburn  11694:                     }
                   11695:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11696:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11697:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11698:                         $codebasecount ++;
                   11699:                     }
                   11700:                 }
                   11701:             }
1.1075.2.35  raeburn  11702:             my $skiprewrites;
1.987     raeburn  11703:             if ($count || $codebasecount) {
                   11704:                 my $saveresult;
1.1071    raeburn  11705:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11706:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11707:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11708:                     if ($url eq $container) {
                   11709:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11710:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11711:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11712:                                             $fname.'</span>').'</p>';
1.987     raeburn  11713:                     } else {
                   11714:                          $output = '<p class="LC_error">'.
                   11715:                                    &mt('Error: update failed for: [_1].',
                   11716:                                    '<span class="LC_filename">'.
                   11717:                                    $container.'</span>').'</p>';
                   11718:                     }
1.1075.2.35  raeburn  11719:                     if ($context eq 'syllabus') {
                   11720:                         unless ($saveresult eq 'ok') {
                   11721:                             $skiprewrites = 1;
                   11722:                         }
                   11723:                     }
1.987     raeburn  11724:                 } else {
1.1075.2.128  raeburn  11725:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11726:                         print $fh $content;
                   11727:                         close($fh);
                   11728:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11729:                                   $count,'<span class="LC_filename">'.
                   11730:                                   $container.'</span>').'</p>';
1.661     raeburn  11731:                     } else {
1.987     raeburn  11732:                          $output = '<p class="LC_error">'.
                   11733:                                    &mt('Error: could not update [_1].',
                   11734:                                    '<span class="LC_filename">'.
                   11735:                                    $container.'</span>').'</p>';
1.661     raeburn  11736:                     }
                   11737:                 }
                   11738:             }
1.1075.2.35  raeburn  11739:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11740:                 my ($actionurl,$state);
                   11741:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11742:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11743:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11744:                                               \%codebase,
                   11745:                                               {'context' => 'rewrites',
                   11746:                                                'ignore_remote_references' => 1,});
                   11747:                 if (ref($mapping) eq 'HASH') {
                   11748:                     my $rewrites = 0;
                   11749:                     foreach my $key (keys(%{$mapping})) {
                   11750:                         next if ($key =~ m{^https?://});
                   11751:                         my $ref = $mapping->{$key};
                   11752:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11753:                         my $attrib;
                   11754:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11755:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11756:                         }
                   11757:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11758:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11759:                             $rewrites += $numchg;
                   11760:                         }
                   11761:                     }
                   11762:                     if ($rewrites) {
                   11763:                         my $saveresult;
                   11764:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11765:                         if ($url eq $container) {
                   11766:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11767:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11768:                                             $count,'<span class="LC_filename">'.
                   11769:                                             $fname.'</span>').'</p>';
                   11770:                         } else {
                   11771:                             $output .= '<p class="LC_error">'.
                   11772:                                        &mt('Error: could not update links in [_1].',
                   11773:                                        '<span class="LC_filename">'.
                   11774:                                        $container.'</span>').'</p>';
                   11775: 
                   11776:                         }
                   11777:                     }
                   11778:                 }
                   11779:             }
1.987     raeburn  11780:         } else {
                   11781:             &logthis('Failed to parse '.$container.
                   11782:                      ' to modify references: '.$parse_result);
1.661     raeburn  11783:         }
                   11784:     }
1.1071    raeburn  11785:     if (wantarray) {
                   11786:         return ($output,$count,$codebasecount);
                   11787:     } else {
                   11788:         return $output;
                   11789:     }
1.661     raeburn  11790: }
                   11791: 
                   11792: sub check_for_existing {
                   11793:     my ($path,$fname,$element) = @_;
                   11794:     my ($state,$msg);
                   11795:     if (-d $path.'/'.$fname) {
                   11796:         $state = 'exists';
                   11797:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11798:     } elsif (-e $path.'/'.$fname) {
                   11799:         $state = 'exists';
                   11800:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11801:     }
                   11802:     if ($state eq 'exists') {
                   11803:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11804:     }
                   11805:     return ($state,$msg);
                   11806: }
                   11807: 
                   11808: sub check_for_upload {
                   11809:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11810:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11811:     my $filesize = length($env{'form.'.$element});
                   11812:     if (!$filesize) {
                   11813:         my $msg = '<span class="LC_error">'.
                   11814:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11815:                       '<span class="LC_filename">'.$fname.'</span>',
                   11816:                       $filesize).'<br />'.
1.1007    raeburn  11817:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11818:                   '</span>';
                   11819:         return ('zero_bytes',$msg);
                   11820:     }
                   11821:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11822:     my $getpropath = 1;
1.1021    raeburn  11823:     my ($dirlistref,$listerror) =
                   11824:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11825:     my $found_file = 0;
                   11826:     my $locked_file = 0;
1.991     raeburn  11827:     my @lockers;
                   11828:     my $navmap;
                   11829:     if ($env{'request.course.id'}) {
                   11830:         $navmap = Apache::lonnavmaps::navmap->new();
                   11831:     }
1.1021    raeburn  11832:     if (ref($dirlistref) eq 'ARRAY') {
                   11833:         foreach my $line (@{$dirlistref}) {
                   11834:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11835:             if ($file_name eq $fname){
                   11836:                 $file_name = $path.$file_name;
                   11837:                 if ($group ne '') {
                   11838:                     $file_name = $group.$file_name;
                   11839:                 }
                   11840:                 $found_file = 1;
                   11841:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11842:                     foreach my $lock (@lockers) {
                   11843:                         if (ref($lock) eq 'ARRAY') {
                   11844:                             my ($symb,$crsid) = @{$lock};
                   11845:                             if ($crsid eq $env{'request.course.id'}) {
                   11846:                                 if (ref($navmap)) {
                   11847:                                     my $res = $navmap->getBySymb($symb);
                   11848:                                     foreach my $part (@{$res->parts()}) { 
                   11849:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11850:                                         unless (($slot_status == $res->RESERVED) ||
                   11851:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11852:                                             $locked_file = 1;
                   11853:                                         }
1.991     raeburn  11854:                                     }
1.1021    raeburn  11855:                                 } else {
                   11856:                                     $locked_file = 1;
1.991     raeburn  11857:                                 }
                   11858:                             } else {
                   11859:                                 $locked_file = 1;
                   11860:                             }
                   11861:                         }
1.1021    raeburn  11862:                    }
                   11863:                 } else {
                   11864:                     my @info = split(/\&/,$rest);
                   11865:                     my $currsize = $info[6]/1000;
                   11866:                     if ($currsize < $filesize) {
                   11867:                         my $extra = $filesize - $currsize;
                   11868:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11869:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11870:                                       &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  11871:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11872:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11873:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11874:                             return ('will_exceed_quota',$msg);
                   11875:                         }
1.984     raeburn  11876:                     }
                   11877:                 }
1.661     raeburn  11878:             }
                   11879:         }
                   11880:     }
                   11881:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11882:         my $msg = '<p class="LC_warning">'.
                   11883:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11884:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11885:         return ('will_exceed_quota',$msg);
                   11886:     } elsif ($found_file) {
                   11887:         if ($locked_file) {
1.1075.2.69  raeburn  11888:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11889:             $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  11890:             $msg .= '</p>';
1.661     raeburn  11891:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11892:             return ('file_locked',$msg);
                   11893:         } else {
1.1075.2.69  raeburn  11894:             my $msg = '<p class="LC_error">';
1.984     raeburn  11895:             $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  11896:             $msg .= '</p>';
1.984     raeburn  11897:             return ('existingfile',$msg);
1.661     raeburn  11898:         }
                   11899:     }
                   11900: }
                   11901: 
1.987     raeburn  11902: sub check_for_traversal {
                   11903:     my ($path,$url,$toplevel) = @_;
                   11904:     my @parts=split(/\//,$path);
                   11905:     my $cleanpath;
                   11906:     my $fullpath = $url;
                   11907:     for (my $i=0;$i<@parts;$i++) {
                   11908:         next if ($parts[$i] eq '.');
                   11909:         if ($parts[$i] eq '..') {
                   11910:             $fullpath =~ s{([^/]+/)$}{};
                   11911:         } else {
                   11912:             $fullpath .= $parts[$i].'/';
                   11913:         }
                   11914:     }
                   11915:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11916:         $cleanpath = $1;
                   11917:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11918:         my $curr_toprel = $1;
                   11919:         my @parts = split(/\//,$curr_toprel);
                   11920:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11921:         my @urlparts = split(/\//,$url_toprel);
                   11922:         my $doubledots;
                   11923:         my $startdiff = -1;
                   11924:         for (my $i=0; $i<@urlparts; $i++) {
                   11925:             if ($startdiff == -1) {
                   11926:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11927:                     $startdiff = $i;
                   11928:                     $doubledots .= '../';
                   11929:                 }
                   11930:             } else {
                   11931:                 $doubledots .= '../';
                   11932:             }
                   11933:         }
                   11934:         if ($startdiff > -1) {
                   11935:             $cleanpath = $doubledots;
                   11936:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11937:                 $cleanpath .= $parts[$i].'/';
                   11938:             }
                   11939:         }
                   11940:     }
                   11941:     $cleanpath =~ s{(/)$}{};
                   11942:     return $cleanpath;
                   11943: }
1.31      albertel 11944: 
1.1053    raeburn  11945: sub is_archive_file {
                   11946:     my ($mimetype) = @_;
                   11947:     if (($mimetype eq 'application/octet-stream') ||
                   11948:         ($mimetype eq 'application/x-stuffit') ||
                   11949:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11950:         return 1;
                   11951:     }
                   11952:     return;
                   11953: }
                   11954: 
                   11955: sub decompress_form {
1.1065    raeburn  11956:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11957:     my %lt = &Apache::lonlocal::texthash (
                   11958:         this => 'This file is an archive file.',
1.1067    raeburn  11959:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11960:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11961:         youm => 'You may wish to extract its contents.',
                   11962:         extr => 'Extract contents',
1.1067    raeburn  11963:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11964:         proa => 'Process automatically?',
1.1053    raeburn  11965:         yes  => 'Yes',
                   11966:         no   => 'No',
1.1067    raeburn  11967:         fold => 'Title for folder containing movie',
                   11968:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11969:     );
1.1065    raeburn  11970:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11971:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11972:     my $info = &list_archive_contents($fileloc,\@paths);
                   11973:     if (@paths) {
                   11974:         foreach my $path (@paths) {
                   11975:             $path =~ s{^/}{};
1.1067    raeburn  11976:             if ($path =~ m{^([^/]+)/$}) {
                   11977:                 $topdir = $1;
                   11978:             }
1.1065    raeburn  11979:             if ($path =~ m{^([^/]+)/}) {
                   11980:                 $toplevel{$1} = $path;
                   11981:             } else {
                   11982:                 $toplevel{$path} = $path;
                   11983:             }
                   11984:         }
                   11985:     }
1.1067    raeburn  11986:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11987:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11988:                         "$topdir/media/",
                   11989:                         "$topdir/media/$topdir.mp4",
                   11990:                         "$topdir/media/FirstFrame.png",
                   11991:                         "$topdir/media/player.swf",
                   11992:                         "$topdir/media/swfobject.js",
                   11993:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11994:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11995:                          "$topdir/$topdir.mp4",
                   11996:                          "$topdir/$topdir\_config.xml",
                   11997:                          "$topdir/$topdir\_controller.swf",
                   11998:                          "$topdir/$topdir\_embed.css",
                   11999:                          "$topdir/$topdir\_First_Frame.png",
                   12000:                          "$topdir/$topdir\_player.html",
                   12001:                          "$topdir/$topdir\_Thumbnails.png",
                   12002:                          "$topdir/playerProductInstall.swf",
                   12003:                          "$topdir/scripts/",
                   12004:                          "$topdir/scripts/config_xml.js",
                   12005:                          "$topdir/scripts/handlebars.js",
                   12006:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12007:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12008:                          "$topdir/scripts/modernizr.js",
                   12009:                          "$topdir/scripts/player-min.js",
                   12010:                          "$topdir/scripts/swfobject.js",
                   12011:                          "$topdir/skins/",
                   12012:                          "$topdir/skins/configuration_express.xml",
                   12013:                          "$topdir/skins/express_show/",
                   12014:                          "$topdir/skins/express_show/player-min.css",
                   12015:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12016:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12017:                          "$topdir/$topdir.mp4",
                   12018:                          "$topdir/$topdir\_config.xml",
                   12019:                          "$topdir/$topdir\_controller.swf",
                   12020:                          "$topdir/$topdir\_embed.css",
                   12021:                          "$topdir/$topdir\_First_Frame.png",
                   12022:                          "$topdir/$topdir\_player.html",
                   12023:                          "$topdir/$topdir\_Thumbnails.png",
                   12024:                          "$topdir/playerProductInstall.swf",
                   12025:                          "$topdir/scripts/",
                   12026:                          "$topdir/scripts/config_xml.js",
                   12027:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12028:                          "$topdir/skins/",
                   12029:                          "$topdir/skins/configuration_express.xml",
                   12030:                          "$topdir/skins/express_show/",
                   12031:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12032:                          "$topdir/skins/express_show/spritesheet.png",
                   12033:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12034:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12035:         if (@diffs == 0) {
1.1075.2.59  raeburn  12036:             $is_camtasia = 6;
                   12037:         } else {
1.1075.2.81  raeburn  12038:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12039:             if (@diffs == 0) {
                   12040:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12041:             } else {
                   12042:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12043:                 if (@diffs == 0) {
                   12044:                     $is_camtasia = 8;
                   12045:                 }
1.1075.2.59  raeburn  12046:             }
1.1067    raeburn  12047:         }
                   12048:     }
                   12049:     my $output;
                   12050:     if ($is_camtasia) {
                   12051:         $output = <<"ENDCAM";
                   12052: <script type="text/javascript" language="Javascript">
                   12053: // <![CDATA[
                   12054: 
                   12055: function camtasiaToggle() {
                   12056:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12057:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12058:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12059:                 document.getElementById('camtasia_titles').style.display='block';
                   12060:             } else {
                   12061:                 document.getElementById('camtasia_titles').style.display='none';
                   12062:             }
                   12063:         }
                   12064:     }
                   12065:     return;
                   12066: }
                   12067: 
                   12068: // ]]>
                   12069: </script>
                   12070: <p>$lt{'camt'}</p>
                   12071: ENDCAM
1.1065    raeburn  12072:     } else {
1.1067    raeburn  12073:         $output = '<p>'.$lt{'this'};
                   12074:         if ($info eq '') {
                   12075:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12076:         } else {
                   12077:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12078:                        '<div><pre>'.$info.'</pre></div>';
                   12079:         }
1.1065    raeburn  12080:     }
1.1067    raeburn  12081:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12082:     my $duplicates;
                   12083:     my $num = 0;
                   12084:     if (ref($dirlist) eq 'ARRAY') {
                   12085:         foreach my $item (@{$dirlist}) {
                   12086:             if (ref($item) eq 'ARRAY') {
                   12087:                 if (exists($toplevel{$item->[0]})) {
                   12088:                     $duplicates .= 
                   12089:                         &start_data_table_row().
                   12090:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12091:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12092:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12093:                         'value="1" />'.&mt('Yes').'</label>'.
                   12094:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12095:                         '<td>'.$item->[0].'</td>';
                   12096:                     if ($item->[2]) {
                   12097:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12098:                     } else {
                   12099:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12100:                     }
                   12101:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12102:                                    '<td>'.
                   12103:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12104:                                    '</td>'.
                   12105:                                    &end_data_table_row();
                   12106:                     $num ++;
                   12107:                 }
                   12108:             }
                   12109:         }
                   12110:     }
                   12111:     my $itemcount;
                   12112:     if (@paths > 0) {
                   12113:         $itemcount = scalar(@paths);
                   12114:     } else {
                   12115:         $itemcount = 1;
                   12116:     }
1.1067    raeburn  12117:     if ($is_camtasia) {
                   12118:         $output .= $lt{'auto'}.'<br />'.
                   12119:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12120:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12121:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12122:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12123:                    $lt{'no'}.'</label></span><br />'.
                   12124:                    '<div id="camtasia_titles" style="display:block">'.
                   12125:                    &Apache::lonhtmlcommon::start_pick_box().
                   12126:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12127:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12128:                    &Apache::lonhtmlcommon::row_closure().
                   12129:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12130:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12131:                    &Apache::lonhtmlcommon::row_closure(1).
                   12132:                    &Apache::lonhtmlcommon::end_pick_box().
                   12133:                    '</div>';
                   12134:     }
1.1065    raeburn  12135:     $output .= 
                   12136:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12137:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12138:         "\n";
1.1065    raeburn  12139:     if ($duplicates ne '') {
                   12140:         $output .= '<p><span class="LC_warning">'.
                   12141:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12142:                    &start_data_table().
                   12143:                    &start_data_table_header_row().
                   12144:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12145:                    '<th>'.&mt('Name').'</th>'.
                   12146:                    '<th>'.&mt('Type').'</th>'.
                   12147:                    '<th>'.&mt('Size').'</th>'.
                   12148:                    '<th>'.&mt('Last modified').'</th>'.
                   12149:                    &end_data_table_header_row().
                   12150:                    $duplicates.
                   12151:                    &end_data_table().
                   12152:                    '</p>';
                   12153:     }
1.1067    raeburn  12154:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12155:     if (ref($hiddenelements) eq 'HASH') {
                   12156:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12157:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12158:         }
                   12159:     }
                   12160:     $output .= <<"END";
1.1067    raeburn  12161: <br />
1.1053    raeburn  12162: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12163: </form>
                   12164: $noextract
                   12165: END
                   12166:     return $output;
                   12167: }
                   12168: 
1.1065    raeburn  12169: sub decompression_utility {
                   12170:     my ($program) = @_;
                   12171:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12172:     my $location;
                   12173:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12174:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12175:                          '/usr/sbin/') {
                   12176:             if (-x $dir.$program) {
                   12177:                 $location = $dir.$program;
                   12178:                 last;
                   12179:             }
                   12180:         }
                   12181:     }
                   12182:     return $location;
                   12183: }
                   12184: 
                   12185: sub list_archive_contents {
                   12186:     my ($file,$pathsref) = @_;
                   12187:     my (@cmd,$output);
                   12188:     my $needsregexp;
                   12189:     if ($file =~ /\.zip$/) {
                   12190:         @cmd = (&decompression_utility('unzip'),"-l");
                   12191:         $needsregexp = 1;
                   12192:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12193:              ($file =~ /\.tgz$/)) {
                   12194:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12195:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12196:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12197:     } elsif ($file =~ m|\.tar$|) {
                   12198:         @cmd = (&decompression_utility('tar'),"-tf");
                   12199:     }
                   12200:     if (@cmd) {
                   12201:         undef($!);
                   12202:         undef($@);
                   12203:         if (open(my $fh,"-|", @cmd, $file)) {
                   12204:             while (my $line = <$fh>) {
                   12205:                 $output .= $line;
                   12206:                 chomp($line);
                   12207:                 my $item;
                   12208:                 if ($needsregexp) {
                   12209:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12210:                 } else {
                   12211:                     $item = $line;
                   12212:                 }
                   12213:                 if ($item ne '') {
                   12214:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12215:                         push(@{$pathsref},$item);
                   12216:                     } 
                   12217:                 }
                   12218:             }
                   12219:             close($fh);
                   12220:         }
                   12221:     }
                   12222:     return $output;
                   12223: }
                   12224: 
1.1053    raeburn  12225: sub decompress_uploaded_file {
                   12226:     my ($file,$dir) = @_;
                   12227:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12228:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12229:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12230:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12231:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12232:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12233:     my $decompressed = $env{'cgi.decompressed'};
                   12234:     &Apache::lonnet::delenv('cgi.file');
                   12235:     &Apache::lonnet::delenv('cgi.dir');
                   12236:     &Apache::lonnet::delenv('cgi.decompressed');
                   12237:     return ($decompressed,$result);
                   12238: }
                   12239: 
1.1055    raeburn  12240: sub process_decompression {
                   12241:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12242:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12243:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12244:                &mt('Unexpected file path.').'</p>'."\n";
                   12245:     }
                   12246:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12247:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12248:                &mt('Unexpected course context.').'</p>'."\n";
                   12249:     }
                   12250:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12251:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12252:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12253:     }
1.1055    raeburn  12254:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12255:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12256:         $error = &mt('Filename not a supported archive file type.').
                   12257:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12258:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12259:     } else {
                   12260:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12261:         if ($docuhome eq 'no_host') {
                   12262:             $error = &mt('Could not determine home server for course.');
                   12263:         } else {
                   12264:             my @ids=&Apache::lonnet::current_machine_ids();
                   12265:             my $currdir = "$dir_root/$destination";
                   12266:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12267:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12268:                        "$dir_root/$destination";
                   12269:             } else {
                   12270:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12271:                        "$dir_root/$docudom/$docuname/$destination";
                   12272:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12273:                     $error = &mt('Archive file not found.');
                   12274:                 }
                   12275:             }
1.1065    raeburn  12276:             my (@to_overwrite,@to_skip);
                   12277:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12278:                 my $total = $env{'form.archive_overwrite_total'};
                   12279:                 for (my $i=0; $i<$total; $i++) {
                   12280:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12281:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12282:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12283:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12284:                     }
                   12285:                 }
                   12286:             }
                   12287:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12288:             my $numoverwrite = scalar(@to_overwrite);
                   12289:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12290:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12291:             } elsif ($dir eq '') {
1.1055    raeburn  12292:                 $error = &mt('Directory containing archive file unavailable.');
                   12293:             } elsif (!$error) {
1.1065    raeburn  12294:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12295:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12296:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12297:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12298:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12299:                         ($decompressed,$display) =
                   12300:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12301:                         foreach my $item (@to_skip) {
                   12302:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12303:                                 if (-f "$dir/$tempdir/$item") {
                   12304:                                     unlink("$dir/$tempdir/$item");
                   12305:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12306:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12307:                                 }
                   12308:                             }
                   12309:                         }
                   12310:                         foreach my $item (@to_overwrite) {
                   12311:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12312:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12313:                                     if (-f "$dir/$item") {
                   12314:                                         unlink("$dir/$item");
                   12315:                                     } elsif (-d "$dir/$item") {
                   12316:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12317:                                     }
                   12318:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12319:                                 }
1.1065    raeburn  12320:                             }
                   12321:                         }
1.1075.2.128  raeburn  12322:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12323:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12324:                         }
1.1065    raeburn  12325:                     }
                   12326:                 } else {
                   12327:                     ($decompressed,$display) = 
                   12328:                         &decompress_uploaded_file($file,$dir);
                   12329:                 }
1.1055    raeburn  12330:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12331:                     $output = '<p class="LC_info">'.
                   12332:                               &mt('Files extracted successfully from archive.').
                   12333:                               '</p>'."\n";
1.1055    raeburn  12334:                     my ($warning,$result,@contents);
                   12335:                     my ($newdirlistref,$newlisterror) =
                   12336:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12337:                                                  $docuname,1);
                   12338:                     my (%is_dir,%changes,@newitems);
                   12339:                     my $dirptr = 16384;
1.1065    raeburn  12340:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12341:                         foreach my $dir_line (@{$newdirlistref}) {
                   12342:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12343:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12344:                                 push(@newitems,$item);
                   12345:                                 if ($dirptr&$testdir) {
                   12346:                                     $is_dir{$item} = 1;
                   12347:                                 }
                   12348:                                 $changes{$item} = 1;
                   12349:                             }
                   12350:                         }
                   12351:                     }
                   12352:                     if (keys(%changes) > 0) {
                   12353:                         foreach my $item (sort(@newitems)) {
                   12354:                             if ($changes{$item}) {
                   12355:                                 push(@contents,$item);
                   12356:                             }
                   12357:                         }
                   12358:                     }
                   12359:                     if (@contents > 0) {
1.1067    raeburn  12360:                         my $wantform;
                   12361:                         unless ($env{'form.autoextract_camtasia'}) {
                   12362:                             $wantform = 1;
                   12363:                         }
1.1056    raeburn  12364:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12365:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12366:                                                                 $currdir,\%is_dir,
                   12367:                                                                 \%children,\%parent,
1.1056    raeburn  12368:                                                                 \@contents,\%dirorder,
                   12369:                                                                 \%titles,$wantform);
1.1055    raeburn  12370:                         if ($datatable ne '') {
                   12371:                             $output .= &archive_options_form('decompressed',$datatable,
                   12372:                                                              $count,$hiddenelem);
1.1065    raeburn  12373:                             my $startcount = 6;
1.1055    raeburn  12374:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12375:                                                            \%titles,\%children);
1.1055    raeburn  12376:                         }
1.1067    raeburn  12377:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12378:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12379:                             my %displayed;
                   12380:                             my $total = 1;
                   12381:                             $env{'form.archive_directory'} = [];
                   12382:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12383:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12384:                                 $path =~ s{/$}{};
                   12385:                                 my $item;
                   12386:                                 if ($path ne '') {
                   12387:                                     $item = "$path/$titles{$i}";
                   12388:                                 } else {
                   12389:                                     $item = $titles{$i};
                   12390:                                 }
                   12391:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12392:                                 if ($item eq $contents[0]) {
                   12393:                                     push(@{$env{'form.archive_directory'}},$i);
                   12394:                                     $env{'form.archive_'.$i} = 'display';
                   12395:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12396:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12397:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12398:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12399:                                     $env{'form.archive_'.$i} = 'display';
                   12400:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12401:                                     $displayed{'web'} = $i;
                   12402:                                 } else {
1.1075.2.59  raeburn  12403:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12404:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12405:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12406:                                         push(@{$env{'form.archive_directory'}},$i);
                   12407:                                     }
                   12408:                                     $env{'form.archive_'.$i} = 'dependency';
                   12409:                                 }
                   12410:                                 $total ++;
                   12411:                             }
                   12412:                             for (my $i=1; $i<$total; $i++) {
                   12413:                                 next if ($i == $displayed{'web'});
                   12414:                                 next if ($i == $displayed{'folder'});
                   12415:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12416:                             }
                   12417:                             $env{'form.phase'} = 'decompress_cleanup';
                   12418:                             $env{'form.archivedelete'} = 1;
                   12419:                             $env{'form.archive_count'} = $total-1;
                   12420:                             $output .=
                   12421:                                 &process_extracted_files('coursedocs',$docudom,
                   12422:                                                          $docuname,$destination,
                   12423:                                                          $dir_root,$hiddenelem);
                   12424:                         }
1.1055    raeburn  12425:                     } else {
                   12426:                         $warning = &mt('No new items extracted from archive file.');
                   12427:                     }
                   12428:                 } else {
                   12429:                     $output = $display;
                   12430:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12431:                 }
                   12432:             }
                   12433:         }
                   12434:     }
                   12435:     if ($error) {
                   12436:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12437:                    $error.'</p>'."\n";
                   12438:     }
                   12439:     if ($warning) {
                   12440:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12441:     }
                   12442:     return $output;
                   12443: }
                   12444: 
                   12445: sub get_extracted {
1.1056    raeburn  12446:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12447:         $titles,$wantform) = @_;
1.1055    raeburn  12448:     my $count = 0;
                   12449:     my $depth = 0;
                   12450:     my $datatable;
1.1056    raeburn  12451:     my @hierarchy;
1.1055    raeburn  12452:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12453:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12454:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12455:     foreach my $item (@{$contents}) {
                   12456:         $count ++;
1.1056    raeburn  12457:         @{$dirorder->{$count}} = @hierarchy;
                   12458:         $titles->{$count} = $item;
1.1055    raeburn  12459:         &archive_hierarchy($depth,$count,$parent,$children);
                   12460:         if ($wantform) {
                   12461:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12462:                                        $currdir,$depth,$count);
                   12463:         }
                   12464:         if ($is_dir->{$item}) {
                   12465:             $depth ++;
1.1056    raeburn  12466:             push(@hierarchy,$count);
                   12467:             $parent->{$depth} = $count;
1.1055    raeburn  12468:             $datatable .=
                   12469:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12470:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12471:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12472:             $depth --;
1.1056    raeburn  12473:             pop(@hierarchy);
1.1055    raeburn  12474:         }
                   12475:     }
                   12476:     return ($count,$datatable);
                   12477: }
                   12478: 
                   12479: sub recurse_extracted_archive {
1.1056    raeburn  12480:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12481:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12482:     my $result='';
1.1056    raeburn  12483:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12484:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12485:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12486:         return $result;
                   12487:     }
                   12488:     my $dirptr = 16384;
                   12489:     my ($newdirlistref,$newlisterror) =
                   12490:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12491:     if (ref($newdirlistref) eq 'ARRAY') {
                   12492:         foreach my $dir_line (@{$newdirlistref}) {
                   12493:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12494:             unless ($item =~ /^\.+$/) {
                   12495:                 $$count ++;
1.1056    raeburn  12496:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12497:                 $titles->{$$count} = $item;
1.1055    raeburn  12498:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12499: 
1.1055    raeburn  12500:                 my $is_dir;
                   12501:                 if ($dirptr&$testdir) {
                   12502:                     $is_dir = 1;
                   12503:                 }
                   12504:                 if ($wantform) {
                   12505:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12506:                 }
                   12507:                 if ($is_dir) {
                   12508:                     $$depth ++;
1.1056    raeburn  12509:                     push(@{$hierarchy},$$count);
                   12510:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12511:                     $result .=
                   12512:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12513:                                                    $docuname,$depth,$count,
1.1056    raeburn  12514:                                                    $hierarchy,$dirorder,$children,
                   12515:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12516:                     $$depth --;
1.1056    raeburn  12517:                     pop(@{$hierarchy});
1.1055    raeburn  12518:                 }
                   12519:             }
                   12520:         }
                   12521:     }
                   12522:     return $result;
                   12523: }
                   12524: 
                   12525: sub archive_hierarchy {
                   12526:     my ($depth,$count,$parent,$children) =@_;
                   12527:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12528:         if (exists($parent->{$depth})) {
                   12529:              $children->{$parent->{$depth}} .= $count.':';
                   12530:         }
                   12531:     }
                   12532:     return;
                   12533: }
                   12534: 
                   12535: sub archive_row {
                   12536:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12537:     my ($name) = ($item =~ m{([^/]+)$});
                   12538:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12539:                                        'display'    => 'Add as file',
1.1055    raeburn  12540:                                        'dependency' => 'Include as dependency',
                   12541:                                        'discard'    => 'Discard',
                   12542:                                       );
                   12543:     if ($is_dir) {
1.1059    raeburn  12544:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12545:     }
1.1056    raeburn  12546:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12547:     my $offset = 0;
1.1055    raeburn  12548:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12549:         $offset ++;
1.1065    raeburn  12550:         if ($action ne 'display') {
                   12551:             $offset ++;
                   12552:         }  
1.1055    raeburn  12553:         $output .= '<td><span class="LC_nobreak">'.
                   12554:                    '<label><input type="radio" name="archive_'.$count.
                   12555:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12556:         my $text = $choices{$action};
                   12557:         if ($is_dir) {
                   12558:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12559:             if ($action eq 'display') {
1.1059    raeburn  12560:                 $text = &mt('Add as folder');
1.1055    raeburn  12561:             }
1.1056    raeburn  12562:         } else {
                   12563:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12564: 
                   12565:         }
                   12566:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12567:         if ($action eq 'dependency') {
                   12568:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12569:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12570:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12571:                        '<option value=""></option>'."\n".
                   12572:                        '</select>'."\n".
                   12573:                        '</div>';
1.1059    raeburn  12574:         } elsif ($action eq 'display') {
                   12575:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12576:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12577:                        '</div>';
1.1055    raeburn  12578:         }
1.1056    raeburn  12579:         $output .= '</td>';
1.1055    raeburn  12580:     }
                   12581:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12582:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12583:     for (my $i=0; $i<$depth; $i++) {
                   12584:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12585:     }
                   12586:     if ($is_dir) {
                   12587:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12588:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12589:     } else {
                   12590:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12591:     }
                   12592:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12593:                &end_data_table_row();
                   12594:     return $output;
                   12595: }
                   12596: 
                   12597: sub archive_options_form {
1.1065    raeburn  12598:     my ($form,$display,$count,$hiddenelem) = @_;
                   12599:     my %lt = &Apache::lonlocal::texthash(
                   12600:                perm => 'Permanently remove archive file?',
                   12601:                hows => 'How should each extracted item be incorporated in the course?',
                   12602:                cont => 'Content actions for all',
                   12603:                addf => 'Add as folder/file',
                   12604:                incd => 'Include as dependency for a displayed file',
                   12605:                disc => 'Discard',
                   12606:                no   => 'No',
                   12607:                yes  => 'Yes',
                   12608:                save => 'Save',
                   12609:     );
                   12610:     my $output = <<"END";
                   12611: <form name="$form" method="post" action="">
                   12612: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12613: <label>
                   12614:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12615: </label>
                   12616: &nbsp;
                   12617: <label>
                   12618:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12619: </span>
                   12620: </p>
                   12621: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12622: <br />$lt{'hows'}
                   12623: <div class="LC_columnSection">
                   12624:   <fieldset>
                   12625:     <legend>$lt{'cont'}</legend>
                   12626:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12627:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12628:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12629:   </fieldset>
                   12630: </div>
                   12631: END
                   12632:     return $output.
1.1055    raeburn  12633:            &start_data_table()."\n".
1.1065    raeburn  12634:            $display."\n".
1.1055    raeburn  12635:            &end_data_table()."\n".
                   12636:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12637:            $hiddenelem.
1.1065    raeburn  12638:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12639:            '</form>';
                   12640: }
                   12641: 
                   12642: sub archive_javascript {
1.1056    raeburn  12643:     my ($startcount,$numitems,$titles,$children) = @_;
                   12644:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12645:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12646:     my $scripttag = <<START;
                   12647: <script type="text/javascript">
                   12648: // <![CDATA[
                   12649: 
                   12650: function checkAll(form,prefix) {
                   12651:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12652:     for (var i=0; i < form.elements.length; i++) {
                   12653:         var id = form.elements[i].id;
                   12654:         if ((id != '') && (id != undefined)) {
                   12655:             if (idstr.test(id)) {
                   12656:                 if (form.elements[i].type == 'radio') {
                   12657:                     form.elements[i].checked = true;
1.1056    raeburn  12658:                     var nostart = i-$startcount;
1.1059    raeburn  12659:                     var offset = nostart%7;
                   12660:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12661:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12662:                 }
                   12663:             }
                   12664:         }
                   12665:     }
                   12666: }
                   12667: 
                   12668: function propagateCheck(form,count) {
                   12669:     if (count > 0) {
1.1059    raeburn  12670:         var startelement = $startcount + ((count-1) * 7);
                   12671:         for (var j=1; j<6; j++) {
                   12672:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12673:                 var item = startelement + j; 
                   12674:                 if (form.elements[item].type == 'radio') {
                   12675:                     if (form.elements[item].checked) {
                   12676:                         containerCheck(form,count,j);
                   12677:                         break;
                   12678:                     }
1.1055    raeburn  12679:                 }
                   12680:             }
                   12681:         }
                   12682:     }
                   12683: }
                   12684: 
                   12685: numitems = $numitems
1.1056    raeburn  12686: var titles = new Array(numitems);
                   12687: var parents = new Array(numitems);
1.1055    raeburn  12688: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12689:     parents[i] = new Array;
1.1055    raeburn  12690: }
1.1059    raeburn  12691: var maintitle = '$maintitle';
1.1055    raeburn  12692: 
                   12693: START
                   12694: 
1.1056    raeburn  12695:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12696:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12697:         for (my $i=0; $i<@contents; $i ++) {
                   12698:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12699:         }
                   12700:     }
                   12701: 
1.1056    raeburn  12702:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12703:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12704:     }
                   12705: 
1.1055    raeburn  12706:     $scripttag .= <<END;
                   12707: 
                   12708: function containerCheck(form,count,offset) {
                   12709:     if (count > 0) {
1.1056    raeburn  12710:         dependencyCheck(form,count,offset);
1.1059    raeburn  12711:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12712:         form.elements[item].checked = true;
                   12713:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12714:             if (parents[count].length > 0) {
                   12715:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12716:                     containerCheck(form,parents[count][j],offset);
                   12717:                 }
                   12718:             }
                   12719:         }
                   12720:     }
                   12721: }
                   12722: 
                   12723: function dependencyCheck(form,count,offset) {
                   12724:     if (count > 0) {
1.1059    raeburn  12725:         var chosen = (offset+$startcount)+7*(count-1);
                   12726:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12727:         var currtype = form.elements[depitem].type;
                   12728:         if (form.elements[chosen].value == 'dependency') {
                   12729:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12730:             form.elements[depitem].options.length = 0;
                   12731:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12732:             for (var i=1; i<=numitems; i++) {
                   12733:                 if (i == count) {
                   12734:                     continue;
                   12735:                 }
1.1059    raeburn  12736:                 var startelement = $startcount + (i-1) * 7;
                   12737:                 for (var j=1; j<6; j++) {
                   12738:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12739:                         var item = startelement + j;
                   12740:                         if (form.elements[item].type == 'radio') {
                   12741:                             if (form.elements[item].checked) {
                   12742:                                 if (form.elements[item].value == 'display') {
                   12743:                                     var n = form.elements[depitem].options.length;
                   12744:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12745:                                 }
                   12746:                             }
                   12747:                         }
                   12748:                     }
                   12749:                 }
                   12750:             }
                   12751:         } else {
                   12752:             document.getElementById('arc_depon_'+count).style.display='none';
                   12753:             form.elements[depitem].options.length = 0;
                   12754:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12755:         }
1.1059    raeburn  12756:         titleCheck(form,count,offset);
1.1056    raeburn  12757:     }
                   12758: }
                   12759: 
                   12760: function propagateSelect(form,count,offset) {
                   12761:     if (count > 0) {
1.1065    raeburn  12762:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12763:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12764:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12765:             if (parents[count].length > 0) {
                   12766:                 for (var j=0; j<parents[count].length; j++) {
                   12767:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12768:                 }
                   12769:             }
                   12770:         }
                   12771:     }
                   12772: }
1.1056    raeburn  12773: 
                   12774: function containerSelect(form,count,offset,picked) {
                   12775:     if (count > 0) {
1.1065    raeburn  12776:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12777:         if (form.elements[item].type == 'radio') {
                   12778:             if (form.elements[item].value == 'dependency') {
                   12779:                 if (form.elements[item+1].type == 'select-one') {
                   12780:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12781:                         if (form.elements[item+1].options[i].value == picked) {
                   12782:                             form.elements[item+1].selectedIndex = i;
                   12783:                             break;
                   12784:                         }
                   12785:                     }
                   12786:                 }
                   12787:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12788:                     if (parents[count].length > 0) {
                   12789:                         for (var j=0; j<parents[count].length; j++) {
                   12790:                             containerSelect(form,parents[count][j],offset,picked);
                   12791:                         }
                   12792:                     }
                   12793:                 }
                   12794:             }
                   12795:         }
                   12796:     }
                   12797: }
                   12798: 
1.1059    raeburn  12799: function titleCheck(form,count,offset) {
                   12800:     if (count > 0) {
                   12801:         var chosen = (offset+$startcount)+7*(count-1);
                   12802:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12803:         var currtype = form.elements[depitem].type;
                   12804:         if (form.elements[chosen].value == 'display') {
                   12805:             document.getElementById('arc_title_'+count).style.display='block';
                   12806:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12807:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12808:             }
                   12809:         } else {
                   12810:             document.getElementById('arc_title_'+count).style.display='none';
                   12811:             if (currtype == 'text') { 
                   12812:                 document.getElementById('archive_title_'+count).value='';
                   12813:             }
                   12814:         }
                   12815:     }
                   12816:     return;
                   12817: }
                   12818: 
1.1055    raeburn  12819: // ]]>
                   12820: </script>
                   12821: END
                   12822:     return $scripttag;
                   12823: }
                   12824: 
                   12825: sub process_extracted_files {
1.1067    raeburn  12826:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12827:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12828:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12829:     my @ids=&Apache::lonnet::current_machine_ids();
                   12830:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12831:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12832:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12833:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12834:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12835:         $pathtocheck = "$dir_root/$destination";
                   12836:         $dir = $dir_root;
                   12837:         $ishome = 1;
                   12838:     } else {
                   12839:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12840:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12841:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12842:     }
                   12843:     my $currdir = "$dir_root/$destination";
                   12844:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12845:     if ($env{'form.folderpath'}) {
                   12846:         my @items = split('&',$env{'form.folderpath'});
                   12847:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12848:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12849:             $containers{'0'}='page';
                   12850:         } else {
                   12851:             $containers{'0'}='sequence';
                   12852:         }
1.1055    raeburn  12853:     }
                   12854:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12855:     if ($numitems) {
                   12856:         for (my $i=1; $i<=$numitems; $i++) {
                   12857:             my $path = $env{'form.archive_content_'.$i};
                   12858:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12859:                 my $item = $1;
                   12860:                 $toplevelitems{$item} = $i;
                   12861:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12862:                     $is_dir{$item} = 1;
                   12863:                 }
                   12864:             }
                   12865:         }
                   12866:     }
1.1067    raeburn  12867:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12868:     if (keys(%toplevelitems) > 0) {
                   12869:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12870:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12871:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12872:     }
1.1066    raeburn  12873:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12874:     if ($numitems) {
                   12875:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12876:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12877:             my $path = $env{'form.archive_content_'.$i};
                   12878:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12879:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12880:                     if ($prefix ne '' && $path ne '') {
                   12881:                         if (-e $prefix.$path) {
1.1066    raeburn  12882:                             if ((@archdirs > 0) && 
                   12883:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12884:                                 $todeletedir{$prefix.$path} = 1;
                   12885:                             } else {
                   12886:                                 $todelete{$prefix.$path} = 1;
                   12887:                             }
1.1055    raeburn  12888:                         }
                   12889:                     }
                   12890:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12891:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12892:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12893:                     $docstitle = $env{'form.archive_title_'.$i};
                   12894:                     if ($docstitle eq '') {
                   12895:                         $docstitle = $title;
                   12896:                     }
1.1055    raeburn  12897:                     $outer = 0;
1.1056    raeburn  12898:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12899:                         if (@{$dirorder{$i}} > 0) {
                   12900:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12901:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12902:                                     $outer = $item;
                   12903:                                     last;
                   12904:                                 }
                   12905:                             }
                   12906:                         }
                   12907:                     }
                   12908:                     my ($errtext,$fatal) = 
                   12909:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12910:                                                '/'.$folders{$outer}.'.'.
                   12911:                                                $containers{$outer});
                   12912:                     next if ($fatal);
                   12913:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12914:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12915:                             $mapinner{$i} = time;
1.1055    raeburn  12916:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12917:                             $containers{$i} = 'sequence';
                   12918:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12919:                                       $folders{$i}.'.'.$containers{$i};
                   12920:                             my $newidx = &LONCAPA::map::getresidx();
                   12921:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12922:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12923:                             push(@LONCAPA::map::order,$newidx);
                   12924:                             my ($outtext,$errtext) =
                   12925:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12926:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12927:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12928:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12929:                             unless ($errtext) {
1.1075.2.128  raeburn  12930:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12931:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12932:                                             '</li>'."\n";
1.1067    raeburn  12933:                             }
1.1055    raeburn  12934:                         }
                   12935:                     } else {
                   12936:                         if ($context eq 'coursedocs') {
                   12937:                             my $newidx=&LONCAPA::map::getresidx();
                   12938:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12939:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12940:                                       $title;
1.1075.2.128  raeburn  12941:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12942:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12943:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12944:                                 }
1.1075.2.128  raeburn  12945:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12946:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12947:                                 }
                   12948:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12949:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12950:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12951:                                         unless ($ishome) {
                   12952:                                             my $fetch = "$newdest{$i}/$title";
                   12953:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12954:                                             $prompttofetch{$fetch} = 1;
                   12955:                                         }
                   12956:                                    }
                   12957:                                 }
                   12958:                                 $LONCAPA::map::resources[$newidx]=
                   12959:                                     $docstitle.':'.$url.':false:normal:res';
                   12960:                                 push(@LONCAPA::map::order, $newidx);
                   12961:                                 my ($outtext,$errtext)=
                   12962:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12963:                                                             $docuname.'/'.$folders{$outer}.
                   12964:                                                             '.'.$containers{$outer},1,1);
                   12965:                                 unless ($errtext) {
                   12966:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12967:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12968:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12969:                                                    '</li>'."\n";
                   12970:                                     }
1.1067    raeburn  12971:                                 }
1.1075.2.128  raeburn  12972:                             } else {
                   12973:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12974:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  12975:                             }
1.1055    raeburn  12976:                         }
                   12977:                     }
1.1075.2.11  raeburn  12978:                 }
                   12979:             } else {
1.1075.2.128  raeburn  12980:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12981:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  12982:             }
                   12983:         }
                   12984:         for (my $i=1; $i<=$numitems; $i++) {
                   12985:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12986:             my $path = $env{'form.archive_content_'.$i};
                   12987:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12988:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12989:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12990:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12991:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12992:                         my ($itemidx,$fullpath,$relpath);
                   12993:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12994:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12995:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12996:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12997:                                     $itemidx = $j;
1.1056    raeburn  12998:                                 }
                   12999:                             }
1.1075.2.11  raeburn  13000:                         }
                   13001:                         if ($itemidx eq '') {
                   13002:                             $itemidx =  0;
                   13003:                         }
                   13004:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13005:                             if ($mapinner{$referrer{$i}}) {
                   13006:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13007:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13008:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13009:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13010:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13011:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13012:                                             if (!-e $fullpath) {
                   13013:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13014:                                             }
                   13015:                                         }
1.1075.2.11  raeburn  13016:                                     } else {
                   13017:                                         last;
1.1056    raeburn  13018:                                     }
1.1075.2.11  raeburn  13019:                                 }
                   13020:                             }
                   13021:                         } elsif ($newdest{$referrer{$i}}) {
                   13022:                             $fullpath = $newdest{$referrer{$i}};
                   13023:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13024:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13025:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13026:                                     last;
                   13027:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13028:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13029:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13030:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13031:                                         if (!-e $fullpath) {
                   13032:                                             mkdir($fullpath,0755);
1.1056    raeburn  13033:                                         }
                   13034:                                     }
1.1075.2.11  raeburn  13035:                                 } else {
                   13036:                                     last;
1.1056    raeburn  13037:                                 }
1.1075.2.11  raeburn  13038:                             }
                   13039:                         }
                   13040:                         if ($fullpath ne '') {
                   13041:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13042:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13043:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13044:                                 }
1.1075.2.11  raeburn  13045:                             }
                   13046:                             if (-e "$fullpath/$title") {
                   13047:                                 my $showpath;
                   13048:                                 if ($relpath ne '') {
                   13049:                                     $showpath = "$relpath/$title";
                   13050:                                 } else {
                   13051:                                     $showpath = "/$title";
1.1056    raeburn  13052:                                 }
1.1075.2.128  raeburn  13053:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13054:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13055:                                            '</li>'."\n";
                   13056:                                 unless ($ishome) {
                   13057:                                     my $fetch = "$fullpath/$title";
                   13058:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13059:                                     $prompttofetch{$fetch} = 1;
                   13060:                                 }
1.1055    raeburn  13061:                             }
                   13062:                         }
                   13063:                     }
1.1075.2.11  raeburn  13064:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13065:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13066:                                     &HTML::Entities::encode($path,'<>&"'),
                   13067:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13068:                                 '<br />';
1.1055    raeburn  13069:                 }
                   13070:             } else {
1.1075.2.128  raeburn  13071:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13072:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13073:             }
                   13074:         }
                   13075:         if (keys(%todelete)) {
                   13076:             foreach my $key (keys(%todelete)) {
                   13077:                 unlink($key);
1.1066    raeburn  13078:             }
                   13079:         }
                   13080:         if (keys(%todeletedir)) {
                   13081:             foreach my $key (keys(%todeletedir)) {
                   13082:                 rmdir($key);
                   13083:             }
                   13084:         }
                   13085:         foreach my $dir (sort(keys(%is_dir))) {
                   13086:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13087:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13088:             }
                   13089:         }
1.1067    raeburn  13090:         if ($result ne '') {
                   13091:             $output .= '<ul>'."\n".
                   13092:                        $result."\n".
                   13093:                        '</ul>';
                   13094:         }
                   13095:         unless ($ishome) {
                   13096:             my $replicationfail;
                   13097:             foreach my $item (keys(%prompttofetch)) {
                   13098:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13099:                 unless ($fetchresult eq 'ok') {
                   13100:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13101:                 }
                   13102:             }
                   13103:             if ($replicationfail) {
                   13104:                 $output .= '<p class="LC_error">'.
                   13105:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13106:                            $replicationfail.
                   13107:                            '</ul></p>';
                   13108:             }
                   13109:         }
1.1055    raeburn  13110:     } else {
                   13111:         $warning = &mt('No items found in archive.');
                   13112:     }
                   13113:     if ($error) {
                   13114:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13115:                    $error.'</p>'."\n";
                   13116:     }
                   13117:     if ($warning) {
                   13118:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13119:     }
                   13120:     return $output;
                   13121: }
                   13122: 
1.1066    raeburn  13123: sub cleanup_empty_dirs {
                   13124:     my ($path) = @_;
                   13125:     if (($path ne '') && (-d $path)) {
                   13126:         if (opendir(my $dirh,$path)) {
                   13127:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13128:             my $numitems = 0;
                   13129:             foreach my $item (@dircontents) {
                   13130:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13131:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13132:                     if (-e "$path/$item") {
                   13133:                         $numitems ++;
                   13134:                     }
                   13135:                 } else {
                   13136:                     $numitems ++;
                   13137:                 }
                   13138:             }
                   13139:             if ($numitems == 0) {
                   13140:                 rmdir($path);
                   13141:             }
                   13142:             closedir($dirh);
                   13143:         }
                   13144:     }
                   13145:     return;
                   13146: }
                   13147: 
1.41      ng       13148: =pod
1.45      matthew  13149: 
1.1075.2.56  raeburn  13150: =item * &get_folder_hierarchy()
1.1068    raeburn  13151: 
                   13152: Provides hierarchy of names of folders/sub-folders containing the current
                   13153: item,
                   13154: 
                   13155: Inputs: 3
                   13156:      - $navmap - navmaps object
                   13157: 
                   13158:      - $map - url for map (either the trigger itself, or map containing
                   13159:                            the resource, which is the trigger).
                   13160: 
                   13161:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13162: 
                   13163: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13164: 
                   13165: =cut
                   13166: 
                   13167: sub get_folder_hierarchy {
                   13168:     my ($navmap,$map,$showitem) = @_;
                   13169:     my @pathitems;
                   13170:     if (ref($navmap)) {
                   13171:         my $mapres = $navmap->getResourceByUrl($map);
                   13172:         if (ref($mapres)) {
                   13173:             my $pcslist = $mapres->map_hierarchy();
                   13174:             if ($pcslist ne '') {
                   13175:                 my @pcs = split(/,/,$pcslist);
                   13176:                 foreach my $pc (@pcs) {
                   13177:                     if ($pc == 1) {
1.1075.2.38  raeburn  13178:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13179:                     } else {
                   13180:                         my $res = $navmap->getByMapPc($pc);
                   13181:                         if (ref($res)) {
                   13182:                             my $title = $res->compTitle();
                   13183:                             $title =~ s/\W+/_/g;
                   13184:                             if ($title ne '') {
                   13185:                                 push(@pathitems,$title);
                   13186:                             }
                   13187:                         }
                   13188:                     }
                   13189:                 }
                   13190:             }
1.1071    raeburn  13191:             if ($showitem) {
                   13192:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13193:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13194:                 } else {
                   13195:                     my $maptitle = $mapres->compTitle();
                   13196:                     $maptitle =~ s/\W+/_/g;
                   13197:                     if ($maptitle ne '') {
                   13198:                         push(@pathitems,$maptitle);
                   13199:                     }
1.1068    raeburn  13200:                 }
                   13201:             }
                   13202:         }
                   13203:     }
                   13204:     return @pathitems;
                   13205: }
                   13206: 
                   13207: =pod
                   13208: 
1.1015    raeburn  13209: =item * &get_turnedin_filepath()
                   13210: 
                   13211: Determines path in a user's portfolio file for storage of files uploaded
                   13212: to a specific essayresponse or dropbox item.
                   13213: 
                   13214: Inputs: 3 required + 1 optional.
                   13215: $symb is symb for resource, $uname and $udom are for current user (required).
                   13216: $caller is optional (can be "submission", if routine is called when storing
                   13217: an upoaded file when "Submit Answer" button was pressed).
                   13218: 
                   13219: Returns array containing $path and $multiresp. 
                   13220: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13221: than one file upload item.  Callers of routine should append partid as a 
                   13222: subdirectory to $path in cases where $multiresp is 1.
                   13223: 
                   13224: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13225: 
                   13226: =cut
                   13227: 
                   13228: sub get_turnedin_filepath {
                   13229:     my ($symb,$uname,$udom,$caller) = @_;
                   13230:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13231:     my $turnindir;
                   13232:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13233:     $turnindir = $userhash{'turnindir'};
                   13234:     my ($path,$multiresp);
                   13235:     if ($turnindir eq '') {
                   13236:         if ($caller eq 'submission') {
                   13237:             $turnindir = &mt('turned in');
                   13238:             $turnindir =~ s/\W+/_/g;
                   13239:             my %newhash = (
                   13240:                             'turnindir' => $turnindir,
                   13241:                           );
                   13242:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13243:         }
                   13244:     }
                   13245:     if ($turnindir ne '') {
                   13246:         $path = '/'.$turnindir.'/';
                   13247:         my ($multipart,$turnin,@pathitems);
                   13248:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13249:         if (defined($navmap)) {
                   13250:             my $mapres = $navmap->getResourceByUrl($map);
                   13251:             if (ref($mapres)) {
                   13252:                 my $pcslist = $mapres->map_hierarchy();
                   13253:                 if ($pcslist ne '') {
                   13254:                     foreach my $pc (split(/,/,$pcslist)) {
                   13255:                         my $res = $navmap->getByMapPc($pc);
                   13256:                         if (ref($res)) {
                   13257:                             my $title = $res->compTitle();
                   13258:                             $title =~ s/\W+/_/g;
                   13259:                             if ($title ne '') {
1.1075.2.48  raeburn  13260:                                 if (($pc > 1) && (length($title) > 12)) {
                   13261:                                     $title = substr($title,0,12);
                   13262:                                 }
1.1015    raeburn  13263:                                 push(@pathitems,$title);
                   13264:                             }
                   13265:                         }
                   13266:                     }
                   13267:                 }
                   13268:                 my $maptitle = $mapres->compTitle();
                   13269:                 $maptitle =~ s/\W+/_/g;
                   13270:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13271:                     if (length($maptitle) > 12) {
                   13272:                         $maptitle = substr($maptitle,0,12);
                   13273:                     }
1.1015    raeburn  13274:                     push(@pathitems,$maptitle);
                   13275:                 }
                   13276:                 unless ($env{'request.state'} eq 'construct') {
                   13277:                     my $res = $navmap->getBySymb($symb);
                   13278:                     if (ref($res)) {
                   13279:                         my $partlist = $res->parts();
                   13280:                         my $totaluploads = 0;
                   13281:                         if (ref($partlist) eq 'ARRAY') {
                   13282:                             foreach my $part (@{$partlist}) {
                   13283:                                 my @types = $res->responseType($part);
                   13284:                                 my @ids = $res->responseIds($part);
                   13285:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13286:                                     if ($types[$i] eq 'essay') {
                   13287:                                         my $partid = $part.'_'.$ids[$i];
                   13288:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13289:                                             $totaluploads ++;
                   13290:                                         }
                   13291:                                     }
                   13292:                                 }
                   13293:                             }
                   13294:                             if ($totaluploads > 1) {
                   13295:                                 $multiresp = 1;
                   13296:                             }
                   13297:                         }
                   13298:                     }
                   13299:                 }
                   13300:             } else {
                   13301:                 return;
                   13302:             }
                   13303:         } else {
                   13304:             return;
                   13305:         }
                   13306:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13307:         $restitle =~ s/\W+/_/g;
                   13308:         if ($restitle eq '') {
                   13309:             $restitle = ($resurl =~ m{/[^/]+$});
                   13310:             if ($restitle eq '') {
                   13311:                 $restitle = time;
                   13312:             }
                   13313:         }
1.1075.2.48  raeburn  13314:         if (length($restitle) > 12) {
                   13315:             $restitle = substr($restitle,0,12);
                   13316:         }
1.1015    raeburn  13317:         push(@pathitems,$restitle);
                   13318:         $path .= join('/',@pathitems);
                   13319:     }
                   13320:     return ($path,$multiresp);
                   13321: }
                   13322: 
                   13323: =pod
                   13324: 
1.464     albertel 13325: =back
1.41      ng       13326: 
1.112     bowersj2 13327: =head1 CSV Upload/Handling functions
1.38      albertel 13328: 
1.41      ng       13329: =over 4
                   13330: 
1.648     raeburn  13331: =item * &upfile_store($r)
1.41      ng       13332: 
                   13333: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13334: needs $env{'form.upfile'}
1.41      ng       13335: returns $datatoken to be put into hidden field
                   13336: 
                   13337: =cut
1.31      albertel 13338: 
                   13339: sub upfile_store {
                   13340:     my $r=shift;
1.258     albertel 13341:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13342:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13343:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13344:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13345: 
1.1075.2.128  raeburn  13346:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13347:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13348:                                      time.'_'.$$);
                   13349:     return if ($datatoken eq '');
                   13350: 
1.31      albertel 13351:     {
1.158     raeburn  13352:         my $datafile = $r->dir_config('lonDaemons').
                   13353:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13354:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13355:             print $fh $env{'form.upfile'};
1.158     raeburn  13356:             close($fh);
                   13357:         }
1.31      albertel 13358:     }
                   13359:     return $datatoken;
                   13360: }
                   13361: 
1.56      matthew  13362: =pod
                   13363: 
1.1075.2.128  raeburn  13364: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13365: 
                   13366: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13367: $datatoken is the name to assign to the temporary file.
1.258     albertel 13368: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13369: 
                   13370: =cut
1.31      albertel 13371: 
                   13372: sub load_tmp_file {
1.1075.2.128  raeburn  13373:     my ($r,$datatoken) = @_;
                   13374:     return if ($datatoken eq '');
1.31      albertel 13375:     my @studentdata=();
                   13376:     {
1.158     raeburn  13377:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13378:                               '/tmp/'.$datatoken.'.tmp';
                   13379:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13380:             @studentdata=<$fh>;
                   13381:             close($fh);
                   13382:         }
1.31      albertel 13383:     }
1.258     albertel 13384:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13385: }
                   13386: 
1.1075.2.128  raeburn  13387: sub valid_datatoken {
                   13388:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13389:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13390:         return $datatoken;
                   13391:     }
                   13392:     return;
                   13393: }
                   13394: 
1.56      matthew  13395: =pod
                   13396: 
1.648     raeburn  13397: =item * &upfile_record_sep()
1.41      ng       13398: 
                   13399: Separate uploaded file into records
                   13400: returns array of records,
1.258     albertel 13401: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13402: 
                   13403: =cut
1.31      albertel 13404: 
                   13405: sub upfile_record_sep {
1.258     albertel 13406:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13407:     } else {
1.248     albertel 13408: 	my @records;
1.258     albertel 13409: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13410: 	    if ($line=~/^\s*$/) { next; }
                   13411: 	    push(@records,$line);
                   13412: 	}
                   13413: 	return @records;
1.31      albertel 13414:     }
                   13415: }
                   13416: 
1.56      matthew  13417: =pod
                   13418: 
1.648     raeburn  13419: =item * &record_sep($record)
1.41      ng       13420: 
1.258     albertel 13421: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13422: 
                   13423: =cut
                   13424: 
1.263     www      13425: sub takeleft {
                   13426:     my $index=shift;
                   13427:     return substr('0000'.$index,-4,4);
                   13428: }
                   13429: 
1.31      albertel 13430: sub record_sep {
                   13431:     my $record=shift;
                   13432:     my %components=();
1.258     albertel 13433:     if ($env{'form.upfiletype'} eq 'xml') {
                   13434:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13435:         my $i=0;
1.356     albertel 13436:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13437:             $field=~s/^(\"|\')//;
                   13438:             $field=~s/(\"|\')$//;
1.263     www      13439:             $components{&takeleft($i)}=$field;
1.31      albertel 13440:             $i++;
                   13441:         }
1.258     albertel 13442:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13443:         my $i=0;
1.356     albertel 13444:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13445:             $field=~s/^(\"|\')//;
                   13446:             $field=~s/(\"|\')$//;
1.263     www      13447:             $components{&takeleft($i)}=$field;
1.31      albertel 13448:             $i++;
                   13449:         }
                   13450:     } else {
1.561     www      13451:         my $separator=',';
1.480     banghart 13452:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13453:             $separator=';';
1.480     banghart 13454:         }
1.31      albertel 13455:         my $i=0;
1.561     www      13456: # the character we are looking for to indicate the end of a quote or a record 
                   13457:         my $looking_for=$separator;
                   13458: # do not add the characters to the fields
                   13459:         my $ignore=0;
                   13460: # we just encountered a separator (or the beginning of the record)
                   13461:         my $just_found_separator=1;
                   13462: # store the field we are working on here
                   13463:         my $field='';
                   13464: # work our way through all characters in record
                   13465:         foreach my $character ($record=~/(.)/g) {
                   13466:             if ($character eq $looking_for) {
                   13467:                if ($character ne $separator) {
                   13468: # Found the end of a quote, again looking for separator
                   13469:                   $looking_for=$separator;
                   13470:                   $ignore=1;
                   13471:                } else {
                   13472: # Found a separator, store away what we got
                   13473:                   $components{&takeleft($i)}=$field;
                   13474: 	          $i++;
                   13475:                   $just_found_separator=1;
                   13476:                   $ignore=0;
                   13477:                   $field='';
                   13478:                }
                   13479:                next;
                   13480:             }
                   13481: # single or double quotation marks after a separator indicate beginning of a quote
                   13482: # we are now looking for the end of the quote and need to ignore separators
                   13483:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13484:                $looking_for=$character;
                   13485:                next;
                   13486:             }
                   13487: # ignore would be true after we reached the end of a quote
                   13488:             if ($ignore) { next; }
                   13489:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13490:             $field.=$character;
                   13491:             $just_found_separator=0; 
1.31      albertel 13492:         }
1.561     www      13493: # catch the very last entry, since we never encountered the separator
                   13494:         $components{&takeleft($i)}=$field;
1.31      albertel 13495:     }
                   13496:     return %components;
                   13497: }
                   13498: 
1.144     matthew  13499: ######################################################
                   13500: ######################################################
                   13501: 
1.56      matthew  13502: =pod
                   13503: 
1.648     raeburn  13504: =item * &upfile_select_html()
1.41      ng       13505: 
1.144     matthew  13506: Return HTML code to select a file from the users machine and specify 
                   13507: the file type.
1.41      ng       13508: 
                   13509: =cut
                   13510: 
1.144     matthew  13511: ######################################################
                   13512: ######################################################
1.31      albertel 13513: sub upfile_select_html {
1.144     matthew  13514:     my %Types = (
                   13515:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13516:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13517:                  space => &mt('Space separated'),
                   13518:                  tab   => &mt('Tabulator separated'),
                   13519: #                 xml   => &mt('HTML/XML'),
                   13520:                  );
                   13521:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13522:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13523:     foreach my $type (sort(keys(%Types))) {
                   13524:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13525:     }
                   13526:     $Str .= "</select>\n";
                   13527:     return $Str;
1.31      albertel 13528: }
                   13529: 
1.301     albertel 13530: sub get_samples {
                   13531:     my ($records,$toget) = @_;
                   13532:     my @samples=({});
                   13533:     my $got=0;
                   13534:     foreach my $rec (@$records) {
                   13535: 	my %temp = &record_sep($rec);
                   13536: 	if (! grep(/\S/, values(%temp))) { next; }
                   13537: 	if (%temp) {
                   13538: 	    $samples[$got]=\%temp;
                   13539: 	    $got++;
                   13540: 	    if ($got == $toget) { last; }
                   13541: 	}
                   13542:     }
                   13543:     return \@samples;
                   13544: }
                   13545: 
1.144     matthew  13546: ######################################################
                   13547: ######################################################
                   13548: 
1.56      matthew  13549: =pod
                   13550: 
1.648     raeburn  13551: =item * &csv_print_samples($r,$records)
1.41      ng       13552: 
                   13553: Prints a table of sample values from each column uploaded $r is an
                   13554: Apache Request ref, $records is an arrayref from
                   13555: &Apache::loncommon::upfile_record_sep
                   13556: 
                   13557: =cut
                   13558: 
1.144     matthew  13559: ######################################################
                   13560: ######################################################
1.31      albertel 13561: sub csv_print_samples {
                   13562:     my ($r,$records) = @_;
1.662     bisitz   13563:     my $samples = &get_samples($records,5);
1.301     albertel 13564: 
1.594     raeburn  13565:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13566:               &start_data_table_header_row());
1.356     albertel 13567:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13568:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13569:     $r->print(&end_data_table_header_row());
1.301     albertel 13570:     foreach my $hash (@$samples) {
1.594     raeburn  13571: 	$r->print(&start_data_table_row());
1.356     albertel 13572: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13573: 	    $r->print('<td>');
1.356     albertel 13574: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13575: 	    $r->print('</td>');
                   13576: 	}
1.594     raeburn  13577: 	$r->print(&end_data_table_row());
1.31      albertel 13578:     }
1.594     raeburn  13579:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13580: }
                   13581: 
1.144     matthew  13582: ######################################################
                   13583: ######################################################
                   13584: 
1.56      matthew  13585: =pod
                   13586: 
1.648     raeburn  13587: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13588: 
                   13589: Prints a table to create associations between values and table columns.
1.144     matthew  13590: 
1.41      ng       13591: $r is an Apache Request ref,
                   13592: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13593: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13594: 
                   13595: =cut
                   13596: 
1.144     matthew  13597: ######################################################
                   13598: ######################################################
1.31      albertel 13599: sub csv_print_select_table {
                   13600:     my ($r,$records,$d) = @_;
1.301     albertel 13601:     my $i=0;
                   13602:     my $samples = &get_samples($records,1);
1.144     matthew  13603:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13604: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13605:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13606:               '<th>'.&mt('Column').'</th>'.
                   13607:               &end_data_table_header_row()."\n");
1.356     albertel 13608:     foreach my $array_ref (@$d) {
                   13609: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13610: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13611: 
1.875     bisitz   13612: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13613: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13614: 	$r->print('<option value="none"></option>');
1.356     albertel 13615: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13616: 	    $r->print('<option value="'.$sample.'"'.
                   13617:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13618:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13619: 	}
1.594     raeburn  13620: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13621: 	$i++;
                   13622:     }
1.594     raeburn  13623:     $r->print(&end_data_table());
1.31      albertel 13624:     $i--;
                   13625:     return $i;
                   13626: }
1.56      matthew  13627: 
1.144     matthew  13628: ######################################################
                   13629: ######################################################
                   13630: 
1.56      matthew  13631: =pod
1.31      albertel 13632: 
1.648     raeburn  13633: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13634: 
                   13635: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13636: 
                   13637: $r is an Apache Request ref,
                   13638: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13639: $d is an array of 2 element arrays (internal name, displayed name)
                   13640: 
                   13641: =cut
                   13642: 
1.144     matthew  13643: ######################################################
                   13644: ######################################################
1.31      albertel 13645: sub csv_samples_select_table {
                   13646:     my ($r,$records,$d) = @_;
                   13647:     my $i=0;
1.144     matthew  13648:     #
1.662     bisitz   13649:     my $max_samples = 5;
                   13650:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13651:     $r->print(&start_data_table().
                   13652:               &start_data_table_header_row().'<th>'.
                   13653:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13654:               &end_data_table_header_row());
1.301     albertel 13655: 
                   13656:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13657: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13658: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13659: 	foreach my $option (@$d) {
                   13660: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13661: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13662:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13663:                       $display.'</option>');
1.31      albertel 13664: 	}
                   13665: 	$r->print('</select></td><td>');
1.662     bisitz   13666: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13667: 	    if (defined($samples->[$line]{$key})) { 
                   13668: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13669: 	    }
                   13670: 	}
1.594     raeburn  13671: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13672: 	$i++;
                   13673:     }
1.594     raeburn  13674:     $r->print(&end_data_table());
1.31      albertel 13675:     $i--;
                   13676:     return($i);
1.115     matthew  13677: }
                   13678: 
1.144     matthew  13679: ######################################################
                   13680: ######################################################
                   13681: 
1.115     matthew  13682: =pod
                   13683: 
1.648     raeburn  13684: =item * &clean_excel_name($name)
1.115     matthew  13685: 
                   13686: Returns a replacement for $name which does not contain any illegal characters.
                   13687: 
                   13688: =cut
                   13689: 
1.144     matthew  13690: ######################################################
                   13691: ######################################################
1.115     matthew  13692: sub clean_excel_name {
                   13693:     my ($name) = @_;
                   13694:     $name =~ s/[:\*\?\/\\]//g;
                   13695:     if (length($name) > 31) {
                   13696:         $name = substr($name,0,31);
                   13697:     }
                   13698:     return $name;
1.25      albertel 13699: }
1.84      albertel 13700: 
1.85      albertel 13701: =pod
                   13702: 
1.648     raeburn  13703: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13704: 
                   13705: Returns either 1 or undef
                   13706: 
                   13707: 1 if the part is to be hidden, undef if it is to be shown
                   13708: 
                   13709: Arguments are:
                   13710: 
                   13711: $id the id of the part to be checked
                   13712: $symb, optional the symb of the resource to check
                   13713: $udom, optional the domain of the user to check for
                   13714: $uname, optional the username of the user to check for
                   13715: 
                   13716: =cut
1.84      albertel 13717: 
                   13718: sub check_if_partid_hidden {
                   13719:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13720:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13721: 					 $symb,$udom,$uname);
1.141     albertel 13722:     my $truth=1;
                   13723:     #if the string starts with !, then the list is the list to show not hide
                   13724:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13725:     my @hiddenlist=split(/,/,$hiddenparts);
                   13726:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13727: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13728:     }
1.141     albertel 13729:     return !$truth;
1.84      albertel 13730: }
1.127     matthew  13731: 
1.138     matthew  13732: 
                   13733: ############################################################
                   13734: ############################################################
                   13735: 
                   13736: =pod
                   13737: 
1.157     matthew  13738: =back 
                   13739: 
1.138     matthew  13740: =head1 cgi-bin script and graphing routines
                   13741: 
1.157     matthew  13742: =over 4
                   13743: 
1.648     raeburn  13744: =item * &get_cgi_id()
1.138     matthew  13745: 
                   13746: Inputs: none
                   13747: 
                   13748: Returns an id which can be used to pass environment variables
                   13749: to various cgi-bin scripts.  These environment variables will
                   13750: be removed from the users environment after a given time by
                   13751: the routine &Apache::lonnet::transfer_profile_to_env.
                   13752: 
                   13753: =cut
                   13754: 
                   13755: ############################################################
                   13756: ############################################################
1.152     albertel 13757: my $uniq=0;
1.136     matthew  13758: sub get_cgi_id {
1.154     albertel 13759:     $uniq=($uniq+1)%100000;
1.280     albertel 13760:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13761: }
                   13762: 
1.127     matthew  13763: ############################################################
                   13764: ############################################################
                   13765: 
                   13766: =pod
                   13767: 
1.648     raeburn  13768: =item * &DrawBarGraph()
1.127     matthew  13769: 
1.138     matthew  13770: Facilitates the plotting of data in a (stacked) bar graph.
                   13771: Puts plot definition data into the users environment in order for 
                   13772: graph.png to plot it.  Returns an <img> tag for the plot.
                   13773: The bars on the plot are labeled '1','2',...,'n'.
                   13774: 
                   13775: Inputs:
                   13776: 
                   13777: =over 4
                   13778: 
                   13779: =item $Title: string, the title of the plot
                   13780: 
                   13781: =item $xlabel: string, text describing the X-axis of the plot
                   13782: 
                   13783: =item $ylabel: string, text describing the Y-axis of the plot
                   13784: 
                   13785: =item $Max: scalar, the maximum Y value to use in the plot
                   13786: If $Max is < any data point, the graph will not be rendered.
                   13787: 
1.140     matthew  13788: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13789: they are plotted.  If undefined, default values will be used.
                   13790: 
1.178     matthew  13791: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13792: 
1.138     matthew  13793: =item @Values: An array of array references.  Each array reference holds data
                   13794: to be plotted in a stacked bar chart.
                   13795: 
1.239     matthew  13796: =item If the final element of @Values is a hash reference the key/value
                   13797: pairs will be added to the graph definition.
                   13798: 
1.138     matthew  13799: =back
                   13800: 
                   13801: Returns:
                   13802: 
                   13803: An <img> tag which references graph.png and the appropriate identifying
                   13804: information for the plot.
                   13805: 
1.127     matthew  13806: =cut
                   13807: 
                   13808: ############################################################
                   13809: ############################################################
1.134     matthew  13810: sub DrawBarGraph {
1.178     matthew  13811:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13812:     #
                   13813:     if (! defined($colors)) {
                   13814:         $colors = ['#33ff00', 
                   13815:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13816:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13817:                   ]; 
                   13818:     }
1.228     matthew  13819:     my $extra_settings = {};
                   13820:     if (ref($Values[-1]) eq 'HASH') {
                   13821:         $extra_settings = pop(@Values);
                   13822:     }
1.127     matthew  13823:     #
1.136     matthew  13824:     my $identifier = &get_cgi_id();
                   13825:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13826:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13827:         return '';
                   13828:     }
1.225     matthew  13829:     #
                   13830:     my @Labels;
                   13831:     if (defined($labels)) {
                   13832:         @Labels = @$labels;
                   13833:     } else {
                   13834:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13835:             push(@Labels,$i+1);
1.225     matthew  13836:         }
                   13837:     }
                   13838:     #
1.129     matthew  13839:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13840:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13841:     my %ValuesHash;
                   13842:     my $NumSets=1;
                   13843:     foreach my $array (@Values) {
                   13844:         next if (! ref($array));
1.136     matthew  13845:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13846:             join(',',@$array);
1.129     matthew  13847:     }
1.127     matthew  13848:     #
1.136     matthew  13849:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13850:     if ($NumBars < 3) {
                   13851:         $width = 120+$NumBars*32;
1.220     matthew  13852:         $xskip = 1;
1.225     matthew  13853:         $bar_width = 30;
                   13854:     } elsif ($NumBars < 5) {
                   13855:         $width = 120+$NumBars*20;
                   13856:         $xskip = 1;
                   13857:         $bar_width = 20;
1.220     matthew  13858:     } elsif ($NumBars < 10) {
1.136     matthew  13859:         $width = 120+$NumBars*15;
                   13860:         $xskip = 1;
                   13861:         $bar_width = 15;
                   13862:     } elsif ($NumBars <= 25) {
                   13863:         $width = 120+$NumBars*11;
                   13864:         $xskip = 5;
                   13865:         $bar_width = 8;
                   13866:     } elsif ($NumBars <= 50) {
                   13867:         $width = 120+$NumBars*8;
                   13868:         $xskip = 5;
                   13869:         $bar_width = 4;
                   13870:     } else {
                   13871:         $width = 120+$NumBars*8;
                   13872:         $xskip = 5;
                   13873:         $bar_width = 4;
                   13874:     }
                   13875:     #
1.137     matthew  13876:     $Max = 1 if ($Max < 1);
                   13877:     if ( int($Max) < $Max ) {
                   13878:         $Max++;
                   13879:         $Max = int($Max);
                   13880:     }
1.127     matthew  13881:     $Title  = '' if (! defined($Title));
                   13882:     $xlabel = '' if (! defined($xlabel));
                   13883:     $ylabel = '' if (! defined($ylabel));
1.369     www      13884:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13885:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13886:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13887:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13888:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13889:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13890:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13891:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13892:     $ValuesHash{$id.'.height'}   = $height;
                   13893:     $ValuesHash{$id.'.width'}    = $width;
                   13894:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13895:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13896:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13897:     #
1.228     matthew  13898:     # Deal with other parameters
                   13899:     while (my ($key,$value) = each(%$extra_settings)) {
                   13900:         $ValuesHash{$id.'.'.$key} = $value;
                   13901:     }
                   13902:     #
1.646     raeburn  13903:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13904:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13905: }
                   13906: 
                   13907: ############################################################
                   13908: ############################################################
                   13909: 
                   13910: =pod
                   13911: 
1.648     raeburn  13912: =item * &DrawXYGraph()
1.137     matthew  13913: 
1.138     matthew  13914: Facilitates the plotting of data in an XY graph.
                   13915: Puts plot definition data into the users environment in order for 
                   13916: graph.png to plot it.  Returns an <img> tag for the plot.
                   13917: 
                   13918: Inputs:
                   13919: 
                   13920: =over 4
                   13921: 
                   13922: =item $Title: string, the title of the plot
                   13923: 
                   13924: =item $xlabel: string, text describing the X-axis of the plot
                   13925: 
                   13926: =item $ylabel: string, text describing the Y-axis of the plot
                   13927: 
                   13928: =item $Max: scalar, the maximum Y value to use in the plot
                   13929: If $Max is < any data point, the graph will not be rendered.
                   13930: 
                   13931: =item $colors: Array ref containing the hex color codes for the data to be 
                   13932: plotted in.  If undefined, default values will be used.
                   13933: 
                   13934: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13935: 
                   13936: =item $Ydata: Array ref containing Array refs.  
1.185     www      13937: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13938: 
                   13939: =item %Values: hash indicating or overriding any default values which are 
                   13940: passed to graph.png.  
                   13941: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13942: 
                   13943: =back
                   13944: 
                   13945: Returns:
                   13946: 
                   13947: An <img> tag which references graph.png and the appropriate identifying
                   13948: information for the plot.
                   13949: 
1.137     matthew  13950: =cut
                   13951: 
                   13952: ############################################################
                   13953: ############################################################
                   13954: sub DrawXYGraph {
                   13955:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13956:     #
                   13957:     # Create the identifier for the graph
                   13958:     my $identifier = &get_cgi_id();
                   13959:     my $id = 'cgi.'.$identifier;
                   13960:     #
                   13961:     $Title  = '' if (! defined($Title));
                   13962:     $xlabel = '' if (! defined($xlabel));
                   13963:     $ylabel = '' if (! defined($ylabel));
                   13964:     my %ValuesHash = 
                   13965:         (
1.369     www      13966:          $id.'.title'  => &escape($Title),
                   13967:          $id.'.xlabel' => &escape($xlabel),
                   13968:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13969:          $id.'.y_max_value'=> $Max,
                   13970:          $id.'.labels'     => join(',',@$Xlabels),
                   13971:          $id.'.PlotType'   => 'XY',
                   13972:          );
                   13973:     #
                   13974:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13975:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13976:     }
                   13977:     #
                   13978:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13979:         return '';
                   13980:     }
                   13981:     my $NumSets=1;
1.138     matthew  13982:     foreach my $array (@{$Ydata}){
1.137     matthew  13983:         next if (! ref($array));
                   13984:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13985:     }
1.138     matthew  13986:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13987:     #
                   13988:     # Deal with other parameters
                   13989:     while (my ($key,$value) = each(%Values)) {
                   13990:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13991:     }
                   13992:     #
1.646     raeburn  13993:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13994:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13995: }
                   13996: 
                   13997: ############################################################
                   13998: ############################################################
                   13999: 
                   14000: =pod
                   14001: 
1.648     raeburn  14002: =item * &DrawXYYGraph()
1.138     matthew  14003: 
                   14004: Facilitates the plotting of data in an XY graph with two Y axes.
                   14005: Puts plot definition data into the users environment in order for 
                   14006: graph.png to plot it.  Returns an <img> tag for the plot.
                   14007: 
                   14008: Inputs:
                   14009: 
                   14010: =over 4
                   14011: 
                   14012: =item $Title: string, the title of the plot
                   14013: 
                   14014: =item $xlabel: string, text describing the X-axis of the plot
                   14015: 
                   14016: =item $ylabel: string, text describing the Y-axis of the plot
                   14017: 
                   14018: =item $colors: Array ref containing the hex color codes for the data to be 
                   14019: plotted in.  If undefined, default values will be used.
                   14020: 
                   14021: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14022: 
                   14023: =item $Ydata1: The first data set
                   14024: 
                   14025: =item $Min1: The minimum value of the left Y-axis
                   14026: 
                   14027: =item $Max1: The maximum value of the left Y-axis
                   14028: 
                   14029: =item $Ydata2: The second data set
                   14030: 
                   14031: =item $Min2: The minimum value of the right Y-axis
                   14032: 
                   14033: =item $Max2: The maximum value of the left Y-axis
                   14034: 
                   14035: =item %Values: hash indicating or overriding any default values which are 
                   14036: passed to graph.png.  
                   14037: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14038: 
                   14039: =back
                   14040: 
                   14041: Returns:
                   14042: 
                   14043: An <img> tag which references graph.png and the appropriate identifying
                   14044: information for the plot.
1.136     matthew  14045: 
                   14046: =cut
                   14047: 
                   14048: ############################################################
                   14049: ############################################################
1.137     matthew  14050: sub DrawXYYGraph {
                   14051:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14052:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14053:     #
                   14054:     # Create the identifier for the graph
                   14055:     my $identifier = &get_cgi_id();
                   14056:     my $id = 'cgi.'.$identifier;
                   14057:     #
                   14058:     $Title  = '' if (! defined($Title));
                   14059:     $xlabel = '' if (! defined($xlabel));
                   14060:     $ylabel = '' if (! defined($ylabel));
                   14061:     my %ValuesHash = 
                   14062:         (
1.369     www      14063:          $id.'.title'  => &escape($Title),
                   14064:          $id.'.xlabel' => &escape($xlabel),
                   14065:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14066:          $id.'.labels' => join(',',@$Xlabels),
                   14067:          $id.'.PlotType' => 'XY',
                   14068:          $id.'.NumSets' => 2,
1.137     matthew  14069:          $id.'.two_axes' => 1,
                   14070:          $id.'.y1_max_value' => $Max1,
                   14071:          $id.'.y1_min_value' => $Min1,
                   14072:          $id.'.y2_max_value' => $Max2,
                   14073:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14074:          );
                   14075:     #
1.137     matthew  14076:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14077:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14078:     }
                   14079:     #
                   14080:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14081:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14082:         return '';
                   14083:     }
                   14084:     my $NumSets=1;
1.137     matthew  14085:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14086:         next if (! ref($array));
                   14087:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14088:     }
                   14089:     #
                   14090:     # Deal with other parameters
                   14091:     while (my ($key,$value) = each(%Values)) {
                   14092:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14093:     }
                   14094:     #
1.646     raeburn  14095:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14096:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14097: }
                   14098: 
                   14099: ############################################################
                   14100: ############################################################
                   14101: 
                   14102: =pod
                   14103: 
1.157     matthew  14104: =back 
                   14105: 
1.139     matthew  14106: =head1 Statistics helper routines?  
                   14107: 
                   14108: Bad place for them but what the hell.
                   14109: 
1.157     matthew  14110: =over 4
                   14111: 
1.648     raeburn  14112: =item * &chartlink()
1.139     matthew  14113: 
                   14114: Returns a link to the chart for a specific student.  
                   14115: 
                   14116: Inputs:
                   14117: 
                   14118: =over 4
                   14119: 
                   14120: =item $linktext: The text of the link
                   14121: 
                   14122: =item $sname: The students username
                   14123: 
                   14124: =item $sdomain: The students domain
                   14125: 
                   14126: =back
                   14127: 
1.157     matthew  14128: =back
                   14129: 
1.139     matthew  14130: =cut
                   14131: 
                   14132: ############################################################
                   14133: ############################################################
                   14134: sub chartlink {
                   14135:     my ($linktext, $sname, $sdomain) = @_;
                   14136:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14137:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14138:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14139:        '">'.$linktext.'</a>';
1.153     matthew  14140: }
                   14141: 
                   14142: #######################################################
                   14143: #######################################################
                   14144: 
                   14145: =pod
                   14146: 
                   14147: =head1 Course Environment Routines
1.157     matthew  14148: 
                   14149: =over 4
1.153     matthew  14150: 
1.648     raeburn  14151: =item * &restore_course_settings()
1.153     matthew  14152: 
1.648     raeburn  14153: =item * &store_course_settings()
1.153     matthew  14154: 
                   14155: Restores/Store indicated form parameters from the course environment.
                   14156: Will not overwrite existing values of the form parameters.
                   14157: 
                   14158: Inputs: 
                   14159: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14160: 
                   14161: a hash ref describing the data to be stored.  For example:
                   14162:    
                   14163: %Save_Parameters = ('Status' => 'scalar',
                   14164:     'chartoutputmode' => 'scalar',
                   14165:     'chartoutputdata' => 'scalar',
                   14166:     'Section' => 'array',
1.373     raeburn  14167:     'Group' => 'array',
1.153     matthew  14168:     'StudentData' => 'array',
                   14169:     'Maps' => 'array');
                   14170: 
                   14171: Returns: both routines return nothing
                   14172: 
1.631     raeburn  14173: =back
                   14174: 
1.153     matthew  14175: =cut
                   14176: 
                   14177: #######################################################
                   14178: #######################################################
                   14179: sub store_course_settings {
1.496     albertel 14180:     return &store_settings($env{'request.course.id'},@_);
                   14181: }
                   14182: 
                   14183: sub store_settings {
1.153     matthew  14184:     # save to the environment
                   14185:     # appenv the same items, just to be safe
1.300     albertel 14186:     my $udom  = $env{'user.domain'};
                   14187:     my $uname = $env{'user.name'};
1.496     albertel 14188:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14189:     my %SaveHash;
                   14190:     my %AppHash;
                   14191:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14192:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14193:         my $envname = 'environment.'.$basename;
1.258     albertel 14194:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14195:             # Save this value away
                   14196:             if ($type eq 'scalar' &&
1.258     albertel 14197:                 (! exists($env{$envname}) || 
                   14198:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14199:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14200:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14201:             } elsif ($type eq 'array') {
                   14202:                 my $stored_form;
1.258     albertel 14203:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14204:                     $stored_form = join(',',
                   14205:                                         map {
1.369     www      14206:                                             &escape($_);
1.258     albertel 14207:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14208:                 } else {
                   14209:                     $stored_form = 
1.369     www      14210:                         &escape($env{'form.'.$setting});
1.153     matthew  14211:                 }
                   14212:                 # Determine if the array contents are the same.
1.258     albertel 14213:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14214:                     $SaveHash{$basename} = $stored_form;
                   14215:                     $AppHash{$envname}   = $stored_form;
                   14216:                 }
                   14217:             }
                   14218:         }
                   14219:     }
                   14220:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14221:                                           $udom,$uname);
1.153     matthew  14222:     if ($put_result !~ /^(ok|delayed)/) {
                   14223:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14224:                                  'got error:'.$put_result);
                   14225:     }
                   14226:     # Make sure these settings stick around in this session, too
1.646     raeburn  14227:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14228:     return;
                   14229: }
                   14230: 
                   14231: sub restore_course_settings {
1.499     albertel 14232:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14233: }
                   14234: 
                   14235: sub restore_settings {
                   14236:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14237:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14238:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14239:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14240:             '.'.$setting;
1.258     albertel 14241:         if (exists($env{$envname})) {
1.153     matthew  14242:             if ($type eq 'scalar') {
1.258     albertel 14243:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14244:             } elsif ($type eq 'array') {
1.258     albertel 14245:                 $env{'form.'.$setting} = [ 
1.153     matthew  14246:                                            map { 
1.369     www      14247:                                                &unescape($_); 
1.258     albertel 14248:                                            } split(',',$env{$envname})
1.153     matthew  14249:                                            ];
                   14250:             }
                   14251:         }
                   14252:     }
1.127     matthew  14253: }
                   14254: 
1.618     raeburn  14255: #######################################################
                   14256: #######################################################
                   14257: 
                   14258: =pod
                   14259: 
                   14260: =head1 Domain E-mail Routines  
                   14261: 
                   14262: =over 4
                   14263: 
1.648     raeburn  14264: =item * &build_recipient_list()
1.618     raeburn  14265: 
1.1075.2.44  raeburn  14266: Build recipient lists for following types of e-mail:
1.766     raeburn  14267: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14268: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14269: module change checking, student/employee ID conflict checks, as
                   14270: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14271: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14272: 
                   14273: Inputs:
1.1075.2.44  raeburn  14274: defmail (scalar - email address of default recipient),
                   14275: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14276: requestsmail, updatesmail, or idconflictsmail).
                   14277: 
1.619     raeburn  14278: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14279: 
                   14280: origmail (scalar - email address of recipient from loncapa.conf,
                   14281: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14282: 
1.1075.2.139  raeburn  14283: $requname username of requester (if mailing type is helpdeskmail)
                   14284: 
                   14285: $requdom domain of requester (if mailing type is helpdeskmail)
                   14286: 
                   14287: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14288: 
1.655     raeburn  14289: Returns: comma separated list of addresses to which to send e-mail.
                   14290: 
                   14291: =back
1.618     raeburn  14292: 
                   14293: =cut
                   14294: 
                   14295: ############################################################
                   14296: ############################################################
                   14297: sub build_recipient_list {
1.1075.2.139  raeburn  14298:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14299:     my @recipients;
1.1075.2.122  raeburn  14300:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14301:     my %domconfig =
1.1075.2.122  raeburn  14302:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14303:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14304:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14305:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14306:                 my @contacts = ('adminemail','supportemail');
                   14307:                 foreach my $item (@contacts) {
                   14308:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14309:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14310:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14311:                             push(@recipients,$addr);
                   14312:                         }
1.619     raeburn  14313:                     }
1.1075.2.122  raeburn  14314:                 }
                   14315:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14316:                 if ($mailing eq 'helpdeskmail') {
                   14317:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14318:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14319:                         my @ok_bccs;
                   14320:                         foreach my $bcc (@bccs) {
                   14321:                             $bcc =~ s/^\s+//g;
                   14322:                             $bcc =~ s/\s+$//g;
                   14323:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14324:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14325:                                     push(@ok_bccs,$bcc);
                   14326:                                 }
                   14327:                             }
                   14328:                         }
                   14329:                         if (@ok_bccs > 0) {
                   14330:                             $allbcc = join(', ',@ok_bccs);
                   14331:                         }
                   14332:                     }
                   14333:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14334:                 }
                   14335:             }
1.766     raeburn  14336:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14337:             $lastresort = $origmail;
1.618     raeburn  14338:         }
1.1075.2.139  raeburn  14339:         if ($mailing eq 'helpdeskmail') {
                   14340:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14341:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14342:                 my ($inststatus,$inststatus_checked);
                   14343:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14344:                     ($env{'user.domain'} ne 'public')) {
                   14345:                     $inststatus_checked = 1;
                   14346:                     $inststatus = $env{'environment.inststatus'};
                   14347:                 }
                   14348:                 unless ($inststatus_checked) {
                   14349:                     if (($requname ne '') && ($requdom ne '')) {
                   14350:                         if (($requname =~ /^$match_username$/) &&
                   14351:                             ($requdom =~ /^$match_domain$/) &&
                   14352:                             (&Apache::lonnet::domain($requdom))) {
                   14353:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14354:                                                                       $requdom);
                   14355:                             unless ($requhome eq 'no_host') {
                   14356:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14357:                                 $inststatus = $userenv{'inststatus'};
                   14358:                                 $inststatus_checked = 1;
                   14359:                             }
                   14360:                         }
                   14361:                     }
                   14362:                 }
                   14363:                 unless ($inststatus_checked) {
                   14364:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14365:                         my %srch = (srchby     => 'email',
                   14366:                                     srchdomain => $defdom,
                   14367:                                     srchterm   => $reqemail,
                   14368:                                     srchtype   => 'exact');
                   14369:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14370:                         foreach my $uname (keys(%srch_results)) {
                   14371:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14372:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14373:                                 $inststatus_checked = 1;
                   14374:                                 last;
                   14375:                             }
                   14376:                         }
                   14377:                         unless ($inststatus_checked) {
                   14378:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14379:                             if ($dirsrchres eq 'ok') {
                   14380:                                 foreach my $uname (keys(%srch_results)) {
                   14381:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14382:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14383:                                         $inststatus_checked = 1;
                   14384:                                         last;
                   14385:                                     }
                   14386:                                 }
                   14387:                             }
                   14388:                         }
                   14389:                     }
                   14390:                 }
                   14391:                 if ($inststatus ne '') {
                   14392:                     foreach my $status (split(/\:/,$inststatus)) {
                   14393:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14394:                             my @contacts = ('adminemail','supportemail');
                   14395:                             foreach my $item (@contacts) {
                   14396:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14397:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14398:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14399:                                         push(@recipients,$addr);
                   14400:                                     }
                   14401:                                 }
                   14402:                             }
                   14403:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14404:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14405:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14406:                                 my @ok_bccs;
                   14407:                                 foreach my $bcc (@bccs) {
                   14408:                                     $bcc =~ s/^\s+//g;
                   14409:                                     $bcc =~ s/\s+$//g;
                   14410:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14411:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14412:                                             push(@ok_bccs,$bcc);
                   14413:                                         }
                   14414:                                     }
                   14415:                                 }
                   14416:                                 if (@ok_bccs > 0) {
                   14417:                                     $allbcc = join(', ',@ok_bccs);
                   14418:                                 }
                   14419:                             }
                   14420:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14421:                             last;
                   14422:                         }
                   14423:                     }
                   14424:                 }
                   14425:             }
                   14426:         }
1.619     raeburn  14427:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14428:         $lastresort = $origmail;
                   14429:     }
1.1075.2.128  raeburn  14430:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14431:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14432:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14433:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14434:             my %what = (
                   14435:                           perlvar => 1,
                   14436:                        );
                   14437:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14438:             if ($primary) {
                   14439:                 my $gotaddr;
                   14440:                 my ($result,$returnhash) =
                   14441:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14442:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14443:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14444:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14445:                         $gotaddr = 1;
                   14446:                     }
                   14447:                 }
                   14448:                 unless ($gotaddr) {
                   14449:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14450:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14451:                     unless ($uintdom eq $intdom) {
                   14452:                         my %domconfig =
                   14453:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14454:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14455:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14456:                                 my @contacts = ('adminemail','supportemail');
                   14457:                                 foreach my $item (@contacts) {
                   14458:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14459:                                         my $addr = $domconfig{'contacts'}{$item};
                   14460:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14461:                                             push(@recipients,$addr);
                   14462:                                         }
                   14463:                                     }
                   14464:                                 }
                   14465:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14466:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14467:                                 }
                   14468:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14469:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14470:                                     my @ok_bccs;
                   14471:                                     foreach my $bcc (@bccs) {
                   14472:                                         $bcc =~ s/^\s+//g;
                   14473:                                         $bcc =~ s/\s+$//g;
                   14474:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14475:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14476:                                                 push(@ok_bccs,$bcc);
                   14477:                                             }
                   14478:                                         }
                   14479:                                     }
                   14480:                                     if (@ok_bccs > 0) {
                   14481:                                         $allbcc = join(', ',@ok_bccs);
                   14482:                                     }
                   14483:                                 }
                   14484:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14485:                             }
                   14486:                         }
                   14487:                     }
                   14488:                 }
                   14489:             }
                   14490:         }
1.618     raeburn  14491:     }
1.688     raeburn  14492:     if (defined($defmail)) {
                   14493:         if ($defmail ne '') {
                   14494:             push(@recipients,$defmail);
                   14495:         }
1.618     raeburn  14496:     }
                   14497:     if ($otheremails) {
1.619     raeburn  14498:         my @others;
                   14499:         if ($otheremails =~ /,/) {
                   14500:             @others = split(/,/,$otheremails);
1.618     raeburn  14501:         } else {
1.619     raeburn  14502:             push(@others,$otheremails);
                   14503:         }
                   14504:         foreach my $addr (@others) {
                   14505:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14506:                 push(@recipients,$addr);
                   14507:             }
1.618     raeburn  14508:         }
                   14509:     }
1.1075.2.128  raeburn  14510:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14511:         if ((!@recipients) && ($lastresort ne '')) {
                   14512:             push(@recipients,$lastresort);
                   14513:         }
                   14514:     } elsif ($lastresort ne '') {
                   14515:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14516:             push(@recipients,$lastresort);
                   14517:         }
                   14518:     }
                   14519:     my $recipientlist = join(',',@recipients);
                   14520:     if (wantarray) {
                   14521:         return ($recipientlist,$allbcc,$addtext);
                   14522:     } else {
                   14523:         return $recipientlist;
                   14524:     }
1.618     raeburn  14525: }
                   14526: 
1.127     matthew  14527: ############################################################
                   14528: ############################################################
1.154     albertel 14529: 
1.655     raeburn  14530: =pod
                   14531: 
                   14532: =head1 Course Catalog Routines
                   14533: 
                   14534: =over 4
                   14535: 
                   14536: =item * &gather_categories()
                   14537: 
                   14538: Converts category definitions - keys of categories hash stored in  
                   14539: coursecategories in configuration.db on the primary library server in a 
                   14540: domain - to an array.  Also generates javascript and idx hash used to 
                   14541: generate Domain Coordinator interface for editing Course Categories.
                   14542: 
                   14543: Inputs:
1.663     raeburn  14544: 
1.655     raeburn  14545: categories (reference to hash of category definitions).
1.663     raeburn  14546: 
1.655     raeburn  14547: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14548:       categories and subcategories).
1.663     raeburn  14549: 
1.655     raeburn  14550: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14551:       editing Course Categories).
1.663     raeburn  14552: 
1.655     raeburn  14553: jsarray (reference to array of categories used to create Javascript arrays for
                   14554:          Domain Coordinator interface for editing Course Categories).
                   14555: 
                   14556: Returns: nothing
                   14557: 
                   14558: Side effects: populates cats, idx and jsarray. 
                   14559: 
                   14560: =cut
                   14561: 
                   14562: sub gather_categories {
                   14563:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14564:     my %counters;
                   14565:     my $num = 0;
                   14566:     foreach my $item (keys(%{$categories})) {
                   14567:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14568:         if ($container eq '' && $depth == 0) {
                   14569:             $cats->[$depth][$categories->{$item}] = $cat;
                   14570:         } else {
                   14571:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14572:         }
                   14573:         my ($escitem,$tail) = split(/:/,$item,2);
                   14574:         if ($counters{$tail} eq '') {
                   14575:             $counters{$tail} = $num;
                   14576:             $num ++;
                   14577:         }
                   14578:         if (ref($idx) eq 'HASH') {
                   14579:             $idx->{$item} = $counters{$tail};
                   14580:         }
                   14581:         if (ref($jsarray) eq 'ARRAY') {
                   14582:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14583:         }
                   14584:     }
                   14585:     return;
                   14586: }
                   14587: 
                   14588: =pod
                   14589: 
                   14590: =item * &extract_categories()
                   14591: 
                   14592: Used to generate breadcrumb trails for course categories.
                   14593: 
                   14594: Inputs:
1.663     raeburn  14595: 
1.655     raeburn  14596: categories (reference to hash of category definitions).
1.663     raeburn  14597: 
1.655     raeburn  14598: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14599:       categories and subcategories).
1.663     raeburn  14600: 
1.655     raeburn  14601: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14602: 
1.655     raeburn  14603: allitems (reference to hash - key is category key 
                   14604:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14605: 
1.655     raeburn  14606: idx (reference to hash of counters used in Domain Coordinator interface for
                   14607:       editing Course Categories).
1.663     raeburn  14608: 
1.655     raeburn  14609: jsarray (reference to array of categories used to create Javascript arrays for
                   14610:          Domain Coordinator interface for editing Course Categories).
                   14611: 
1.665     raeburn  14612: subcats (reference to hash of arrays containing all subcategories within each 
                   14613:          category, -recursive)
                   14614: 
1.1075.2.132  raeburn  14615: maxd (reference to hash used to hold max depth for all top-level categories).
                   14616: 
1.655     raeburn  14617: Returns: nothing
                   14618: 
                   14619: Side effects: populates trails and allitems hash references.
                   14620: 
                   14621: =cut
                   14622: 
                   14623: sub extract_categories {
1.1075.2.132  raeburn  14624:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14625:     if (ref($categories) eq 'HASH') {
                   14626:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14627:         if (ref($cats->[0]) eq 'ARRAY') {
                   14628:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14629:                 my $name = $cats->[0][$i];
                   14630:                 my $item = &escape($name).'::0';
                   14631:                 my $trailstr;
                   14632:                 if ($name eq 'instcode') {
                   14633:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14634:                 } elsif ($name eq 'communities') {
                   14635:                     $trailstr = &mt('Communities');
1.655     raeburn  14636:                 } else {
                   14637:                     $trailstr = $name;
                   14638:                 }
                   14639:                 if ($allitems->{$item} eq '') {
                   14640:                     push(@{$trails},$trailstr);
                   14641:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14642:                 }
                   14643:                 my @parents = ($name);
                   14644:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14645:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14646:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14647:                         if (ref($subcats) eq 'HASH') {
                   14648:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14649:                         }
1.1075.2.132  raeburn  14650:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14651:                     }
                   14652:                 } else {
                   14653:                     if (ref($subcats) eq 'HASH') {
                   14654:                         $subcats->{$item} = [];
1.655     raeburn  14655:                     }
1.1075.2.132  raeburn  14656:                     if (ref($maxd) eq 'HASH') {
                   14657:                         $maxd->{$name} = 1;
                   14658:                     }
1.655     raeburn  14659:                 }
                   14660:             }
                   14661:         }
                   14662:     }
                   14663:     return;
                   14664: }
                   14665: 
                   14666: =pod
                   14667: 
1.1075.2.56  raeburn  14668: =item * &recurse_categories()
1.655     raeburn  14669: 
                   14670: Recursively used to generate breadcrumb trails for course categories.
                   14671: 
                   14672: Inputs:
1.663     raeburn  14673: 
1.655     raeburn  14674: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14675:       categories and subcategories).
1.663     raeburn  14676: 
1.655     raeburn  14677: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14678: 
                   14679: category (current course category, for which breadcrumb trail is being generated).
                   14680: 
                   14681: trails (reference to array of breadcrumb trails for each category).
                   14682: 
1.655     raeburn  14683: allitems (reference to hash - key is category key
                   14684:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14685: 
1.655     raeburn  14686: parents (array containing containers directories for current category, 
                   14687:          back to top level). 
                   14688: 
                   14689: Returns: nothing
                   14690: 
                   14691: Side effects: populates trails and allitems hash references
                   14692: 
                   14693: =cut
                   14694: 
                   14695: sub recurse_categories {
1.1075.2.132  raeburn  14696:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14697:     my $shallower = $depth - 1;
                   14698:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14699:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14700:             my $name = $cats->[$depth]{$category}[$k];
                   14701:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14702:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14703:             if ($allitems->{$item} eq '') {
                   14704:                 push(@{$trails},$trailstr);
                   14705:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14706:             }
                   14707:             my $deeper = $depth+1;
                   14708:             push(@{$parents},$category);
1.665     raeburn  14709:             if (ref($subcats) eq 'HASH') {
                   14710:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14711:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14712:                     my $higher;
                   14713:                     if ($j > 0) {
                   14714:                         $higher = &escape($parents->[$j]).':'.
                   14715:                                   &escape($parents->[$j-1]).':'.$j;
                   14716:                     } else {
                   14717:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14718:                     }
                   14719:                     push(@{$subcats->{$higher}},$subcat);
                   14720:                 }
                   14721:             }
                   14722:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14723:                                 $subcats,$maxd);
1.655     raeburn  14724:             pop(@{$parents});
                   14725:         }
                   14726:     } else {
                   14727:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14728:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14729:         if ($allitems->{$item} eq '') {
                   14730:             push(@{$trails},$trailstr);
                   14731:             $allitems->{$item} = scalar(@{$trails})-1;
                   14732:         }
1.1075.2.132  raeburn  14733:         if (ref($maxd) eq 'HASH') {
                   14734:             if ($depth > $maxd->{$parents->[0]}) {
                   14735:                 $maxd->{$parents->[0]} = $depth;
                   14736:             }
                   14737:         }
1.655     raeburn  14738:     }
                   14739:     return;
                   14740: }
                   14741: 
1.663     raeburn  14742: =pod
                   14743: 
1.1075.2.56  raeburn  14744: =item * &assign_categories_table()
1.663     raeburn  14745: 
                   14746: Create a datatable for display of hierarchical categories in a domain,
                   14747: with checkboxes to allow a course to be categorized. 
                   14748: 
                   14749: Inputs:
                   14750: 
                   14751: cathash - reference to hash of categories defined for the domain (from
                   14752:           configuration.db)
                   14753: 
                   14754: currcat - scalar with an & separated list of categories assigned to a course. 
                   14755: 
1.919     raeburn  14756: type    - scalar contains course type (Course or Community).
                   14757: 
1.1075.2.117  raeburn  14758: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14759:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14760: 
1.663     raeburn  14761: Returns: $output (markup to be displayed) 
                   14762: 
                   14763: =cut
                   14764: 
                   14765: sub assign_categories_table {
1.1075.2.117  raeburn  14766:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14767:     my $output;
                   14768:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14769:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14770:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14771:         $maxdepth = scalar(@cats);
                   14772:         if (@cats > 0) {
                   14773:             my $itemcount = 0;
                   14774:             if (ref($cats[0]) eq 'ARRAY') {
                   14775:                 my @currcategories;
                   14776:                 if ($currcat ne '') {
                   14777:                     @currcategories = split('&',$currcat);
                   14778:                 }
1.919     raeburn  14779:                 my $table;
1.663     raeburn  14780:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14781:                     my $parent = $cats[0][$i];
1.919     raeburn  14782:                     next if ($parent eq 'instcode');
                   14783:                     if ($type eq 'Community') {
                   14784:                         next unless ($parent eq 'communities');
                   14785:                     } else {
                   14786:                         next if ($parent eq 'communities');
                   14787:                     }
1.663     raeburn  14788:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14789:                     my $item = &escape($parent).'::0';
                   14790:                     my $checked = '';
                   14791:                     if (@currcategories > 0) {
                   14792:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14793:                             $checked = ' checked="checked"';
1.663     raeburn  14794:                         }
                   14795:                     }
1.919     raeburn  14796:                     my $parent_title = $parent;
                   14797:                     if ($parent eq 'communities') {
                   14798:                         $parent_title = &mt('Communities');
                   14799:                     }
                   14800:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14801:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14802:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14803:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14804:                     my $depth = 1;
                   14805:                     push(@path,$parent);
1.1075.2.117  raeburn  14806:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14807:                     pop(@path);
1.919     raeburn  14808:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14809:                     $itemcount ++;
                   14810:                 }
1.919     raeburn  14811:                 if ($itemcount) {
                   14812:                     $output = &Apache::loncommon::start_data_table().
                   14813:                               $table.
                   14814:                               &Apache::loncommon::end_data_table();
                   14815:                 }
1.663     raeburn  14816:             }
                   14817:         }
                   14818:     }
                   14819:     return $output;
                   14820: }
                   14821: 
                   14822: =pod
                   14823: 
1.1075.2.56  raeburn  14824: =item * &assign_category_rows()
1.663     raeburn  14825: 
                   14826: Create a datatable row for display of nested categories in a domain,
                   14827: with checkboxes to allow a course to be categorized,called recursively.
                   14828: 
                   14829: Inputs:
                   14830: 
                   14831: itemcount - track row number for alternating colors
                   14832: 
                   14833: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14834:       categories and subcategories.
                   14835: 
                   14836: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14837: 
                   14838: parent - parent of current category item
                   14839: 
                   14840: path - Array containing all categories back up through the hierarchy from the
                   14841:        current category to the top level.
                   14842: 
                   14843: currcategories - reference to array of current categories assigned to the course
                   14844: 
1.1075.2.117  raeburn  14845: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14846:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14847: 
1.663     raeburn  14848: Returns: $output (markup to be displayed).
                   14849: 
                   14850: =cut
                   14851: 
                   14852: sub assign_category_rows {
1.1075.2.117  raeburn  14853:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14854:     my ($text,$name,$item,$chgstr);
                   14855:     if (ref($cats) eq 'ARRAY') {
                   14856:         my $maxdepth = scalar(@{$cats});
                   14857:         if (ref($cats->[$depth]) eq 'HASH') {
                   14858:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14859:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14860:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14861:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14862:                 for (my $j=0; $j<$numchildren; $j++) {
                   14863:                     $name = $cats->[$depth]{$parent}[$j];
                   14864:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14865:                     my $deeper = $depth+1;
                   14866:                     my $checked = '';
                   14867:                     if (ref($currcategories) eq 'ARRAY') {
                   14868:                         if (@{$currcategories} > 0) {
                   14869:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14870:                                 $checked = ' checked="checked"';
1.663     raeburn  14871:                             }
                   14872:                         }
                   14873:                     }
1.664     raeburn  14874:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14875:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14876:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14877:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14878:                              '</td><td>';
1.663     raeburn  14879:                     if (ref($path) eq 'ARRAY') {
                   14880:                         push(@{$path},$name);
1.1075.2.117  raeburn  14881:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14882:                         pop(@{$path});
                   14883:                     }
                   14884:                     $text .= '</td></tr>';
                   14885:                 }
                   14886:                 $text .= '</table></td>';
                   14887:             }
                   14888:         }
                   14889:     }
                   14890:     return $text;
                   14891: }
                   14892: 
1.1075.2.69  raeburn  14893: =pod
                   14894: 
                   14895: =back
                   14896: 
                   14897: =cut
                   14898: 
1.655     raeburn  14899: ############################################################
                   14900: ############################################################
                   14901: 
                   14902: 
1.443     albertel 14903: sub commit_customrole {
1.664     raeburn  14904:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14905:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14906:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14907:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14908:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14909:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14910:                  '</b><br />';
                   14911:     return $output;
                   14912: }
                   14913: 
                   14914: sub commit_standardrole {
1.1075.2.31  raeburn  14915:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14916:     my ($output,$logmsg,$linefeed);
                   14917:     if ($context eq 'auto') {
                   14918:         $linefeed = "\n";
                   14919:     } else {
                   14920:         $linefeed = "<br />\n";
                   14921:     }  
1.443     albertel 14922:     if ($three eq 'st') {
1.541     raeburn  14923:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14924:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14925:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14926:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14927:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14928:         } else {
1.541     raeburn  14929:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14930:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14931:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14932:             if ($context eq 'auto') {
                   14933:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14934:             } else {
                   14935:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14936:                &mt('Add to classlist').': <b>ok</b>';
                   14937:             }
                   14938:             $output .= $linefeed;
1.443     albertel 14939:         }
                   14940:     } else {
                   14941:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14942:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14943:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14944:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14945:         if ($context eq 'auto') {
                   14946:             $output .= $result.$linefeed;
                   14947:         } else {
                   14948:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14949:         }
1.443     albertel 14950:     }
                   14951:     return $output;
                   14952: }
                   14953: 
                   14954: sub commit_studentrole {
1.1075.2.31  raeburn  14955:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14956:         $credits) = @_;
1.626     raeburn  14957:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14958:     if ($context eq 'auto') {
                   14959:         $linefeed = "\n";
                   14960:     } else {
                   14961:         $linefeed = '<br />'."\n";
                   14962:     }
1.443     albertel 14963:     if (defined($one) && defined($two)) {
                   14964:         my $cid=$one.'_'.$two;
                   14965:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14966:         my $secchange = 0;
                   14967:         my $expire_role_result;
                   14968:         my $modify_section_result;
1.628     raeburn  14969:         if ($oldsec ne '-1') { 
                   14970:             if ($oldsec ne $sec) {
1.443     albertel 14971:                 $secchange = 1;
1.628     raeburn  14972:                 my $now = time;
1.443     albertel 14973:                 my $uurl='/'.$cid;
                   14974:                 $uurl=~s/\_/\//g;
                   14975:                 if ($oldsec) {
                   14976:                     $uurl.='/'.$oldsec;
                   14977:                 }
1.626     raeburn  14978:                 $oldsecurl = $uurl;
1.628     raeburn  14979:                 $expire_role_result = 
1.652     raeburn  14980:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14981:                 if ($env{'request.course.sec'} ne '') { 
                   14982:                     if ($expire_role_result eq 'refused') {
                   14983:                         my @roles = ('st');
                   14984:                         my @statuses = ('previous');
                   14985:                         my @roledoms = ($one);
                   14986:                         my $withsec = 1;
                   14987:                         my %roleshash = 
                   14988:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14989:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14990:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14991:                             my ($oldstart,$oldend) = 
                   14992:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14993:                             if ($oldend > 0 && $oldend <= $now) {
                   14994:                                 $expire_role_result = 'ok';
                   14995:                             }
                   14996:                         }
                   14997:                     }
                   14998:                 }
1.443     albertel 14999:                 $result = $expire_role_result;
                   15000:             }
                   15001:         }
                   15002:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15003:             $modify_section_result = 
                   15004:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15005:                                                            undef,undef,undef,$sec,
                   15006:                                                            $end,$start,'','',$cid,
                   15007:                                                            '',$context,$credits);
1.443     albertel 15008:             if ($modify_section_result =~ /^ok/) {
                   15009:                 if ($secchange == 1) {
1.628     raeburn  15010:                     if ($sec eq '') {
                   15011:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15012:                     } else {
                   15013:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15014:                     }
1.443     albertel 15015:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15016:                     if ($sec eq '') {
                   15017:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15018:                     } else {
                   15019:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15020:                     }
1.443     albertel 15021:                 } else {
1.628     raeburn  15022:                     if ($sec eq '') {
                   15023:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15024:                     } else {
                   15025:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15026:                     }
1.443     albertel 15027:                 }
                   15028:             } else {
1.628     raeburn  15029:                 if ($secchange) {       
                   15030:                     $$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;
                   15031:                 } else {
                   15032:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15033:                 }
1.443     albertel 15034:             }
                   15035:             $result = $modify_section_result;
                   15036:         } elsif ($secchange == 1) {
1.628     raeburn  15037:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15038:                 $$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  15039:             } else {
                   15040:                 $$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;
                   15041:             }
1.626     raeburn  15042:             if ($expire_role_result eq 'refused') {
                   15043:                 my $newsecurl = '/'.$cid;
                   15044:                 $newsecurl =~ s/\_/\//g;
                   15045:                 if ($sec ne '') {
                   15046:                     $newsecurl.='/'.$sec;
                   15047:                 }
                   15048:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15049:                     if ($sec eq '') {
                   15050:                         $$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;
                   15051:                     } else {
                   15052:                         $$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;
                   15053:                     }
                   15054:                 }
                   15055:             }
1.443     albertel 15056:         }
                   15057:     } else {
1.626     raeburn  15058:         $$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 15059:         $result = "error: incomplete course id\n";
                   15060:     }
                   15061:     return $result;
                   15062: }
                   15063: 
1.1075.2.25  raeburn  15064: sub show_role_extent {
                   15065:     my ($scope,$context,$role) = @_;
                   15066:     $scope =~ s{^/}{};
                   15067:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15068:     push(@courseroles,'co');
                   15069:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15070:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15071:         $scope =~ s{/}{_};
                   15072:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15073:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15074:         my ($audom,$auname) = split(/\//,$scope);
                   15075:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15076:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15077:     } else {
                   15078:         $scope =~ s{/$}{};
                   15079:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15080:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15081:     }
                   15082: }
                   15083: 
1.443     albertel 15084: ############################################################
                   15085: ############################################################
                   15086: 
1.566     albertel 15087: sub check_clone {
1.578     raeburn  15088:     my ($args,$linefeed) = @_;
1.566     albertel 15089:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15090:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15091:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.141.  .5(raebu 15092:20):     my $clonetitle;
                   15093:20):     my @clonemsg;
1.566     albertel 15094:     my $can_clone = 0;
1.944     raeburn  15095:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15096:     if ($lctype ne 'community') {
                   15097:         $lctype = 'course';
                   15098:     }
1.566     albertel 15099:     if ($clonehome eq 'no_host') {
1.944     raeburn  15100:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.141.  .5(raebu 15101:20):             push(@clonemsg,({
                   15102:20):                               mt => 'No new community created.',
                   15103:20):                               args => [],
                   15104:20):                             },
                   15105:20):                             {
                   15106:20):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15107:20):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15108:20):                             }));
1.908     raeburn  15109:         } else {
1.1075.2.141.  .5(raebu 15110:20):             push(@clonemsg,({
                   15111:20):                               mt => 'No new course created.',
                   15112:20):                               args => [],
                   15113:20):                             },
                   15114:20):                             {
                   15115:20):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15116:20):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15117:20):                             }));
                   15118:20):         }
1.566     albertel 15119:     } else {
                   15120: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.141.  .5(raebu 15121:20):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15122:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15123:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.141.  .5(raebu 15124:20):                 push(@clonemsg,({
                   15125:20):                                   mt => 'No new community created.',
                   15126:20):                                   args => [],
                   15127:20):                                 },
                   15128:20):                                 {
                   15129:20):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15130:20):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15131:20):                                 }));
                   15132:20):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15133:             }
                   15134:         }
1.1075.2.119  raeburn  15135: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15136:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15137: 	    $can_clone = 1;
                   15138: 	} else {
1.1075.2.95  raeburn  15139: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15140: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15141:             if ($clonehash{'cloners'} eq '') {
                   15142:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15143:                 if ($domdefs{'canclone'}) {
                   15144:                     unless ($domdefs{'canclone'} eq 'none') {
                   15145:                         if ($domdefs{'canclone'} eq 'domain') {
                   15146:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15147:                                 $can_clone = 1;
                   15148:                             }
                   15149:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15150:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15151:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15152:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15153:                                 $can_clone = 1;
                   15154:                             }
                   15155:                         }
                   15156:                     }
1.908     raeburn  15157:                 }
1.1075.2.95  raeburn  15158:             } else {
                   15159: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15160:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15161:                     $can_clone = 1;
1.1075.2.95  raeburn  15162:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15163:                     $can_clone = 1;
1.1075.2.96  raeburn  15164:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15165:                     $can_clone = 1;
1.1075.2.95  raeburn  15166:                 }
                   15167:                 unless ($can_clone) {
1.1075.2.96  raeburn  15168:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15169:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15170:                         my (%gotdomdefaults,%gotcodedefaults);
                   15171:                         foreach my $cloner (@cloners) {
                   15172:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15173:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15174:                                 my (%codedefaults,@code_order);
                   15175:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15176:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15177:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15178:                                     }
                   15179:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15180:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15181:                                     }
                   15182:                                 } else {
                   15183:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15184:                                                                             \%codedefaults,
                   15185:                                                                             \@code_order);
                   15186:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15187:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15188:                                 }
                   15189:                                 if (@code_order > 0) {
                   15190:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15191:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15192:                                                                                 $args->{'crscode'})) {
                   15193:                                         $can_clone = 1;
                   15194:                                         last;
                   15195:                                     }
                   15196:                                 }
                   15197:                             }
                   15198:                         }
                   15199:                     }
1.1075.2.96  raeburn  15200:                 }
                   15201:             }
                   15202:             unless ($can_clone) {
                   15203:                 my $ccrole = 'cc';
                   15204:                 if ($args->{'crstype'} eq 'Community') {
                   15205:                     $ccrole = 'co';
                   15206:                 }
                   15207:                 my %roleshash =
                   15208:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15209:                                                   $args->{'ccdomain'},
                   15210:                                                   'userroles',['active'],[$ccrole],
                   15211:                                                   [$args->{'clonedomain'}]);
                   15212:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15213:                     $can_clone = 1;
                   15214:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15215:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15216:                     $can_clone = 1;
1.1075.2.95  raeburn  15217:                 }
                   15218:             }
                   15219:             unless ($can_clone) {
                   15220:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.141.  .5(raebu 15221:20):                     push(@clonemsg,({
                   15222:20):                                       mt => 'No new community created.',
                   15223:20):                                       args => [],
                   15224:20):                                     },
                   15225:20):                                     {
                   15226:20):                                       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]).',
                   15227:20):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15228:20):                                     }));
1.1075.2.95  raeburn  15229:                 } else {
1.1075.2.141.  .5(raebu 15230:20):                     push(@clonemsg,({
                   15231:20):                                       mt => 'No new course created.',
                   15232:20):                                       args => [],
                   15233:20):                                     },
                   15234:20):                                     {
                   15235:20):                                       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]).',
                   15236:20):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15237:20):                                     }));
                   15238:20):                 }
1.566     albertel 15239: 	    }
1.578     raeburn  15240:         }
1.566     albertel 15241:     }
1.1075.2.141.  .5(raebu 15242:20):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15243: }
                   15244: 
1.444     albertel 15245: sub construct_course {
1.1075.2.119  raeburn  15246:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.141.  .5(raebu 15247:20):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   15248:20):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  15249:     my $linefeed =  '<br />'."\n";
                   15250:     if ($context eq 'auto') {
                   15251:         $linefeed = "\n";
                   15252:     }
1.566     albertel 15253: 
                   15254: #
                   15255: # Are we cloning?
                   15256: #
1.1075.2.141.  .5(raebu 15257:20):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15258:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.141.  .5(raebu 15259:20): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 15260:         if (!$can_clone) {
1.1075.2.141.  .5(raebu 15261:20): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 15262: 	}
                   15263:     }
                   15264: 
1.444     albertel 15265: #
                   15266: # Open course
                   15267: #
                   15268:     my $crstype = lc($args->{'crstype'});
                   15269:     my %cenv=();
                   15270:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15271:                                              $args->{'cdescr'},
                   15272:                                              $args->{'curl'},
                   15273:                                              $args->{'course_home'},
                   15274:                                              $args->{'nonstandard'},
                   15275:                                              $args->{'crscode'},
                   15276:                                              $args->{'ccuname'}.':'.
                   15277:                                              $args->{'ccdomain'},
1.882     raeburn  15278:                                              $args->{'crstype'},
1.1075.2.141.  .5(raebu 15279:20):                                              $cnum,$context,$category,
                   15280:20):                                              $callercontext);
1.444     albertel 15281: 
                   15282:     # Note: The testing routines depend on this being output; see 
                   15283:     # Utils::Course. This needs to at least be output as a comment
                   15284:     # if anyone ever decides to not show this, and Utils::Course::new
                   15285:     # will need to be suitably modified.
1.1075.2.141.  .5(raebu 15286:20):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15287:20):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15288:20):     } else {
                   15289:20):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15290:20):     }
1.943     raeburn  15291:     if ($$courseid =~ /^error:/) {
1.1075.2.141.  .5(raebu 15292:20):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15293:     }
                   15294: 
1.444     albertel 15295: #
                   15296: # Check if created correctly
                   15297: #
1.479     albertel 15298:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15299:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15300:     if ($crsuhome eq 'no_host') {
1.1075.2.141.  .5(raebu 15301:20):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15302:20):             $outcome .= &mt_user($user_lh,
                   15303:20):                             'Course creation failed, unrecognized course home server.');
                   15304:20):         } else {
                   15305:20):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   15306:20):         }
                   15307:20):         $outcome .= $linefeed;
                   15308:20):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15309:     }
1.541     raeburn  15310:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15311: 
1.444     albertel 15312: #
1.566     albertel 15313: # Do the cloning
                   15314: #   
1.1075.2.141.  .5(raebu 15315:20):     my @clonemsg;
1.566     albertel 15316:     if ($can_clone && $cloneid) {
1.1075.2.141.  .5(raebu 15317:20):         push(@clonemsg,
                   15318:20):                       {
                   15319:20):                           mt => 'Created [_1] by cloning from [_2]',
                   15320:20):                           args => [$crstype,$clonetitle],
                   15321:20):                       });
1.566     albertel 15322: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15323: # Copy all files
1.1075.2.141.  .5(raebu 15324:20):         my @info =
                   15325:20): 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   15326:20):                                                      $args->{'dateshift'},$args->{'crscode'},
                   15327:20):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   15328:20):                                                      $args->{'tinyurls'});
                   15329:20):         if (@info) {
                   15330:20):             push(@clonemsg,@info);
                   15331:20):         }
1.444     albertel 15332: # Restore URL
1.566     albertel 15333: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15334: # Restore title
1.566     albertel 15335: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15336: # Restore creation date, creator and creation context.
                   15337:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15338:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15339:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15340: # Mark as cloned
1.566     albertel 15341: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15342: # Need to clone grading mode
                   15343:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15344:         $cenv{'grading'}=$newenv{'grading'};
                   15345: # Do not clone these environment entries
                   15346:         &Apache::lonnet::del('environment',
                   15347:                   ['default_enrollment_start_date',
                   15348:                    'default_enrollment_end_date',
                   15349:                    'question.email',
                   15350:                    'policy.email',
                   15351:                    'comment.email',
                   15352:                    'pch.users.denied',
1.725     raeburn  15353:                    'plc.users.denied',
                   15354:                    'hidefromcat',
1.1075.2.36  raeburn  15355:                    'checkforpriv',
1.1075.2.59  raeburn  15356:                    'categories',
                   15357:                    'internal.uniquecode'],
1.638     www      15358:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15359:         if ($args->{'textbook'}) {
                   15360:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15361:         }
1.444     albertel 15362:     }
1.566     albertel 15363: 
1.444     albertel 15364: #
                   15365: # Set environment (will override cloned, if existing)
                   15366: #
                   15367:     my @sections = ();
                   15368:     my @xlists = ();
                   15369:     if ($args->{'crstype'}) {
                   15370:         $cenv{'type'}=$args->{'crstype'};
                   15371:     }
                   15372:     if ($args->{'crsid'}) {
                   15373:         $cenv{'courseid'}=$args->{'crsid'};
                   15374:     }
                   15375:     if ($args->{'crscode'}) {
                   15376:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15377:     }
                   15378:     if ($args->{'crsquota'} ne '') {
                   15379:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15380:     } else {
                   15381:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15382:     }
                   15383:     if ($args->{'ccuname'}) {
                   15384:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15385:                                         ':'.$args->{'ccdomain'};
                   15386:     } else {
                   15387:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15388:     }
1.1075.2.31  raeburn  15389:     if ($args->{'defaultcredits'}) {
                   15390:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15391:     }
1.444     albertel 15392:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15393:     if ($args->{'crssections'}) {
                   15394:         $cenv{'internal.sectionnums'} = '';
                   15395:         if ($args->{'crssections'} =~ m/,/) {
                   15396:             @sections = split/,/,$args->{'crssections'};
                   15397:         } else {
                   15398:             $sections[0] = $args->{'crssections'};
                   15399:         }
                   15400:         if (@sections > 0) {
                   15401:             foreach my $item (@sections) {
                   15402:                 my ($sec,$gp) = split/:/,$item;
                   15403:                 my $class = $args->{'crscode'}.$sec;
                   15404:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15405:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15406:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15407:                     push(@badclasses,$class);
1.444     albertel 15408:                 }
                   15409:             }
                   15410:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15411:         }
                   15412:     }
                   15413: # do not hide course coordinator from staff listing, 
                   15414: # even if privileged
                   15415:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15416: # add course coordinator's domain to domains to check for privileged users
                   15417: # if different to course domain
                   15418:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15419:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15420:     }
1.444     albertel 15421: # add crosslistings
                   15422:     if ($args->{'crsxlist'}) {
                   15423:         $cenv{'internal.crosslistings'}='';
                   15424:         if ($args->{'crsxlist'} =~ m/,/) {
                   15425:             @xlists = split/,/,$args->{'crsxlist'};
                   15426:         } else {
                   15427:             $xlists[0] = $args->{'crsxlist'};
                   15428:         }
                   15429:         if (@xlists > 0) {
                   15430:             foreach my $item (@xlists) {
                   15431:                 my ($xl,$gp) = split/:/,$item;
                   15432:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15433:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15434:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15435:                     push(@badclasses,$xl);
1.444     albertel 15436:                 }
                   15437:             }
                   15438:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15439:         }
                   15440:     }
                   15441:     if ($args->{'autoadds'}) {
                   15442:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15443:     }
                   15444:     if ($args->{'autodrops'}) {
                   15445:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15446:     }
                   15447: # check for notification of enrollment changes
                   15448:     my @notified = ();
                   15449:     if ($args->{'notify_owner'}) {
                   15450:         if ($args->{'ccuname'} ne '') {
                   15451:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15452:         }
                   15453:     }
                   15454:     if ($args->{'notify_dc'}) {
                   15455:         if ($uname ne '') { 
1.630     raeburn  15456:             push(@notified,$uname.':'.$udom);
1.444     albertel 15457:         }
                   15458:     }
                   15459:     if (@notified > 0) {
                   15460:         my $notifylist;
                   15461:         if (@notified > 1) {
                   15462:             $notifylist = join(',',@notified);
                   15463:         } else {
                   15464:             $notifylist = $notified[0];
                   15465:         }
                   15466:         $cenv{'internal.notifylist'} = $notifylist;
                   15467:     }
                   15468:     if (@badclasses > 0) {
                   15469:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15470:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15471:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15472:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15473:         );
1.1075.2.119  raeburn  15474:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15475:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15476:         if ($context eq 'auto') {
                   15477:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15478:         } else {
1.566     albertel 15479:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15480:         }
                   15481:         foreach my $item (@badclasses) {
1.541     raeburn  15482:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15483:                 $outcome .= " - $item\n";
1.541     raeburn  15484:             } else {
1.1075.2.119  raeburn  15485:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15486:             }
1.1075.2.119  raeburn  15487:         }
                   15488:         if ($context eq 'auto') {
                   15489:             $outcome .= $linefeed;
                   15490:         } else {
                   15491:             $outcome .= "</ul><br /><br /></div>\n";
                   15492:         }
1.444     albertel 15493:     }
                   15494:     if ($args->{'no_end_date'}) {
                   15495:         $args->{'endaccess'} = 0;
                   15496:     }
                   15497:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15498:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15499:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15500:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15501:     if ($args->{'showphotos'}) {
                   15502:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15503:     }
                   15504:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15505:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15506:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15507:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15508:             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'); 
                   15509:             if ($context eq 'auto') {
                   15510:                 $outcome .= $krb_msg;
                   15511:             } else {
1.566     albertel 15512:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15513:             }
                   15514:             $outcome .= $linefeed;
1.444     albertel 15515:         }
                   15516:     }
                   15517:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15518:        if ($args->{'setpolicy'}) {
                   15519:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15520:        }
                   15521:        if ($args->{'setcontent'}) {
                   15522:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15523:        }
1.1075.2.110  raeburn  15524:        if ($args->{'setcomment'}) {
                   15525:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15526:        }
1.444     albertel 15527:     }
                   15528:     if ($args->{'reshome'}) {
                   15529: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15530: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15531:     }
                   15532: #
                   15533: # course has keyed access
                   15534: #
                   15535:     if ($args->{'setkeys'}) {
                   15536:        $cenv{'keyaccess'}='yes';
                   15537:     }
                   15538: # if specified, key authority is not course, but user
                   15539: # only active if keyaccess is yes
                   15540:     if ($args->{'keyauth'}) {
1.487     albertel 15541: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15542: 	$user = &LONCAPA::clean_username($user);
                   15543: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15544: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15545: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15546: 	}
                   15547:     }
                   15548: 
1.1075.2.59  raeburn  15549: #
                   15550: #  generate and store uniquecode (available to course requester), if course should have one.
                   15551: #
                   15552:     if ($args->{'uniquecode'}) {
                   15553:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15554:         if ($code) {
                   15555:             $cenv{'internal.uniquecode'} = $code;
                   15556:             my %crsinfo =
                   15557:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15558:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15559:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15560:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15561:             }
                   15562:             if (ref($coderef)) {
                   15563:                 $$coderef = $code;
                   15564:             }
                   15565:         }
                   15566:     }
                   15567: 
1.444     albertel 15568:     if ($args->{'disresdis'}) {
                   15569:         $cenv{'pch.roles.denied'}='st';
                   15570:     }
                   15571:     if ($args->{'disablechat'}) {
                   15572:         $cenv{'plc.roles.denied'}='st';
                   15573:     }
                   15574: 
                   15575:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15576:     # course
                   15577:     $cenv{'course.helper.not.run'} = 1;
                   15578:     #
                   15579:     # Use new Randomseed
                   15580:     #
                   15581:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15582:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15583:     #
                   15584:     # The encryption code and receipt prefix for this course
                   15585:     #
                   15586:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15587:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15588:     #
                   15589:     # By default, use standard grading
                   15590:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15591: 
1.541     raeburn  15592:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15593:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15594: #
                   15595: # Open all assignments
                   15596: #
                   15597:     if ($args->{'openall'}) {
1.1075.2.141.  .4(raebu 15598:20):        my $opendate = time;
                   15599:20):        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15600:20):            $opendate = $args->{'openallfrom'};
                   15601:20):        }
1.444     albertel 15602:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.141.  .4(raebu 15603:20):        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15604:                            $storeunder.'.type' => 'date_start');
1.1075.2.141.  .4(raebu 15605:20):        $outcome .= &mt('All assignments open starting [_1]',
                   15606:20):                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15607:20):                    &Apache::lonnet::cput
                   15608:20):                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15609:    }
                   15610: #
                   15611: # Set first page
                   15612: #
                   15613:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15614: 	    || ($cloneid)) {
1.445     albertel 15615: 	use LONCAPA::map;
1.444     albertel 15616: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15617: 
                   15618: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15619:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15620: 
1.444     albertel 15621:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15622:         my $title; my $url;
                   15623:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15624: 	    $title=&mt('Syllabus');
1.444     albertel 15625:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15626:         } else {
1.963     raeburn  15627:             $title=&mt('Table of Contents');
1.444     albertel 15628:             $url='/adm/navmaps';
                   15629:         }
1.445     albertel 15630: 
                   15631:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15632: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15633: 
                   15634: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15635:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15636:     }
1.566     albertel 15637: 
1.1075.2.141.  .5(raebu 15638:20):     return (1,$outcome,\@clonemsg);
1.444     albertel 15639: }
                   15640: 
1.1075.2.59  raeburn  15641: sub make_unique_code {
                   15642:     my ($cdom,$cnum) = @_;
                   15643:     # get lock on uniquecodes db
                   15644:     my $lockhash = {
                   15645:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15646:                                                   ':'.$env{'user.domain'},
                   15647:                    };
                   15648:     my $tries = 0;
                   15649:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15650:     my ($code,$error);
                   15651: 
                   15652:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15653:         $tries ++;
                   15654:         sleep 1;
                   15655:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15656:     }
                   15657:     if ($gotlock eq 'ok') {
                   15658:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15659:         my $gotcode;
                   15660:         my $attempts = 0;
                   15661:         while ((!$gotcode) && ($attempts < 100)) {
                   15662:             $code = &generate_code();
                   15663:             if (!exists($currcodes{$code})) {
                   15664:                 $gotcode = 1;
                   15665:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15666:                     $error = 'nostore';
                   15667:                 }
                   15668:             }
                   15669:             $attempts ++;
                   15670:         }
                   15671:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15672:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15673:     } else {
                   15674:         $error = 'nolock';
                   15675:     }
                   15676:     return ($code,$error);
                   15677: }
                   15678: 
                   15679: sub generate_code {
                   15680:     my $code;
                   15681:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15682:     for (my $i=0; $i<6; $i++) {
                   15683:         my $lettnum = int (rand 2);
                   15684:         my $item = '';
                   15685:         if ($lettnum) {
                   15686:             $item = $letts[int( rand(18) )];
                   15687:         } else {
                   15688:             $item = 1+int( rand(8) );
                   15689:         }
                   15690:         $code .= $item;
                   15691:     }
                   15692:     return $code;
                   15693: }
                   15694: 
1.444     albertel 15695: ############################################################
                   15696: ############################################################
                   15697: 
1.953     droeschl 15698: #SD
                   15699: # only Community and Course, or anything else?
1.378     raeburn  15700: sub course_type {
                   15701:     my ($cid) = @_;
                   15702:     if (!defined($cid)) {
                   15703:         $cid = $env{'request.course.id'};
                   15704:     }
1.404     albertel 15705:     if (defined($env{'course.'.$cid.'.type'})) {
                   15706:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15707:     } else {
                   15708:         return 'Course';
1.377     raeburn  15709:     }
                   15710: }
1.156     albertel 15711: 
1.406     raeburn  15712: sub group_term {
                   15713:     my $crstype = &course_type();
                   15714:     my %names = (
                   15715:                   'Course' => 'group',
1.865     raeburn  15716:                   'Community' => 'group',
1.406     raeburn  15717:                 );
                   15718:     return $names{$crstype};
                   15719: }
                   15720: 
1.902     raeburn  15721: sub course_types {
1.1075.2.59  raeburn  15722:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15723:     my %typename = (
                   15724:                          official   => 'Official course',
                   15725:                          unofficial => 'Unofficial course',
                   15726:                          community  => 'Community',
1.1075.2.59  raeburn  15727:                          textbook   => 'Textbook course',
1.902     raeburn  15728:                    );
                   15729:     return (\@types,\%typename);
                   15730: }
                   15731: 
1.156     albertel 15732: sub icon {
                   15733:     my ($file)=@_;
1.505     albertel 15734:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15735:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15736:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15737:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15738: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15739: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15740: 	            $curfext.".gif") {
                   15741: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15742: 		$curfext.".gif";
                   15743: 	}
                   15744:     }
1.249     albertel 15745:     return &lonhttpdurl($iconname);
1.154     albertel 15746: } 
1.84      albertel 15747: 
1.575     albertel 15748: sub lonhttpdurl {
1.692     www      15749: #
                   15750: # Had been used for "small fry" static images on separate port 8080.
                   15751: # Modify here if lightweight http functionality desired again.
                   15752: # Currently eliminated due to increasing firewall issues.
                   15753: #
1.575     albertel 15754:     my ($url)=@_;
1.692     www      15755:     return $url;
1.215     albertel 15756: }
                   15757: 
1.213     albertel 15758: sub connection_aborted {
                   15759:     my ($r)=@_;
                   15760:     $r->print(" ");$r->rflush();
                   15761:     my $c = $r->connection;
                   15762:     return $c->aborted();
                   15763: }
                   15764: 
1.221     foxr     15765: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15766: #    strings as 'strings'.
                   15767: sub escape_single {
1.221     foxr     15768:     my ($input) = @_;
1.223     albertel 15769:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15770:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15771:     return $input;
                   15772: }
1.223     albertel 15773: 
1.222     foxr     15774: #  Same as escape_single, but escape's "'s  This 
                   15775: #  can be used for  "strings"
                   15776: sub escape_double {
                   15777:     my ($input) = @_;
                   15778:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15779:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15780:     return $input;
                   15781: }
1.223     albertel 15782:  
1.222     foxr     15783: #   Escapes the last element of a full URL.
                   15784: sub escape_url {
                   15785:     my ($url)   = @_;
1.238     raeburn  15786:     my @urlslices = split(/\//, $url,-1);
1.369     www      15787:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15788:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15789: }
1.462     albertel 15790: 
1.820     raeburn  15791: sub compare_arrays {
                   15792:     my ($arrayref1,$arrayref2) = @_;
                   15793:     my (@difference,%count);
                   15794:     @difference = ();
                   15795:     %count = ();
                   15796:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15797:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15798:         foreach my $element (keys(%count)) {
                   15799:             if ($count{$element} == 1) {
                   15800:                 push(@difference,$element);
                   15801:             }
                   15802:         }
                   15803:     }
                   15804:     return @difference;
                   15805: }
                   15806: 
1.817     bisitz   15807: # -------------------------------------------------------- Initialize user login
1.462     albertel 15808: sub init_user_environment {
1.463     albertel 15809:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15810:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15811: 
                   15812:     my $public=($username eq 'public' && $domain eq 'public');
                   15813: 
                   15814: # See if old ID present, if so, remove
                   15815: 
1.1062    raeburn  15816:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15817:     my $now=time;
                   15818: 
                   15819:     if ($public) {
                   15820: 	my $max_public=100;
                   15821: 	my $oldest;
                   15822: 	my $oldest_time=0;
                   15823: 	for(my $next=1;$next<=$max_public;$next++) {
                   15824: 	    if (-e $lonids."/publicuser_$next.id") {
                   15825: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15826: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15827: 		    $oldest_time=$mtime;
                   15828: 		    $oldest=$next;
                   15829: 		}
                   15830: 	    } else {
                   15831: 		$cookie="publicuser_$next";
                   15832: 		last;
                   15833: 	    }
                   15834: 	}
                   15835: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15836:     } else {
1.463     albertel 15837: 	# if this isn't a robot, kill any existing non-robot sessions
                   15838: 	if (!$args->{'robot'}) {
                   15839: 	    opendir(DIR,$lonids);
                   15840: 	    while ($filename=readdir(DIR)) {
                   15841: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15842:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15843:                             &GDBM_READER(),0640)) {
                   15844:                         my $linkedfile;
                   15845:                         if (exists($oldenv{'user.linkedenv'})) {
                   15846:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15847:                         }
                   15848:                         untie(%oldenv);
                   15849:                         if (unlink("$lonids/$filename")) {
                   15850:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15851:                                 if (-l "$lonids/$linkedfile.id") {
                   15852:                                     unlink("$lonids/$linkedfile.id");
                   15853:                                 }
                   15854:                             }
                   15855:                         }
                   15856:                     } else {
                   15857:                         unlink($lonids.'/'.$filename);
                   15858:                     }
1.463     albertel 15859: 		}
1.462     albertel 15860: 	    }
1.463     albertel 15861: 	    closedir(DIR);
1.1075.2.84  raeburn  15862: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15863:             my $namespace = 'nohist_courseeditor';
                   15864:             my $lockingkey = 'paste'."\0".'locked_num';
                   15865:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15866:                                                 $domain,$username);
                   15867:             if (exists($lockhash{$lockingkey})) {
                   15868:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15869:                 unless ($delresult eq 'ok') {
                   15870:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15871:                 }
                   15872:             }
1.462     albertel 15873: 	}
                   15874: # Give them a new cookie
1.463     albertel 15875: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15876: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15877: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15878:     
                   15879: # Initialize roles
                   15880: 
1.1062    raeburn  15881: 	($userroles,$firstaccenv,$timerintenv) = 
                   15882:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15883:     }
                   15884: # ------------------------------------ Check browser type and MathML capability
                   15885: 
1.1075.2.77  raeburn  15886:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15887:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15888: 
                   15889: # ------------------------------------------------------------- Get environment
                   15890: 
                   15891:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15892:     my ($tmp) = keys(%userenv);
                   15893:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15894:     } else {
                   15895: 	undef(%userenv);
                   15896:     }
                   15897:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15898: 	$form->{'interface'}=$userenv{'interface'};
                   15899:     }
                   15900:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15901: 
                   15902: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15903:     foreach my $option ('interface','localpath','localres') {
                   15904:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15905:     }
                   15906: # --------------------------------------------------------- Write first profile
                   15907: 
                   15908:     {
                   15909: 	my %initial_env = 
                   15910: 	    ("user.name"          => $username,
                   15911: 	     "user.domain"        => $domain,
                   15912: 	     "user.home"          => $authhost,
                   15913: 	     "browser.type"       => $clientbrowser,
                   15914: 	     "browser.version"    => $clientversion,
                   15915: 	     "browser.mathml"     => $clientmathml,
                   15916: 	     "browser.unicode"    => $clientunicode,
                   15917: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15918:              "browser.mobile"     => $clientmobile,
                   15919:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15920:              "browser.osversion"  => $clientosversion,
1.462     albertel 15921: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15922: 	     "request.course.fn"  => '',
                   15923: 	     "request.course.uri" => '',
                   15924: 	     "request.course.sec" => '',
                   15925: 	     "request.role"       => 'cm',
                   15926: 	     "request.role.adv"   => $env{'user.adv'},
                   15927: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15928: 
                   15929:         if ($form->{'localpath'}) {
                   15930: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15931: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15932:         }
                   15933: 	
                   15934: 	if ($form->{'interface'}) {
                   15935: 	    $form->{'interface'}=~s/\W//gs;
                   15936: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15937: 	    $env{'browser.interface'}=$form->{'interface'};
                   15938: 	}
                   15939: 
1.1075.2.54  raeburn  15940:         if ($form->{'iptoken'}) {
                   15941:             my $lonhost = $r->dir_config('lonHostID');
                   15942:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15943:             $env{'user.noloadbalance'} = $lonhost;
                   15944:         }
                   15945: 
1.1075.2.120  raeburn  15946:         if ($form->{'noloadbalance'}) {
                   15947:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15948:             my $hosthere = $form->{'noloadbalance'};
                   15949:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15950:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15951:                 $env{'user.noloadbalance'} = $hosthere;
                   15952:             }
                   15953:         }
                   15954: 
1.1016    raeburn  15955:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15956:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15957:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15958: 
1.1075.2.125  raeburn  15959:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15960:                 $userenv{'availabletools.'.$tool} = 
                   15961:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15962:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15963:             }
1.724     raeburn  15964: 
1.1075.2.125  raeburn  15965:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15966:                 $userenv{'canrequest.'.$crstype} =
                   15967:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15968:                                                       'reload','requestcourses',
                   15969:                                                       \%userenv,\%domdef,\%is_adv);
                   15970:             }
1.765     raeburn  15971: 
1.1075.2.125  raeburn  15972:             $userenv{'canrequest.author'} =
                   15973:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15974:                                                   'reload','requestauthor',
                   15975:                                                   \%userenv,\%domdef,\%is_adv);
                   15976:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15977:                                                  $domain,$username);
                   15978:             my $reqstatus = $reqauthor{'author_status'};
                   15979:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15980:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15981:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15982:                                                       $reqauthor{'author'}{'timestamp'};
                   15983:                 }
1.1075.2.14  raeburn  15984:             }
                   15985:         }
                   15986: 
1.462     albertel 15987: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15988: 
1.462     albertel 15989: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15990: 		 &GDBM_WRCREAT(),0640)) {
                   15991: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15992: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15993: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15994:             if (ref($firstaccenv) eq 'HASH') {
                   15995:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15996:             }
                   15997:             if (ref($timerintenv) eq 'HASH') {
                   15998:                 &_add_to_env(\%disk_env,$timerintenv);
                   15999:             }
1.463     albertel 16000: 	    if (ref($args->{'extra_env'})) {
                   16001: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16002: 	    }
1.462     albertel 16003: 	    untie(%disk_env);
                   16004: 	} else {
1.705     tempelho 16005: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16006: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16007: 	    return 'error: '.$!;
                   16008: 	}
                   16009:     }
                   16010:     $env{'request.role'}='cm';
                   16011:     $env{'request.role.adv'}=$env{'user.adv'};
                   16012:     $env{'browser.type'}=$clientbrowser;
                   16013: 
                   16014:     return $cookie;
                   16015: 
                   16016: }
                   16017: 
                   16018: sub _add_to_env {
                   16019:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16020:     if (ref($env_data) eq 'HASH') {
                   16021:         while (my ($key,$value) = each(%$env_data)) {
                   16022: 	    $idf->{$prefix.$key} = $value;
                   16023: 	    $env{$prefix.$key}   = $value;
                   16024:         }
1.462     albertel 16025:     }
                   16026: }
                   16027: 
1.685     tempelho 16028: # --- Get the symbolic name of a problem and the url
                   16029: sub get_symb {
                   16030:     my ($request,$silent) = @_;
1.726     raeburn  16031:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16032:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16033:     if ($symb eq '') {
                   16034:         if (!$silent) {
1.1071    raeburn  16035:             if (ref($request)) { 
                   16036:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16037:             }
1.685     tempelho 16038:             return ();
                   16039:         }
                   16040:     }
                   16041:     &Apache::lonenc::check_decrypt(\$symb);
                   16042:     return ($symb);
                   16043: }
                   16044: 
                   16045: # --------------------------------------------------------------Get annotation
                   16046: 
                   16047: sub get_annotation {
                   16048:     my ($symb,$enc) = @_;
                   16049: 
                   16050:     my $key = $symb;
                   16051:     if (!$enc) {
                   16052:         $key =
                   16053:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16054:     }
                   16055:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16056:     return $annotation{$key};
                   16057: }
                   16058: 
                   16059: sub clean_symb {
1.731     raeburn  16060:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16061: 
                   16062:     &Apache::lonenc::check_decrypt(\$symb);
                   16063:     my $enc = $env{'request.enc'};
1.731     raeburn  16064:     if ($delete_enc) {
1.730     raeburn  16065:         delete($env{'request.enc'});
                   16066:     }
1.685     tempelho 16067: 
                   16068:     return ($symb,$enc);
                   16069: }
1.462     albertel 16070: 
1.1075.2.69  raeburn  16071: ############################################################
                   16072: ############################################################
                   16073: 
                   16074: =pod
                   16075: 
                   16076: =head1 Routines for building display used to search for courses
                   16077: 
                   16078: 
                   16079: =over 4
                   16080: 
                   16081: =item * &build_filters()
                   16082: 
                   16083: Create markup for a table used to set filters to use when selecting
                   16084: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16085: and quotacheck.pl
                   16086: 
                   16087: 
                   16088: Inputs:
                   16089: 
                   16090: filterlist - anonymous array of fields to include as potential filters
                   16091: 
                   16092: crstype - course type
                   16093: 
                   16094: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16095:               to pop-open a course selector (will contain "extra element").
                   16096: 
                   16097: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16098: 
                   16099: filter - anonymous hash of criteria and their values
                   16100: 
                   16101: action - form action
                   16102: 
                   16103: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16104: 
                   16105: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16106: 
                   16107: cloneruname - username of owner of new course who wants to clone
                   16108: 
                   16109: clonerudom - domain of owner of new course who wants to clone
                   16110: 
                   16111: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16112: 
                   16113: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16114: 
                   16115: codedom - domain
                   16116: 
                   16117: formname - value of form element named "form".
                   16118: 
                   16119: fixeddom - domain, if fixed.
                   16120: 
                   16121: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16122: 
                   16123: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16124: 
                   16125: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16126: 
                   16127: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16128: 
                   16129: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16130: 
                   16131: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16132: 
                   16133: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16134: 
                   16135: 
                   16136: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16137: 
                   16138: 
                   16139: Side Effects: None
                   16140: 
                   16141: =cut
                   16142: 
                   16143: # ---------------------------------------------- search for courses based on last activity etc.
                   16144: 
                   16145: sub build_filters {
                   16146:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16147:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16148:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16149:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16150:         $clonetext,$clonewarning) = @_;
                   16151:     my ($list,$jscript);
                   16152:     my $onchange = 'javascript:updateFilters(this)';
                   16153:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16154:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16155:         $typeselectform,$instcodetitle);
                   16156:     if ($formname eq '') {
                   16157:         $formname = $caller;
                   16158:     }
                   16159:     foreach my $item (@{$filterlist}) {
                   16160:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16161:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16162:             if ($item eq 'domainfilter') {
                   16163:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16164:             } elsif ($item eq 'coursefilter') {
                   16165:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16166:             } elsif ($item eq 'ownerfilter') {
                   16167:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16168:             } elsif ($item eq 'ownerdomfilter') {
                   16169:                 $filter->{'ownerdomfilter'} =
                   16170:                     &LONCAPA::clean_domain($filter->{$item});
                   16171:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16172:                                                        'ownerdomfilter',1);
                   16173:             } elsif ($item eq 'personfilter') {
                   16174:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16175:             } elsif ($item eq 'persondomfilter') {
                   16176:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16177:                                                         'persondomfilter',1);
                   16178:             } else {
                   16179:                 $filter->{$item} =~ s/\W//g;
                   16180:             }
                   16181:             if (!$filter->{$item}) {
                   16182:                 $filter->{$item} = '';
                   16183:             }
                   16184:         }
                   16185:         if ($item eq 'domainfilter') {
                   16186:             my $allow_blank = 1;
                   16187:             if ($formname eq 'portform') {
                   16188:                 $allow_blank=0;
                   16189:             } elsif ($formname eq 'studentform') {
                   16190:                 $allow_blank=0;
                   16191:             }
                   16192:             if ($fixeddom) {
                   16193:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16194:                                     ' value="'.$codedom.'" />'.
                   16195:                                     &Apache::lonnet::domain($codedom,'description');
                   16196:             } else {
                   16197:                 $domainselectform = &select_dom_form($filter->{$item},
                   16198:                                                      'domainfilter',
                   16199:                                                       $allow_blank,'',$onchange);
                   16200:             }
                   16201:         } else {
                   16202:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16203:         }
                   16204:     }
                   16205: 
                   16206:     # last course activity filter and selection
                   16207:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16208: 
                   16209:     # course created filter and selection
                   16210:     if (exists($filter->{'createdfilter'})) {
                   16211:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16212:     }
                   16213: 
                   16214:     my %lt = &Apache::lonlocal::texthash(
                   16215:                 'cac' => "$crstype Activity",
                   16216:                 'ccr' => "$crstype Created",
                   16217:                 'cde' => "$crstype Title",
                   16218:                 'cdo' => "$crstype Domain",
                   16219:                 'ins' => 'Institutional Code',
                   16220:                 'inc' => 'Institutional Categorization',
                   16221:                 'cow' => "$crstype Owner/Co-owner",
                   16222:                 'cop' => "$crstype Personnel Includes",
                   16223:                 'cog' => 'Type',
                   16224:              );
                   16225: 
                   16226:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16227:         my $typeval = 'Course';
                   16228:         if ($crstype eq 'Community') {
                   16229:             $typeval = 'Community';
                   16230:         }
                   16231:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16232:     } else {
                   16233:         $typeselectform =  '<select name="type" size="1"';
                   16234:         if ($onchange) {
                   16235:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16236:         }
                   16237:         $typeselectform .= '>'."\n";
                   16238:         foreach my $posstype ('Course','Community') {
                   16239:             $typeselectform.='<option value="'.$posstype.'"'.
                   16240:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16241:         }
                   16242:         $typeselectform.="</select>";
                   16243:     }
                   16244: 
                   16245:     my ($cloneableonlyform,$cloneabletitle);
                   16246:     if (exists($filter->{'cloneableonly'})) {
                   16247:         my $cloneableon = '';
                   16248:         my $cloneableoff = ' checked="checked"';
                   16249:         if ($filter->{'cloneableonly'}) {
                   16250:             $cloneableon = $cloneableoff;
                   16251:             $cloneableoff = '';
                   16252:         }
                   16253:         $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>';
                   16254:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16255:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16256:         } else {
                   16257:             $cloneabletitle = &mt('Cloneable by you');
                   16258:         }
                   16259:     }
                   16260:     my $officialjs;
                   16261:     if ($crstype eq 'Course') {
                   16262:         if (exists($filter->{'instcodefilter'})) {
                   16263: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16264: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16265:             if ($codedom) {
                   16266:                 $officialjs = 1;
                   16267:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16268:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16269:                                                                   $officialjs,$codetitlesref);
                   16270:                 if ($jscript) {
                   16271:                     $jscript = '<script type="text/javascript">'."\n".
                   16272:                                '// <![CDATA['."\n".
                   16273:                                $jscript."\n".
                   16274:                                '// ]]>'."\n".
                   16275:                                '</script>'."\n";
                   16276:                 }
                   16277:             }
                   16278:             if ($instcodeform eq '') {
                   16279:                 $instcodeform =
                   16280:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16281:                     $list->{'instcodefilter'}.'" />';
                   16282:                 $instcodetitle = $lt{'ins'};
                   16283:             } else {
                   16284:                 $instcodetitle = $lt{'inc'};
                   16285:             }
                   16286:             if ($fixeddom) {
                   16287:                 $instcodetitle .= '<br />('.$codedom.')';
                   16288:             }
                   16289:         }
                   16290:     }
                   16291:     my $output = qq|
                   16292: <form method="post" name="filterpicker" action="$action">
                   16293: <input type="hidden" name="form" value="$formname" />
                   16294: |;
                   16295:     if ($formname eq 'modifycourse') {
                   16296:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16297:                    '<input type="hidden" name="prevphase" value="'.
                   16298:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16299:     } elsif ($formname eq 'quotacheck') {
                   16300:         $output .= qq|
                   16301: <input type="hidden" name="sortby" value="" />
                   16302: <input type="hidden" name="sortorder" value="" />
                   16303: |;
                   16304:     } else {
1.1075.2.69  raeburn  16305:         my $name_input;
                   16306:         if ($cnameelement ne '') {
                   16307:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16308:                           $cnameelement.'" />';
                   16309:         }
                   16310:         $output .= qq|
                   16311: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16312: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16313: $name_input
                   16314: $roleelement
                   16315: $multelement
                   16316: $typeelement
                   16317: |;
                   16318:         if ($formname eq 'portform') {
                   16319:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16320:         }
                   16321:     }
                   16322:     if ($fixeddom) {
                   16323:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16324:     }
                   16325:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16326:     if ($sincefilterform) {
                   16327:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16328:                   .$sincefilterform
                   16329:                   .&Apache::lonhtmlcommon::row_closure();
                   16330:     }
                   16331:     if ($createdfilterform) {
                   16332:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16333:                   .$createdfilterform
                   16334:                   .&Apache::lonhtmlcommon::row_closure();
                   16335:     }
                   16336:     if ($domainselectform) {
                   16337:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16338:                   .$domainselectform
                   16339:                   .&Apache::lonhtmlcommon::row_closure();
                   16340:     }
                   16341:     if ($typeselectform) {
                   16342:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16343:             $output .= $typeselectform;
                   16344:         } else {
                   16345:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16346:                       .$typeselectform
                   16347:                       .&Apache::lonhtmlcommon::row_closure();
                   16348:         }
                   16349:     }
                   16350:     if ($instcodeform) {
                   16351:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16352:                   .$instcodeform
                   16353:                   .&Apache::lonhtmlcommon::row_closure();
                   16354:     }
                   16355:     if (exists($filter->{'ownerfilter'})) {
                   16356:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16357:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16358:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16359:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16360:                    $ownerdomselectform.'</td></tr></table>'.
                   16361:                    &Apache::lonhtmlcommon::row_closure();
                   16362:     }
                   16363:     if (exists($filter->{'personfilter'})) {
                   16364:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16365:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16366:                    '<input type="text" name="personfilter" size="20" value="'.
                   16367:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16368:                    $persondomselectform.'</td></tr></table>'.
                   16369:                    &Apache::lonhtmlcommon::row_closure();
                   16370:     }
                   16371:     if (exists($filter->{'coursefilter'})) {
                   16372:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16373:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16374:                   .$list->{'coursefilter'}.'" />'
                   16375:                   .&Apache::lonhtmlcommon::row_closure();
                   16376:     }
                   16377:     if ($cloneableonlyform) {
                   16378:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16379:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16380:     }
                   16381:     if (exists($filter->{'descriptfilter'})) {
                   16382:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16383:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16384:                   .$list->{'descriptfilter'}.'" />'
                   16385:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16386:     }
                   16387:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16388:                '<input type="hidden" name="updater" value="" />'."\n".
                   16389:                '<input type="submit" name="gosearch" value="'.
                   16390:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16391:     return $jscript.$clonewarning.$output;
                   16392: }
                   16393: 
                   16394: =pod
                   16395: 
                   16396: =item * &timebased_select_form()
                   16397: 
                   16398: Create markup for a dropdown list used to select a time-based
                   16399: filter e.g., Course Activity, Course Created, when searching for courses
                   16400: or communities
                   16401: 
                   16402: Inputs:
                   16403: 
                   16404: item - name of form element (sincefilter or createdfilter)
                   16405: 
                   16406: filter - anonymous hash of criteria and their values
                   16407: 
                   16408: Returns: HTML for a select box contained a blank, then six time selections,
                   16409:          with value set in incoming form variables currently selected.
                   16410: 
                   16411: Side Effects: None
                   16412: 
                   16413: =cut
                   16414: 
                   16415: sub timebased_select_form {
                   16416:     my ($item,$filter) = @_;
                   16417:     if (ref($filter) eq 'HASH') {
                   16418:         $filter->{$item} =~ s/[^\d-]//g;
                   16419:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16420:         return &select_form(
                   16421:                             $filter->{$item},
                   16422:                             $item,
                   16423:                             {      '-1' => '',
                   16424:                                 '86400' => &mt('today'),
                   16425:                                '604800' => &mt('last week'),
                   16426:                               '2592000' => &mt('last month'),
                   16427:                               '7776000' => &mt('last three months'),
                   16428:                              '15552000' => &mt('last six months'),
                   16429:                              '31104000' => &mt('last year'),
                   16430:                     'select_form_order' =>
                   16431:                            ['-1','86400','604800','2592000','7776000',
                   16432:                             '15552000','31104000']});
                   16433:     }
                   16434: }
                   16435: 
                   16436: =pod
                   16437: 
                   16438: =item * &js_changer()
                   16439: 
                   16440: Create script tag containing Javascript used to submit course search form
                   16441: when course type or domain is changed, and also to hide 'Searching ...' on
                   16442: page load completion for page showing search result.
                   16443: 
                   16444: Inputs: None
                   16445: 
                   16446: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16447: 
                   16448: Side Effects: None
                   16449: 
                   16450: =cut
                   16451: 
                   16452: sub js_changer {
                   16453:     return <<ENDJS;
                   16454: <script type="text/javascript">
                   16455: // <![CDATA[
                   16456: function updateFilters(caller) {
                   16457:     if (typeof(caller) != "undefined") {
                   16458:         document.filterpicker.updater.value = caller.name;
                   16459:     }
                   16460:     document.filterpicker.submit();
                   16461: }
                   16462: 
                   16463: function hideSearching() {
                   16464:     if (document.getElementById('searching')) {
                   16465:         document.getElementById('searching').style.display = 'none';
                   16466:     }
                   16467:     return;
                   16468: }
                   16469: 
                   16470: // ]]>
                   16471: </script>
                   16472: 
                   16473: ENDJS
                   16474: }
                   16475: 
                   16476: =pod
                   16477: 
                   16478: =item * &search_courses()
                   16479: 
                   16480: Process selected filters form course search form and pass to lonnet::courseiddump
                   16481: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16482: 
                   16483: Inputs:
                   16484: 
                   16485: dom - domain being searched
                   16486: 
                   16487: type - course type ('Course' or 'Community' or '.' if any).
                   16488: 
                   16489: filter - anonymous hash of criteria and their values
                   16490: 
                   16491: numtitles - for institutional codes - number of categories
                   16492: 
                   16493: cloneruname - optional username of new course owner
                   16494: 
                   16495: clonerudom - optional domain of new course owner
                   16496: 
1.1075.2.95  raeburn  16497: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16498:             (used when DC is using course creation form)
                   16499: 
                   16500: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16501: 
1.1075.2.95  raeburn  16502: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16503:            (and so can clone automatically)
                   16504: 
                   16505: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16506: 
                   16507: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16508:               courses to clone
1.1075.2.69  raeburn  16509: 
                   16510: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16511: 
                   16512: 
                   16513: Side Effects: None
                   16514: 
                   16515: =cut
                   16516: 
                   16517: 
                   16518: sub search_courses {
1.1075.2.95  raeburn  16519:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16520:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16521:     my (%courses,%showcourses,$cloner);
                   16522:     if (($filter->{'ownerfilter'} ne '') ||
                   16523:         ($filter->{'ownerdomfilter'} ne '')) {
                   16524:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16525:                                        $filter->{'ownerdomfilter'};
                   16526:     }
                   16527:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16528:         if (!$filter->{$item}) {
                   16529:             $filter->{$item}='.';
                   16530:         }
                   16531:     }
                   16532:     my $now = time;
                   16533:     my $timefilter =
                   16534:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16535:     my ($createdbefore,$createdafter);
                   16536:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16537:         $createdbefore = $now;
                   16538:         $createdafter = $now-$filter->{'createdfilter'};
                   16539:     }
                   16540:     my ($instcodefilter,$regexpok);
                   16541:     if ($numtitles) {
                   16542:         if ($env{'form.official'} eq 'on') {
                   16543:             $instcodefilter =
                   16544:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16545:             $regexpok = 1;
                   16546:         } elsif ($env{'form.official'} eq 'off') {
                   16547:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16548:             unless ($instcodefilter eq '') {
                   16549:                 $regexpok = -1;
                   16550:             }
                   16551:         }
                   16552:     } else {
                   16553:         $instcodefilter = $filter->{'instcodefilter'};
                   16554:     }
                   16555:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16556:     if ($type eq '') { $type = '.'; }
                   16557: 
                   16558:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16559:         $cloner = $cloneruname.':'.$clonerudom;
                   16560:     }
                   16561:     %courses = &Apache::lonnet::courseiddump($dom,
                   16562:                                              $filter->{'descriptfilter'},
                   16563:                                              $timefilter,
                   16564:                                              $instcodefilter,
                   16565:                                              $filter->{'combownerfilter'},
                   16566:                                              $filter->{'coursefilter'},
                   16567:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16568:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16569:                                              $filter->{'cloneableonly'},
                   16570:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16571:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16572:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16573:         my $ccrole;
                   16574:         if ($type eq 'Community') {
                   16575:             $ccrole = 'co';
                   16576:         } else {
                   16577:             $ccrole = 'cc';
                   16578:         }
                   16579:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16580:                                                      $filter->{'persondomfilter'},
                   16581:                                                      'userroles',undef,
                   16582:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16583:                                                      $dom);
                   16584:         foreach my $role (keys(%rolehash)) {
                   16585:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16586:             my $cid = $cdom.'_'.$cnum;
                   16587:             if (exists($courses{$cid})) {
                   16588:                 if (ref($courses{$cid}) eq 'HASH') {
                   16589:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16590:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16591:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16592:                         }
                   16593:                     } else {
                   16594:                         $courses{$cid}{roles} = [$courserole];
                   16595:                     }
                   16596:                     $showcourses{$cid} = $courses{$cid};
                   16597:                 }
                   16598:             }
                   16599:         }
                   16600:         %courses = %showcourses;
                   16601:     }
                   16602:     return %courses;
                   16603: }
                   16604: 
                   16605: =pod
                   16606: 
                   16607: =back
                   16608: 
1.1075.2.88  raeburn  16609: =head1 Routines for version requirements for current course.
                   16610: 
                   16611: =over 4
                   16612: 
                   16613: =item * &check_release_required()
                   16614: 
                   16615: Compares required LON-CAPA version with version on server, and
                   16616: if required version is newer looks for a server with the required version.
                   16617: 
                   16618: Looks first at servers in user's owen domain; if none suitable, looks at
                   16619: servers in course's domain are permitted to host sessions for user's domain.
                   16620: 
                   16621: Inputs:
                   16622: 
                   16623: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16624: 
                   16625: $courseid - Course ID of current course
                   16626: 
                   16627: $rolecode - User's current role in course (for switchserver query string).
                   16628: 
                   16629: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16630: 
                   16631: 
                   16632: Returns:
                   16633: 
                   16634: $switchserver - query string tp append to /adm/switchserver call (if
                   16635:                 current server's LON-CAPA version is too old.
                   16636: 
                   16637: $warning - Message is displayed if no suitable server could be found.
                   16638: 
                   16639: =cut
                   16640: 
                   16641: sub check_release_required {
                   16642:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16643:     my ($switchserver,$warning);
                   16644:     if ($required ne '') {
                   16645:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16646:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16647:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16648:             my $otherserver;
                   16649:             if (($major eq '' && $minor eq '') ||
                   16650:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16651:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16652:                 my $switchlcrev =
                   16653:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16654:                                                            $userdomserver);
                   16655:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16656:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16657:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16658:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16659:                     if ($cdom ne $env{'user.domain'}) {
                   16660:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16661:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16662:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16663:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16664:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16665:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16666:                         my $canhost =
                   16667:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16668:                                                               $coursedomserver,
                   16669:                                                               $remoterev,
                   16670:                                                               $udomdefaults{'remotesessions'},
                   16671:                                                               $defdomdefaults{'hostedsessions'});
                   16672: 
                   16673:                         if ($canhost) {
                   16674:                             $otherserver = $coursedomserver;
                   16675:                         } else {
                   16676:                             $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.");
                   16677:                         }
                   16678:                     } else {
                   16679:                         $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).");
                   16680:                     }
                   16681:                 } else {
                   16682:                     $otherserver = $userdomserver;
                   16683:                 }
                   16684:             }
                   16685:             if ($otherserver ne '') {
                   16686:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16687:             }
                   16688:         }
                   16689:     }
                   16690:     return ($switchserver,$warning);
                   16691: }
                   16692: 
                   16693: =pod
                   16694: 
                   16695: =item * &check_release_result()
                   16696: 
                   16697: Inputs:
                   16698: 
                   16699: $switchwarning - Warning message if no suitable server found to host session.
                   16700: 
                   16701: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16702:                 and current role.
                   16703: 
                   16704: Returns: HTML to display with information about requirement to switch server.
                   16705:          Either displaying warning with link to Roles/Courses screen or
                   16706:          display link to switchserver.
                   16707: 
1.1075.2.69  raeburn  16708: =cut
                   16709: 
1.1075.2.88  raeburn  16710: sub check_release_result {
                   16711:     my ($switchwarning,$switchserver) = @_;
                   16712:     my $output = &start_page('Selected course unavailable on this server').
                   16713:                  '<p class="LC_warning">';
                   16714:     if ($switchwarning) {
                   16715:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16716:         if (&show_course()) {
                   16717:             $output .= &mt('Display courses');
                   16718:         } else {
                   16719:             $output .= &mt('Display roles');
                   16720:         }
                   16721:         $output .= '</a>';
                   16722:     } elsif ($switchserver) {
                   16723:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16724:                    '<br />'.
                   16725:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16726:                    &mt('Switch Server').
                   16727:                    '</a>';
                   16728:     }
                   16729:     $output .= '</p>'.&end_page();
                   16730:     return $output;
                   16731: }
                   16732: 
                   16733: =pod
                   16734: 
                   16735: =item * &needs_coursereinit()
                   16736: 
                   16737: Determine if course contents stored for user's session needs to be
                   16738: refreshed, because content has changed since "Big Hash" last tied.
                   16739: 
                   16740: Check for change is made if time last checked is more than 10 minutes ago
                   16741: (by default).
                   16742: 
                   16743: Inputs:
                   16744: 
                   16745: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16746: 
                   16747: $interval (optional) - Time which may elapse (in s) between last check for content
                   16748:                        change in current course. (default: 600 s).
                   16749: 
                   16750: Returns: an array; first element is:
                   16751: 
                   16752: =over 4
                   16753: 
                   16754: 'switch' - if content updates mean user's session
                   16755:            needs to be switched to a server running a newer LON-CAPA version
                   16756: 
                   16757: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16758:            on current server hosting user's session
                   16759: 
                   16760: ''       - if no action required.
                   16761: 
                   16762: =back
                   16763: 
                   16764: If first item element is 'switch':
                   16765: 
                   16766: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16767: 
                   16768: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16769:                               and current role.
                   16770: 
                   16771: otherwise: no other elements returned.
                   16772: 
                   16773: =back
                   16774: 
                   16775: =cut
                   16776: 
                   16777: sub needs_coursereinit {
                   16778:     my ($loncaparev,$interval) = @_;
                   16779:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16780:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16781:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16782:     my $now = time;
                   16783:     if ($interval eq '') {
                   16784:         $interval = 600;
                   16785:     }
                   16786:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16787:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.141.  .6(raebu 16788:20):         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
                   16789:20):         if ($blocked) {
                   16790:20):             return ();
                   16791:20):         }
                   16792:20):         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
1.1075.2.88  raeburn  16793:         if ($lastchange > $env{'request.course.tied'}) {
                   16794:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16795:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16796:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16797:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16798:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16799:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16800:                     my ($switchserver,$switchwarning) =
                   16801:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16802:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16803:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16804:                         return ('switch',$switchwarning,$switchserver);
                   16805:                     }
                   16806:                 }
                   16807:             }
                   16808:             return ('update');
                   16809:         }
                   16810:     }
                   16811:     return ();
                   16812: }
1.1075.2.69  raeburn  16813: 
1.1075.2.11  raeburn  16814: sub update_content_constraints {
                   16815:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16816:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16817:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16818:     my %checkresponsetypes;
                   16819:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16820:         my ($item,$name,$value) = split(/:/,$key);
                   16821:         if ($item eq 'resourcetag') {
                   16822:             if ($name eq 'responsetype') {
                   16823:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16824:             }
                   16825:         }
                   16826:     }
                   16827:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16828:     if (defined($navmap)) {
                   16829:         my %allresponses;
                   16830:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16831:             my %responses = $res->responseTypes();
                   16832:             foreach my $key (keys(%responses)) {
                   16833:                 next unless(exists($checkresponsetypes{$key}));
                   16834:                 $allresponses{$key} += $responses{$key};
                   16835:             }
                   16836:         }
                   16837:         foreach my $key (keys(%allresponses)) {
                   16838:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16839:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16840:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16841:             }
                   16842:         }
                   16843:         undef($navmap);
                   16844:     }
                   16845:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16846:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16847:     }
                   16848:     return;
                   16849: }
                   16850: 
1.1075.2.27  raeburn  16851: sub allmaps_incourse {
                   16852:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16853:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16854:         $cid = $env{'request.course.id'};
                   16855:         $cdom = $env{'course.'.$cid.'.domain'};
                   16856:         $cnum = $env{'course.'.$cid.'.num'};
                   16857:         $chome = $env{'course.'.$cid.'.home'};
                   16858:     }
                   16859:     my %allmaps = ();
                   16860:     my $lastchange =
                   16861:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16862:     if ($lastchange > $env{'request.course.tied'}) {
                   16863:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16864:         unless ($ferr) {
                   16865:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16866:         }
                   16867:     }
                   16868:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16869:     if (defined($navmap)) {
                   16870:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16871:             $allmaps{$res->src()} = 1;
                   16872:         }
                   16873:     }
                   16874:     return \%allmaps;
                   16875: }
                   16876: 
1.1075.2.11  raeburn  16877: sub parse_supplemental_title {
                   16878:     my ($title) = @_;
                   16879: 
                   16880:     my ($foldertitle,$renametitle);
                   16881:     if ($title =~ /&amp;&amp;&amp;/) {
                   16882:         $title = &HTML::Entites::decode($title);
                   16883:     }
                   16884:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16885:         $renametitle=$4;
                   16886:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16887:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16888:         my $name =  &plainname($uname,$udom);
                   16889:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16890:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16891:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16892:             $name.': <br />'.$foldertitle;
                   16893:     }
                   16894:     if (wantarray) {
                   16895:         return ($title,$foldertitle,$renametitle);
                   16896:     }
                   16897:     return $title;
                   16898: }
                   16899: 
1.1075.2.43  raeburn  16900: sub recurse_supplemental {
                   16901:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16902:     if ($suppmap) {
                   16903:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16904:         if ($fatal) {
                   16905:             $errors ++;
                   16906:         } else {
                   16907:             if ($#LONCAPA::map::resources > 0) {
                   16908:                 foreach my $res (@LONCAPA::map::resources) {
                   16909:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16910:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16911:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16912:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16913:                         } else {
                   16914:                             $numfiles ++;
                   16915:                         }
                   16916:                     }
                   16917:                 }
                   16918:             }
                   16919:         }
                   16920:     }
                   16921:     return ($numfiles,$errors);
                   16922: }
                   16923: 
1.1075.2.18  raeburn  16924: sub symb_to_docspath {
1.1075.2.119  raeburn  16925:     my ($symb,$navmapref) = @_;
                   16926:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16927:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16928:     if ($resurl=~/\.(sequence|page)$/) {
                   16929:         $mapurl=$resurl;
                   16930:     } elsif ($resurl eq 'adm/navmaps') {
                   16931:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16932:     }
                   16933:     my $mapresobj;
1.1075.2.119  raeburn  16934:     unless (ref($$navmapref)) {
                   16935:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16936:     }
                   16937:     if (ref($$navmapref)) {
                   16938:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16939:     }
                   16940:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16941:     my $type=$2;
                   16942:     my $path;
                   16943:     if (ref($mapresobj)) {
                   16944:         my $pcslist = $mapresobj->map_hierarchy();
                   16945:         if ($pcslist ne '') {
                   16946:             foreach my $pc (split(/,/,$pcslist)) {
                   16947:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16948:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16949:                 if (ref($res)) {
                   16950:                     my $thisurl = $res->src();
                   16951:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16952:                     my $thistitle = $res->title();
                   16953:                     $path .= '&'.
                   16954:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16955:                              &escape($thistitle).
1.1075.2.18  raeburn  16956:                              ':'.$res->randompick().
                   16957:                              ':'.$res->randomout().
                   16958:                              ':'.$res->encrypted().
                   16959:                              ':'.$res->randomorder().
                   16960:                              ':'.$res->is_page();
                   16961:                 }
                   16962:             }
                   16963:         }
                   16964:         $path =~ s/^\&//;
                   16965:         my $maptitle = $mapresobj->title();
                   16966:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16967:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16968:         }
                   16969:         $path .= (($path ne '')? '&' : '').
                   16970:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16971:                  &escape($maptitle).
1.1075.2.18  raeburn  16972:                  ':'.$mapresobj->randompick().
                   16973:                  ':'.$mapresobj->randomout().
                   16974:                  ':'.$mapresobj->encrypted().
                   16975:                  ':'.$mapresobj->randomorder().
                   16976:                  ':'.$mapresobj->is_page();
                   16977:     } else {
                   16978:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16979:         my $ispage = (($type eq 'page')? 1 : '');
                   16980:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16981:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16982:         }
                   16983:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16984:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16985:     }
                   16986:     unless ($mapurl eq 'default') {
                   16987:         $path = 'default&'.
1.1075.2.46  raeburn  16988:                 &escape('Main Content').
1.1075.2.18  raeburn  16989:                 ':::::&'.$path;
                   16990:     }
                   16991:     return $path;
                   16992: }
                   16993: 
1.1075.2.14  raeburn  16994: sub captcha_display {
1.1075.2.137  raeburn  16995:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16996:     my ($output,$error);
1.1075.2.107  raeburn  16997:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  16998:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16999:     if ($captcha eq 'original') {
                   17000:         $output = &create_captcha();
                   17001:         unless ($output) {
                   17002:             $error = 'captcha';
                   17003:         }
                   17004:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17005:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17006:         unless ($output) {
                   17007:             $error = 'recaptcha';
                   17008:         }
                   17009:     }
1.1075.2.107  raeburn  17010:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17011: }
                   17012: 
                   17013: sub captcha_response {
1.1075.2.137  raeburn  17014:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17015:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17016:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17017:     if ($captcha eq 'original') {
                   17018:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17019:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17020:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17021:     } else {
                   17022:         $captcha_chk = 1;
                   17023:     }
                   17024:     return ($captcha_chk,$captcha_error);
                   17025: }
                   17026: 
                   17027: sub get_captcha_config {
1.1075.2.137  raeburn  17028:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17029:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17030:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17031:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17032:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17033:     if ($context eq 'usercreation') {
                   17034:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17035:         if (ref($domconfig{$context}) eq 'HASH') {
                   17036:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17037:             if (ref($hashtocheck) eq 'HASH') {
                   17038:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17039:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17040:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17041:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17042:                     }
                   17043:                     if ($privkey && $pubkey) {
                   17044:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17045:                         $version = $hashtocheck->{'recaptchaversion'};
                   17046:                         if ($version ne '2') {
                   17047:                             $version = 1;
                   17048:                         }
1.1075.2.14  raeburn  17049:                     } else {
                   17050:                         $captcha = 'original';
                   17051:                     }
                   17052:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17053:                     $captcha = 'original';
                   17054:                 }
                   17055:             }
                   17056:         } else {
                   17057:             $captcha = 'captcha';
                   17058:         }
                   17059:     } elsif ($context eq 'login') {
                   17060:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17061:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17062:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17063:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17064:             if ($privkey && $pubkey) {
                   17065:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17066:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17067:                 if ($version ne '2') {
                   17068:                     $version = 1;
                   17069:                 }
1.1075.2.14  raeburn  17070:             } else {
                   17071:                 $captcha = 'original';
                   17072:             }
                   17073:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17074:             $captcha = 'original';
                   17075:         }
1.1075.2.137  raeburn  17076:     } elsif ($context eq 'passwords') {
                   17077:         if ($dom_in_effect) {
                   17078:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17079:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17080:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17081:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17082:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17083:                 }
                   17084:                 if ($privkey && $pubkey) {
                   17085:                     $captcha = 'recaptcha';
                   17086:                     $version = $passwdconf{'recaptchaversion'};
                   17087:                     if ($version ne '2') {
                   17088:                         $version = 1;
                   17089:                     }
                   17090:                 } else {
                   17091:                     $captcha = 'original';
                   17092:                 }
                   17093:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17094:                 $captcha = 'original';
                   17095:             }
                   17096:         }
1.1075.2.14  raeburn  17097:     }
1.1075.2.107  raeburn  17098:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17099: }
                   17100: 
                   17101: sub create_captcha {
                   17102:     my %captcha_params = &captcha_settings();
                   17103:     my ($output,$maxtries,$tries) = ('',10,0);
                   17104:     while ($tries < $maxtries) {
                   17105:         $tries ++;
                   17106:         my $captcha = Authen::Captcha->new (
                   17107:                                            output_folder => $captcha_params{'output_dir'},
                   17108:                                            data_folder   => $captcha_params{'db_dir'},
                   17109:                                           );
                   17110:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17111: 
                   17112:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17113:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17114:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17115:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17116:                       '<br />'.
                   17117:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17118:             last;
                   17119:         }
                   17120:     }
                   17121:     return $output;
                   17122: }
                   17123: 
                   17124: sub captcha_settings {
                   17125:     my %captcha_params = (
                   17126:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17127:                            www_output_dir => "/captchaspool",
                   17128:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17129:                            numchars       => '5',
                   17130:                          );
                   17131:     return %captcha_params;
                   17132: }
                   17133: 
                   17134: sub check_captcha {
                   17135:     my ($captcha_chk,$captcha_error);
                   17136:     my $code = $env{'form.code'};
                   17137:     my $md5sum = $env{'form.crypt'};
                   17138:     my %captcha_params = &captcha_settings();
                   17139:     my $captcha = Authen::Captcha->new(
                   17140:                       output_folder => $captcha_params{'output_dir'},
                   17141:                       data_folder   => $captcha_params{'db_dir'},
                   17142:                   );
1.1075.2.26  raeburn  17143:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17144:     my %captcha_hash = (
                   17145:                         0       => 'Code not checked (file error)',
                   17146:                        -1      => 'Failed: code expired',
                   17147:                        -2      => 'Failed: invalid code (not in database)',
                   17148:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17149:     );
                   17150:     if ($captcha_chk != 1) {
                   17151:         $captcha_error = $captcha_hash{$captcha_chk}
                   17152:     }
                   17153:     return ($captcha_chk,$captcha_error);
                   17154: }
                   17155: 
                   17156: sub create_recaptcha {
1.1075.2.107  raeburn  17157:     my ($pubkey,$version) = @_;
                   17158:     if ($version >= 2) {
                   17159:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17160:     } else {
                   17161:         my $use_ssl;
                   17162:         if ($ENV{'SERVER_PORT'} == 443) {
                   17163:             $use_ssl = 1;
                   17164:         }
                   17165:         my $captcha = Captcha::reCAPTCHA->new;
                   17166:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17167:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17168:                &mt('If the text is hard to read, [_1] will replace them.',
                   17169:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17170:                '<br /><br />';
                   17171:      }
1.1075.2.14  raeburn  17172: }
                   17173: 
                   17174: sub check_recaptcha {
1.1075.2.107  raeburn  17175:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17176:     my $captcha_chk;
1.1075.2.107  raeburn  17177:     if ($version >= 2) {
                   17178:         my $ua = LWP::UserAgent->new;
                   17179:         $ua->timeout(10);
                   17180:         my %info = (
                   17181:                      secret   => $privkey,
                   17182:                      response => $env{'form.g-recaptcha-response'},
                   17183:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17184:                    );
                   17185:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17186:         if ($response->is_success)  {
                   17187:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17188:             if (ref($data) eq 'HASH') {
                   17189:                 if ($data->{'success'}) {
                   17190:                     $captcha_chk = 1;
                   17191:                 }
                   17192:             }
                   17193:         }
                   17194:     } else {
                   17195:         my $captcha = Captcha::reCAPTCHA->new;
                   17196:         my $captcha_result =
                   17197:             $captcha->check_answer(
                   17198:                                     $privkey,
                   17199:                                     $ENV{'REMOTE_ADDR'},
                   17200:                                     $env{'form.recaptcha_challenge_field'},
                   17201:                                     $env{'form.recaptcha_response_field'},
                   17202:                                   );
                   17203:         if ($captcha_result->{is_valid}) {
                   17204:             $captcha_chk = 1;
                   17205:         }
1.1075.2.14  raeburn  17206:     }
                   17207:     return $captcha_chk;
                   17208: }
                   17209: 
1.1075.2.64  raeburn  17210: sub emailusername_info {
1.1075.2.103  raeburn  17211:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17212:     my %titles = &Apache::lonlocal::texthash (
                   17213:                      lastname      => 'Last Name',
                   17214:                      firstname     => 'First Name',
                   17215:                      institution   => 'School/college/university',
                   17216:                      location      => "School's city, state/province, country",
                   17217:                      web           => "School's web address",
                   17218:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17219:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17220:                  );
                   17221:     return (\@fields,\%titles);
                   17222: }
                   17223: 
1.1075.2.56  raeburn  17224: sub cleanup_html {
                   17225:     my ($incoming) = @_;
                   17226:     my $outgoing;
                   17227:     if ($incoming ne '') {
                   17228:         $outgoing = $incoming;
                   17229:         $outgoing =~ s/;/&#059;/g;
                   17230:         $outgoing =~ s/\#/&#035;/g;
                   17231:         $outgoing =~ s/\&/&#038;/g;
                   17232:         $outgoing =~ s/</&#060;/g;
                   17233:         $outgoing =~ s/>/&#062;/g;
                   17234:         $outgoing =~ s/\(/&#040/g;
                   17235:         $outgoing =~ s/\)/&#041;/g;
                   17236:         $outgoing =~ s/"/&#034;/g;
                   17237:         $outgoing =~ s/'/&#039;/g;
                   17238:         $outgoing =~ s/\$/&#036;/g;
                   17239:         $outgoing =~ s{/}{&#047;}g;
                   17240:         $outgoing =~ s/=/&#061;/g;
                   17241:         $outgoing =~ s/\\/&#092;/g
                   17242:     }
                   17243:     return $outgoing;
                   17244: }
                   17245: 
1.1075.2.74  raeburn  17246: # Checks for critical messages and returns a redirect url if one exists.
                   17247: # $interval indicates how often to check for messages.
1.1075.2.141.  .6(raebu 17248:20): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  17249: sub critical_redirect {
1.1075.2.141.  .6(raebu 17250:20):     my ($interval,$context) = @_;
1.1075.2.74  raeburn  17251:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.141.  .6(raebu 17252:20):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17253:20):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17254:20):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17255:20):             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17256:20):             if ($blocked) {
                   17257:20):                 my $checkrole = "cm./$cdom/$cnum";
                   17258:20):                 if ($env{'request.course.sec'} ne '') {
                   17259:20):                     $checkrole .= "/$env{'request.course.sec'}";
                   17260:20):                 }
                   17261:20):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17262:20):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17263:20):                     return;
                   17264:20):                 }
                   17265:20):             }
                   17266:20):         }
1.1075.2.74  raeburn  17267:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17268:                                         $env{'user.name'});
                   17269:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17270:         my $redirecturl;
                   17271:         if ($what[0]) {
                   17272:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17273:                 $redirecturl='/adm/email?critical=display';
                   17274:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17275:                 return (1, $url);
                   17276:             }
                   17277:         }
                   17278:     }
                   17279:     return ();
                   17280: }
                   17281: 
1.1075.2.64  raeburn  17282: # Use:
                   17283: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17284: #
                   17285: ##################################################
                   17286: #          password associated functions         #
                   17287: ##################################################
                   17288: sub des_keys {
                   17289:     # Make a new key for DES encryption.
                   17290:     # Each key has two parts which are returned separately.
                   17291:     # Please note:  Each key must be passed through the &hex function
                   17292:     # before it is output to the web browser.  The hex versions cannot
                   17293:     # be used to decrypt.
                   17294:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17295:                 '8','9','a','b','c','d','e','f');
                   17296:     my $lkey='';
                   17297:     for (0..7) {
                   17298:         $lkey.=$hexstr[rand(15)];
                   17299:     }
                   17300:     my $ukey='';
                   17301:     for (0..7) {
                   17302:         $ukey.=$hexstr[rand(15)];
                   17303:     }
                   17304:     return ($lkey,$ukey);
                   17305: }
                   17306: 
                   17307: sub des_decrypt {
                   17308:     my ($key,$cyphertext) = @_;
                   17309:     my $keybin=pack("H16",$key);
                   17310:     my $cypher;
                   17311:     if ($Crypt::DES::VERSION>=2.03) {
                   17312:         $cypher=new Crypt::DES $keybin;
                   17313:     } else {
                   17314:         $cypher=new DES $keybin;
                   17315:     }
1.1075.2.106  raeburn  17316:     my $plaintext='';
                   17317:     my $cypherlength = length($cyphertext);
                   17318:     my $numchunks = int($cypherlength/32);
                   17319:     for (my $j=0; $j<$numchunks; $j++) {
                   17320:         my $start = $j*32;
                   17321:         my $cypherblock = substr($cyphertext,$start,32);
                   17322:         my $chunk =
                   17323:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17324:         $chunk .=
                   17325:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17326:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17327:         $plaintext .= $chunk;
                   17328:     }
1.1075.2.64  raeburn  17329:     return $plaintext;
                   17330: }
                   17331: 
1.1075.2.141.  .5(raebu 17332:20): sub get_requested_shorturls {
          .1(raebu 17333:20):     my ($cdom,$cnum,$navmap) = @_;
                   17334:20):     return unless (ref($navmap));
          .5(raebu 17335:20):     my ($numnew,$errors);
          .1(raebu 17336:20):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17337:20):     if (@toshorten) {
                   17338:20):         my (%maps,%resources,%titles);
                   17339:20):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17340:20):                                                                'shorturls',$cdom,$cnum);
                   17341:20):         if (keys(%resources)) {
          .5(raebu 17342:20):             my %tocreate;
          .1(raebu 17343:20):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17344:20):                 my $symb = $resources{$item};
                   17345:20):                 if ($symb) {
                   17346:20):                     $tocreate{$cnum.'&'.$symb} = 1;
                   17347:20):                 }
                   17348:20):             }
          .5(raebu 17349:20):             if (keys(%tocreate)) {
                   17350:20):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   17351:20):                                                       \%tocreate);
                   17352:20):             }
          .1(raebu 17353:20):         }
          .5(raebu 17354:20):     }
                   17355:20):     return ($numnew,$errors);
                   17356:20): }
                   17357:20): 
                   17358:20): sub make_short_symbs {
                   17359:20):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   17360:20):     my ($numnew,@errors);
                   17361:20):     if (ref($tocreateref) eq 'HASH') {
                   17362:20):         my %tocreate = %{$tocreateref};
          .1(raebu 17363:20):         if (keys(%tocreate)) {
                   17364:20):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17365:20):             my $su = Short::URL->new(no_vowels => 1);
                   17366:20):             my $init = '';
                   17367:20):             my (%newunique,%addcourse,%courseonly,%failed);
                   17368:20):             # get lock on tiny db
                   17369:20):             my $now = time;
          .5(raebu 17370:20):             if ($lockuser eq '') {
                   17371:20):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   17372:20):             }
          .1(raebu 17373:20):             my $lockhash = {
          .5(raebu 17374:20):                                 "lock\0$now" => $lockuser,
          .1(raebu 17375:20):                             };
                   17376:20):             my $tries = 0;
                   17377:20):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17378:20):             my ($code,$error);
                   17379:20):             while (($gotlock ne 'ok') && ($tries<3)) {
                   17380:20):                 $tries ++;
                   17381:20):                 sleep 1;
                   17382:20):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17383:20):             }
                   17384:20):             if ($gotlock eq 'ok') {
                   17385:20):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17386:20):                                        \%addcourse,\%courseonly,\%failed);
                   17387:20):                 if (keys(%failed)) {
                   17388:20):                     my $numfailed = scalar(keys(%failed));
                   17389:20):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17390:20):                 }
                   17391:20):                 if (keys(%newunique)) {
                   17392:20):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17393:20):                     if ($putres eq 'ok') {
                   17394:20):                         $numnew = scalar(keys(%newunique));
                   17395:20):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17396:20):                         unless ($newputres eq 'ok') {
                   17397:20):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17398:20):                         }
                   17399:20):                     } else {
                   17400:20):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   17401:20):                     }
                   17402:20):                 }
                   17403:20):             }
                   17404:20):         }
                   17405:20):     }
                   17406:20):     return ($numnew,\@errors);
                   17407:20): }
                   17408:20): 
                   17409:20): sub shorten_symbs {
                   17410:20):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   17411:20):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   17412:20):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   17413:20):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   17414:20):     my (%possibles,%collisions);
                   17415:20):     foreach my $key (keys(%{$tocreate})) {
                   17416:20):         my $num = String::CRC32::crc32($key);
                   17417:20):         my $tiny = $su->encode($num,$init);
                   17418:20):         if ($tiny) {
                   17419:20):             $possibles{$tiny} = $key;
                   17420:20):         }
                   17421:20):     }
                   17422:20):     if (!$init) {
                   17423:20):         $init = 1;
                   17424:20):     } else {
                   17425:20):         $init ++;
                   17426:20):     }
                   17427:20):     if (keys(%possibles)) {
                   17428:20):         my @posstiny = keys(%possibles);
                   17429:20):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   17430:20):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   17431:20):         if (keys(%currtiny)) {
                   17432:20):             foreach my $key (keys(%currtiny)) {
                   17433:20):                 next if ($currtiny{$key} eq '');
                   17434:20):                 if ($currtiny{$key} eq $possibles{$key}) {
                   17435:20):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   17436:20):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17437:20):                         $courseonly->{$tsymb} = $key;
                   17438:20):                     }
                   17439:20):                 } else {
                   17440:20):                     $collisions{$possibles{$key}} = 1;
                   17441:20):                 }
                   17442:20):                 delete($possibles{$key});
                   17443:20):             }
                   17444:20):         }
                   17445:20):         foreach my $key (keys(%possibles)) {
                   17446:20):             $newunique->{$key} = $possibles{$key};
                   17447:20):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   17448:20):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17449:20):                 $addcourse->{$tsymb} = $key;
                   17450:20):             }
                   17451:20):         }
                   17452:20):     }
                   17453:20):     if (keys(%collisions)) {
                   17454:20):         if ($init <5) {
                   17455:20):             if (!$init) {
                   17456:20):                 $init = 1;
                   17457:20):             } else {
                   17458:20):                 $init ++;
                   17459:20):             }
                   17460:20):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   17461:20):                                    $newunique,$addcourse,$courseonly,$failed);
                   17462:20):         } else {
                   17463:20):             foreach my $key (keys(%collisions)) {
                   17464:20):                 $failed->{$key} = 1;
                   17465:20):                 $failed->{$key} = 1;
                   17466:20):             }
                   17467:20):         }
                   17468:20):     }
                   17469:20):     return $init;
                   17470:20): }
                   17471:20): 
1.1075.2.135  raeburn  17472: sub is_nonframeable {
                   17473:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17474:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17475:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17476: 
                   17477:     $remprotocol = lc($remprotocol);
                   17478:     $remhost = lc($remhost);
                   17479:     my $remport = 80;
                   17480:     if ($remprotocol eq 'https') {
                   17481:         $remport = 443;
                   17482:     }
                   17483:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17484:     if ($cached) {
                   17485:         unless ($nocache) {
                   17486:             if ($result) {
                   17487:                 return 1;
                   17488:             } else {
                   17489:                 return 0;
                   17490:             }
                   17491:         }
                   17492:     }
                   17493:     my $uselink;
                   17494:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.141.  .2(raebu 17495:20):     my $ua = LWP::UserAgent->new;
                   17496:20):     $ua->timeout(5);
                   17497:20):     my $response=$ua->request($request);
1.1075.2.135  raeburn  17498:     if ($response->is_success()) {
                   17499:         my $secpolicy = lc($response->header('content-security-policy'));
                   17500:         my $xframeop = lc($response->header('x-frame-options'));
                   17501:         $secpolicy =~ s/^\s+|\s+$//g;
                   17502:         $xframeop =~ s/^\s+|\s+$//g;
                   17503:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17504:             my $remotehost = $remprotocol.'://'.$remhost;
                   17505:             my ($origin,$protocol,$port);
                   17506:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17507:                 $port = $ENV{'SERVER_PORT'};
                   17508:             } else {
                   17509:                 $port = 80;
                   17510:             }
                   17511:             if ($absolute eq '') {
                   17512:                 $protocol = 'http:';
                   17513:                 if ($port == 443) {
                   17514:                     $protocol = 'https:';
                   17515:                 }
                   17516:                 $origin = $protocol.'//'.lc($hostname);
                   17517:             } else {
                   17518:                 $origin = lc($absolute);
                   17519:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17520:             }
                   17521:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17522:                 my $framepolicy = $1;
                   17523:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17524:                 my @policies = split(/\s+/,$framepolicy);
                   17525:                 if (@policies) {
                   17526:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17527:                         $uselink = 1;
                   17528:                     } else {
                   17529:                         $uselink = 1;
                   17530:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17531:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17532:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17533:                             undef($uselink);
                   17534:                         }
                   17535:                         if ($uselink) {
                   17536:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17537:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17538:                                     undef($uselink);
                   17539:                                 }
                   17540:                             }
                   17541:                         }
                   17542:                         if ($uselink) {
                   17543:                             my @possok;
                   17544:                             if ($ip ne '') {
                   17545:                                 push(@possok,$ip);
                   17546:                             }
                   17547:                             my $hoststr = '';
                   17548:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17549:                                 if ($hoststr eq '') {
                   17550:                                     $hoststr = $part;
                   17551:                                 } else {
                   17552:                                     $hoststr = "$part.$hoststr";
                   17553:                                 }
                   17554:                                 if ($hoststr eq $hostname) {
                   17555:                                     push(@possok,$hostname);
                   17556:                                 } else {
                   17557:                                     push(@possok,"*.$hoststr");
                   17558:                                 }
                   17559:                             }
                   17560:                             if (@possok) {
                   17561:                                 foreach my $poss (@possok) {
                   17562:                                     last if (!$uselink);
                   17563:                                     foreach my $policy (@policies) {
                   17564:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17565:                                             undef($uselink);
                   17566:                                             last;
                   17567:                                         }
                   17568:                                     }
                   17569:                                 }
                   17570:                             }
                   17571:                         }
                   17572:                     }
                   17573:                 }
                   17574:             } elsif ($xframeop ne '') {
                   17575:                 $uselink = 1;
                   17576:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17577:                 if (@policies) {
                   17578:                     unless (grep(/^deny$/,@policies)) {
                   17579:                         if ($origin ne '') {
                   17580:                             if (grep(/^sameorigin$/,@policies)) {
                   17581:                                 if ($remotehost eq $origin) {
                   17582:                                     undef($uselink);
                   17583:                                 }
                   17584:                             }
                   17585:                             if ($uselink) {
                   17586:                                 foreach my $policy (@policies) {
                   17587:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17588:                                         my $allowfrom = $1;
                   17589:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17590:                                             undef($uselink);
                   17591:                                             last;
                   17592:                                         }
                   17593:                                     }
                   17594:                                 }
                   17595:                             }
                   17596:                         }
                   17597:                     }
                   17598:                 }
                   17599:             }
                   17600:         }
                   17601:     }
                   17602:     if ($nocache) {
                   17603:         if ($cached) {
                   17604:             my $devalidate;
                   17605:             if ($uselink && !$result) {
                   17606:                 $devalidate = 1;
                   17607:             } elsif (!$uselink && $result) {
                   17608:                 $devalidate = 1;
                   17609:             }
                   17610:             if ($devalidate) {
                   17611:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17612:             }
                   17613:         }
                   17614:     } else {
                   17615:         if ($uselink) {
                   17616:             $result = 1;
                   17617:         } else {
                   17618:             $result = 0;
                   17619:         }
                   17620:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17621:     }
                   17622:     return $uselink;
                   17623: }
                   17624: 
1.112     bowersj2 17625: 1;
                   17626: __END__;
1.41      ng       17627: 

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