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

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.161.  .12(raeb    4:-23): # $Id: loncommon.pm,v 1.1075.2.161.2.11 2022/11/16 14:50:04 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.1075.2.161.  .7(raebu   64:22): use Apache::lonnavmaps();
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.161.  .1(raebu   86:21): use String::CRC32();
                     87:21): 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.143  raeburn   433:     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.143  raeburn   448:         if (courseadv == 'condition') {
                    449:             if (document.getElementById('courseadv')) {
                    450:                 courseadv = document.getElementById('courseadv').value;
                    451:             }
                    452:         }
                    453:         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.143  raeburn   485:    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.143  raeburn   496:        if ($courseadv eq 'only') {
                    497:            $callargs .= ",'',1,'$courseadv'";
                    498:        } elsif ($courseadv eq 'none') {
                    499:            $callargs .= ",'','','$courseadv'";
                    500:        } elsif ($courseadv eq 'condition') {
                    501:            $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.161.  .10(raeb  953:-22):    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    954:-22):    my $output='<select name="'.$name.'" '.$id.$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.1075.2.161.  .6(raebu 1224:22): =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
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: 
1.1075.2.161.  .6(raebu 1248:22): $links_target will optionally be set to a target (_top, _parent or _self).
                   1249:22): 
1.44      bowersj2 1250: =cut
                   1251: 
                   1252: sub help_open_topic {
1.1075.2.161.  .6(raebu 1253:22):     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1254:     $text = "" if (not defined $text);
1.44      bowersj2 1255:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1256:     $width = 500 if (not defined $width);
1.44      bowersj2 1257:     $height = 400 if (not defined $height);
                   1258:     my $filename = $topic;
                   1259:     $filename =~ s/ /_/g;
                   1260: 
1.48      bowersj2 1261:     my $template = "";
                   1262:     my $link;
1.572     banghart 1263:     
1.159     www      1264:     $topic=~s/\W/\_/g;
1.44      bowersj2 1265: 
1.572     banghart 1266:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1267:         if ($env{'browser.mobile'}) {
                   1268: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1269:         } else {
                   1270:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1271:         }
1.1037    www      1272:     } elsif ($stayOnPage eq 'popup') {
                   1273:         $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 1274:     } else {
1.48      bowersj2 1275: 	$link = "/adm/help/${filename}.hlp";
                   1276:     }
                   1277: 
                   1278:     # Add the text
1.1075.2.161.  .6(raebu 1279:22):     my $target = ' target="_top"';
                   1280:22):     if ($links_target) {
                   1281:22):         $target = ' target="'.$links_target.'"';
                   1282:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self')) {
                   1283:22):         $target = '';
                   1284:22):     }
1.755     neumanie 1285:     if ($text ne "") {	
1.763     bisitz   1286: 	$template.='<span class="LC_help_open_topic">'
1.1075.2.161.  .6(raebu 1287:22):                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1288:                   .$text.'</a>';
1.48      bowersj2 1289:     }
                   1290: 
1.763     bisitz   1291:     # (Always) Add the graphic
1.179     matthew  1292:     my $title = &mt('Online Help');
1.667     raeburn  1293:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1294:     if ($imgid ne '') {
                   1295:         $imgid = ' id="'.$imgid.'"';
                   1296:     }
1.1075.2.161.  .6(raebu 1297:22):     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1298:               .'<img src="'.$helpicon.'" border="0"'
                   1299:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1300:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1301:               .' /></a>';
                   1302:     if ($text ne "") {	
                   1303:         $template.='</span>';
                   1304:     }
1.44      bowersj2 1305:     return $template;
                   1306: 
1.106     bowersj2 1307: }
                   1308: 
                   1309: # This is a quicky function for Latex cheatsheet editing, since it 
                   1310: # appears in at least four places
                   1311: sub helpLatexCheatsheet {
1.1037    www      1312:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1313:     my $out;
1.106     bowersj2 1314:     my $addOther = '';
1.732     raeburn  1315:     if ($topic) {
1.1037    www      1316: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1317:     }
                   1318:     $out = '<span>' # Start cheatsheet
                   1319: 	  .$addOther
                   1320:           .'<span>'
1.1037    www      1321: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1322: 	  .'</span> <span>'
1.1037    www      1323: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1324: 	  .'</span>';
1.732     raeburn  1325:     unless ($not_author) {
1.763     bisitz   1326:         $out .= ' <span>'
1.1037    www      1327: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1328: 	       .'</span> <span>'
1.1075.2.78  raeburn  1329:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1330:                .'</span>';
1.732     raeburn  1331:     }
1.763     bisitz   1332:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1333:     return $out;
1.172     www      1334: }
                   1335: 
1.430     albertel 1336: sub general_help {
                   1337:     my $helptopic='Student_Intro';
                   1338:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1339: 	$helptopic='Authoring_Intro';
1.907     raeburn  1340:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1341: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1342:     } elsif ($env{'request.role'}=~/^dc/) {
                   1343:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1344:     }
                   1345:     return $helptopic;
                   1346: }
                   1347: 
                   1348: sub update_help_link {
                   1349:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1350:     my $origurl = $ENV{'REQUEST_URI'};
                   1351:     $origurl=~s|^/~|/priv/|;
                   1352:     my $timestamp = time;
                   1353:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1354:         $$datum = &escape($$datum);
                   1355:     }
                   1356: 
                   1357:     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";
                   1358:     my $output .= <<"ENDOUTPUT";
                   1359: <script type="text/javascript">
1.824     bisitz   1360: // <![CDATA[
1.430     albertel 1361: banner_link = '$banner_link';
1.824     bisitz   1362: // ]]>
1.430     albertel 1363: </script>
                   1364: ENDOUTPUT
                   1365:     return $output;
                   1366: }
                   1367: 
                   1368: # now just updates the help link and generates a blue icon
1.193     raeburn  1369: sub help_open_menu {
1.1075.2.161.  .6(raebu 1370:22):     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1371: 	= @_;    
1.949     droeschl 1372:     $stayOnPage = 1;
1.430     albertel 1373:     my $output;
                   1374:     if ($component_help) {
                   1375: 	if (!$text) {
                   1376: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1075.2.161.  .6(raebu 1377:22): 				       $width,$height,'',$links_target);
1.430     albertel 1378: 	} else {
                   1379: 	    my $help_text;
                   1380: 	    $help_text=&unescape($topic);
                   1381: 	    $output='<table><tr><td>'.
                   1382: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1075.2.161.  .6(raebu 1383:22): 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1384: 	}
                   1385:     }
                   1386:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1387:     return $output.$banner_link;
                   1388: }
                   1389: 
                   1390: sub top_nav_help {
1.1075.2.158  raeburn  1391:     my ($text,$linkattr) = @_;
1.436     albertel 1392:     $text = &mt($text);
1.1075.2.60  raeburn  1393:     my $stay_on_page;
                   1394:     unless ($env{'environment.remote'} eq 'on') {
                   1395:         $stay_on_page = 1;
                   1396:     }
1.1075.2.61  raeburn  1397:     my ($link,$banner_link);
                   1398:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1399:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1400: 	                         : "javascript:helpMenu('open')";
                   1401:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1402:     }
1.201     raeburn  1403:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1404:     if ($link) {
                   1405:         return <<"END";
1.436     albertel 1406: $banner_link
1.1075.2.158  raeburn  1407: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1408: END
1.1075.2.61  raeburn  1409:     } else {
                   1410:         return '&nbsp;'.$text.'&nbsp;';
                   1411:     }
1.436     albertel 1412: }
                   1413: 
                   1414: sub help_menu_js {
1.1075.2.52  raeburn  1415:     my ($httphost) = @_;
1.949     droeschl 1416:     my $stayOnPage = 1;
1.436     albertel 1417:     my $width = 620;
                   1418:     my $height = 600;
1.430     albertel 1419:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1420:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1421:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1422:     my $start_page =
                   1423:         &Apache::loncommon::start_page('Help Menu', undef,
                   1424: 				       {'frameset'    => 1,
                   1425: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1426:                                         'use_absolute' => $httphost,
1.331     albertel 1427: 					'add_entries' => {
                   1428: 					    'border' => '0',
1.579     raeburn  1429: 					    'rows'   => "110,*",},});
1.331     albertel 1430:     my $end_page =
                   1431:         &Apache::loncommon::end_page({'frameset' => 1,
                   1432: 				      'js_ready' => 1,});
                   1433: 
1.436     albertel 1434:     my $template .= <<"ENDTEMPLATE";
                   1435: <script type="text/javascript">
1.877     bisitz   1436: // <![CDATA[
1.253     albertel 1437: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1438: var banner_link = '';
1.243     raeburn  1439: function helpMenu(target) {
                   1440:     var caller = this;
                   1441:     if (target == 'open') {
                   1442:         var newWindow = null;
                   1443:         try {
1.262     albertel 1444:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1445:         }
                   1446:         catch(error) {
                   1447:             writeHelp(caller);
                   1448:             return;
                   1449:         }
                   1450:         if (newWindow) {
                   1451:             caller = newWindow;
                   1452:         }
1.193     raeburn  1453:     }
1.243     raeburn  1454:     writeHelp(caller);
                   1455:     return;
                   1456: }
                   1457: function writeHelp(caller) {
1.1075.2.61  raeburn  1458:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1459:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1460:     caller.document.close();
                   1461:     caller.focus();
1.193     raeburn  1462: }
1.877     bisitz   1463: // END LON-CAPA Internal -->
1.253     albertel 1464: // ]]>
1.436     albertel 1465: </script>
1.193     raeburn  1466: ENDTEMPLATE
                   1467:     return $template;
                   1468: }
                   1469: 
1.172     www      1470: sub help_open_bug {
                   1471:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1472:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1473:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1474:     $text = "" if (not defined $text);
                   1475: 	$stayOnPage=1;
1.184     albertel 1476:     $width = 600 if (not defined $width);
                   1477:     $height = 600 if (not defined $height);
1.172     www      1478: 
                   1479:     $topic=~s/\W+/\+/g;
                   1480:     my $link='';
                   1481:     my $template='';
1.379     albertel 1482:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1483: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1484:     if (!$stayOnPage)
                   1485:     {
                   1486: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1487:     }
                   1488:     else
                   1489:     {
                   1490: 	$link = $url;
                   1491:     }
1.1075.2.161.  .6(raebu 1492:22): 
                   1493:22):     my $target = '_top';
                   1494:22):     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1495:22):         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1496:22):         $target = '_blank';
                   1497:22):     }
                   1498:22): 
1.172     www      1499:     # Add the text
                   1500:     if ($text ne "")
                   1501:     {
                   1502: 	$template .= 
                   1503:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1075.2.161.  .6(raebu 1504:22):   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1505:     }
                   1506: 
                   1507:     # Add the graphic
1.179     matthew  1508:     my $title = &mt('Report a Bug');
1.215     albertel 1509:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1510:     $template .= <<"ENDTEMPLATE";
1.1075.2.161.  .6(raebu 1511:22):  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1512: ENDTEMPLATE
                   1513:     if ($text ne '') { $template.='</td></tr></table>' };
                   1514:     return $template;
                   1515: 
                   1516: }
                   1517: 
                   1518: sub help_open_faq {
                   1519:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1520:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1521:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1522:     $text = "" if (not defined $text);
                   1523: 	$stayOnPage=1;
                   1524:     $width = 350 if (not defined $width);
                   1525:     $height = 400 if (not defined $height);
                   1526: 
                   1527:     $topic=~s/\W+/\+/g;
                   1528:     my $link='';
                   1529:     my $template='';
                   1530:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1531:     if (!$stayOnPage)
                   1532:     {
                   1533: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1534:     }
                   1535:     else
                   1536:     {
                   1537: 	$link = $url;
                   1538:     }
                   1539: 
                   1540:     # Add the text
                   1541:     if ($text ne "")
                   1542:     {
                   1543: 	$template .= 
1.173     www      1544:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1545:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1546:     }
                   1547: 
                   1548:     # Add the graphic
1.179     matthew  1549:     my $title = &mt('View the FAQ');
1.215     albertel 1550:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1551:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1552:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1553: ENDTEMPLATE
                   1554:     if ($text ne '') { $template.='</td></tr></table>' };
                   1555:     return $template;
                   1556: 
1.44      bowersj2 1557: }
1.37      matthew  1558: 
1.180     matthew  1559: ###############################################################
                   1560: ###############################################################
                   1561: 
1.45      matthew  1562: =pod
                   1563: 
1.648     raeburn  1564: =item * &change_content_javascript():
1.256     matthew  1565: 
                   1566: This and the next function allow you to create small sections of an
                   1567: otherwise static HTML page that you can update on the fly with
                   1568: Javascript, even in Netscape 4.
                   1569: 
                   1570: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1571: must be written to the HTML page once. It will prove the Javascript
                   1572: function "change(name, content)". Calling the change function with the
                   1573: name of the section 
                   1574: you want to update, matching the name passed to C<changable_area>, and
                   1575: the new content you want to put in there, will put the content into
                   1576: that area.
                   1577: 
                   1578: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1579: to contain room for the original contents. You need to "make space"
                   1580: for whatever changes you wish to make, and be B<sure> to check your
                   1581: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1582: it's adequate for updating a one-line status display, but little more.
                   1583: This script will set the space to 100% width, so you only need to
                   1584: worry about height in Netscape 4.
                   1585: 
                   1586: Modern browsers are much less limiting, and if you can commit to the
                   1587: user not using Netscape 4, this feature may be used freely with
                   1588: pretty much any HTML.
                   1589: 
                   1590: =cut
                   1591: 
                   1592: sub change_content_javascript {
                   1593:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1594:     if ($env{'browser.type'} eq 'netscape' &&
                   1595: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1596: 	return (<<NETSCAPE4);
                   1597: 	function change(name, content) {
                   1598: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1599: 	    doc.open();
                   1600: 	    doc.write(content);
                   1601: 	    doc.close();
                   1602: 	}
                   1603: NETSCAPE4
                   1604:     } else {
                   1605: 	# Otherwise, we need to use semi-standards-compliant code
                   1606: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1607: 	# is really scary, and every useful browser supports it
                   1608: 	return (<<DOMBASED);
                   1609: 	function change(name, content) {
                   1610: 	    element = document.getElementById(name);
                   1611: 	    element.innerHTML = content;
                   1612: 	}
                   1613: DOMBASED
                   1614:     }
                   1615: }
                   1616: 
                   1617: =pod
                   1618: 
1.648     raeburn  1619: =item * &changable_area($name,$origContent):
1.256     matthew  1620: 
                   1621: This provides a "changable area" that can be modified on the fly via
                   1622: the Javascript code provided in C<change_content_javascript>. $name is
                   1623: the name you will use to reference the area later; do not repeat the
                   1624: same name on a given HTML page more then once. $origContent is what
                   1625: the area will originally contain, which can be left blank.
                   1626: 
                   1627: =cut
                   1628: 
                   1629: sub changable_area {
                   1630:     my ($name, $origContent) = @_;
                   1631: 
1.258     albertel 1632:     if ($env{'browser.type'} eq 'netscape' &&
                   1633: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1634: 	# If this is netscape 4, we need to use the Layer tag
                   1635: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1636:     } else {
                   1637: 	return "<span id='$name'>$origContent</span>";
                   1638:     }
                   1639: }
                   1640: 
                   1641: =pod
                   1642: 
1.648     raeburn  1643: =item * &viewport_geometry_js 
1.590     raeburn  1644: 
                   1645: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1646: 
                   1647: =cut
                   1648: 
                   1649: 
                   1650: sub viewport_geometry_js { 
                   1651:     return <<"GEOMETRY";
                   1652: var Geometry = {};
                   1653: function init_geometry() {
                   1654:     if (Geometry.init) { return };
                   1655:     Geometry.init=1;
                   1656:     if (window.innerHeight) {
                   1657:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1658:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1659:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1660:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1661:     }
                   1662:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1663:         Geometry.getViewportHeight =
                   1664:             function() { return document.documentElement.clientHeight; };
                   1665:         Geometry.getViewportWidth =
                   1666:             function() { return document.documentElement.clientWidth; };
                   1667: 
                   1668:         Geometry.getHorizontalScroll =
                   1669:             function() { return document.documentElement.scrollLeft; };
                   1670:         Geometry.getVerticalScroll =
                   1671:             function() { return document.documentElement.scrollTop; };
                   1672:     }
                   1673:     else if (document.body.clientHeight) {
                   1674:         Geometry.getViewportHeight =
                   1675:             function() { return document.body.clientHeight; };
                   1676:         Geometry.getViewportWidth =
                   1677:             function() { return document.body.clientWidth; };
                   1678:         Geometry.getHorizontalScroll =
                   1679:             function() { return document.body.scrollLeft; };
                   1680:         Geometry.getVerticalScroll =
                   1681:             function() { return document.body.scrollTop; };
                   1682:     }
                   1683: }
                   1684: 
                   1685: GEOMETRY
                   1686: }
                   1687: 
                   1688: =pod
                   1689: 
1.648     raeburn  1690: =item * &viewport_size_js()
1.590     raeburn  1691: 
                   1692: 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. 
                   1693: 
                   1694: =cut
                   1695: 
                   1696: sub viewport_size_js {
                   1697:     my $geometry = &viewport_geometry_js();
                   1698:     return <<"DIMS";
                   1699: 
                   1700: $geometry
                   1701: 
                   1702: function getViewportDims(width,height) {
                   1703:     init_geometry();
                   1704:     width.value = Geometry.getViewportWidth();
                   1705:     height.value = Geometry.getViewportHeight();
                   1706:     return;
                   1707: }
                   1708: 
                   1709: DIMS
                   1710: }
                   1711: 
                   1712: =pod
                   1713: 
1.648     raeburn  1714: =item * &resize_textarea_js()
1.565     albertel 1715: 
                   1716: emits the needed javascript to resize a textarea to be as big as possible
                   1717: 
                   1718: creates a function resize_textrea that takes two IDs first should be
                   1719: the id of the element to resize, second should be the id of a div that
                   1720: surrounds everything that comes after the textarea, this routine needs
                   1721: to be attached to the <body> for the onload and onresize events.
                   1722: 
1.648     raeburn  1723: =back
1.565     albertel 1724: 
                   1725: =cut
                   1726: 
                   1727: sub resize_textarea_js {
1.590     raeburn  1728:     my $geometry = &viewport_geometry_js();
1.565     albertel 1729:     return <<"RESIZE";
                   1730:     <script type="text/javascript">
1.824     bisitz   1731: // <![CDATA[
1.590     raeburn  1732: $geometry
1.565     albertel 1733: 
1.588     albertel 1734: function getX(element) {
                   1735:     var x = 0;
                   1736:     while (element) {
                   1737: 	x += element.offsetLeft;
                   1738: 	element = element.offsetParent;
                   1739:     }
                   1740:     return x;
                   1741: }
                   1742: function getY(element) {
                   1743:     var y = 0;
                   1744:     while (element) {
                   1745: 	y += element.offsetTop;
                   1746: 	element = element.offsetParent;
                   1747:     }
                   1748:     return y;
                   1749: }
                   1750: 
                   1751: 
1.565     albertel 1752: function resize_textarea(textarea_id,bottom_id) {
                   1753:     init_geometry();
                   1754:     var textarea        = document.getElementById(textarea_id);
                   1755:     //alert(textarea);
                   1756: 
1.588     albertel 1757:     var textarea_top    = getY(textarea);
1.565     albertel 1758:     var textarea_height = textarea.offsetHeight;
                   1759:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1760:     var bottom_top      = getY(bottom);
1.565     albertel 1761:     var bottom_height   = bottom.offsetHeight;
                   1762:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1763:     var fudge           = 23;
1.565     albertel 1764:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1765:     if (new_height < 300) {
                   1766: 	new_height = 300;
                   1767:     }
                   1768:     textarea.style.height=new_height+'px';
                   1769: }
1.824     bisitz   1770: // ]]>
1.565     albertel 1771: </script>
                   1772: RESIZE
                   1773: 
                   1774: }
                   1775: 
1.1075.2.112  raeburn  1776: sub colorfuleditor_js {
                   1777:     return <<"COLORFULEDIT"
                   1778: <script type="text/javascript">
                   1779: // <![CDATA[>
                   1780:     function fold_box(curDepth, lastresource){
                   1781: 
                   1782:     // we need a list because there can be several blocks you need to fold in one tag
                   1783:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1784:     // but there is only one folding button per tag
                   1785:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1786: 
                   1787:         if(block.item(0).style.display == 'none'){
                   1788: 
                   1789:             foldbutton.value = '@{[&mt("Hide")]}';
                   1790:             for (i = 0; i < block.length; i++){
                   1791:                 block.item(i).style.display = '';
                   1792:             }
                   1793:         }else{
                   1794: 
                   1795:             foldbutton.value = '@{[&mt("Show")]}';
                   1796:             for (i = 0; i < block.length; i++){
                   1797:                 // block.item(i).style.visibility = 'collapse';
                   1798:                 block.item(i).style.display = 'none';
                   1799:             }
                   1800:         };
                   1801:         saveState(lastresource);
                   1802:     }
                   1803: 
                   1804:     function saveState (lastresource) {
                   1805: 
                   1806:         var tag_list = getTagList();
                   1807:         if(tag_list != null){
                   1808:             var timestamp = new Date().getTime();
                   1809:             var key = lastresource;
                   1810: 
                   1811:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1812:             // starting with timestamp
                   1813:             var value = timestamp+';';
                   1814: 
                   1815:             // building the list of key-value pairs
                   1816:             for(var i = 0; i < tag_list.length; i++){
                   1817:                 value += tag_list[i]+',';
                   1818:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1819:             }
                   1820: 
                   1821:             // only iterate whole storage if nothing to override
                   1822:             if(localStorage.getItem(key) == null){
                   1823: 
                   1824:                 // prevent storage from growing large
                   1825:                 if(localStorage.length > 50){
                   1826:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1827:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1828:                     var oldest_key;
                   1829: 
                   1830:                     for(var i = 1; i < localStorage.length; i++){
                   1831:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1832:                             oldest_key = localStorage.key(i);
                   1833:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1834:                         }
                   1835:                     }
                   1836:                     localStorage.removeItem(oldest_key);
                   1837:                 }
                   1838:             }
                   1839:             localStorage.setItem(key,value);
                   1840:         }
                   1841:     }
                   1842: 
                   1843:     // restore folding status of blocks (on page load)
                   1844:     function restoreState (lastresource) {
                   1845:         if(localStorage.getItem(lastresource) != null){
                   1846:             var key = lastresource;
                   1847:             var value = localStorage.getItem(key);
                   1848:             var regex_delTimestamp = /^\d+;/;
                   1849: 
                   1850:             value.replace(regex_delTimestamp, '');
                   1851: 
                   1852:             var valueArr = value.split(';');
                   1853:             var pairs;
                   1854:             var elements;
                   1855:             for (var i = 0; i < valueArr.length; i++){
                   1856:                 pairs = valueArr[i].split(',');
                   1857:                 elements = document.getElementsByName(pairs[0]);
                   1858: 
                   1859:                 for (var j = 0; j < elements.length; j++){
                   1860:                     elements[j].style.display = pairs[1];
                   1861:                     if (pairs[1] == "none"){
                   1862:                         var regex_id = /([_\\d]+)\$/;
                   1863:                         regex_id.exec(pairs[0]);
                   1864:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1865:                     }
                   1866:                 }
                   1867:             }
                   1868:         }
                   1869:     }
                   1870: 
                   1871:     function getTagList () {
                   1872: 
                   1873:         var stringToSearch = document.lonhomework.innerHTML;
                   1874: 
                   1875:         var ret = new Array();
                   1876:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1877:         var tag_list = stringToSearch.match(regex_findBlock);
                   1878: 
                   1879:         if(tag_list != null){
                   1880:             for(var i = 0; i < tag_list.length; i++){
                   1881:                 ret.push(tag_list[i].replace(/"/, ''));
                   1882:             }
                   1883:         }
                   1884:         return ret;
                   1885:     }
                   1886: 
                   1887:     function saveScrollPosition (resource) {
                   1888:         var tag_list = getTagList();
                   1889: 
                   1890:         // we dont always want to jump to the first block
                   1891:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1892:         if(\$(window).scrollTop() > 170){
                   1893:             if(tag_list != null){
                   1894:                 var result;
                   1895:                 for(var i = 0; i < tag_list.length; i++){
                   1896:                     if(isElementInViewport(tag_list[i])){
                   1897:                         result += tag_list[i]+';';
                   1898:                     }
                   1899:                 }
                   1900:                 sessionStorage.setItem('anchor_'+resource, result);
                   1901:             }
                   1902:         } else {
                   1903:             // we dont need to save zero, just delete the item to leave everything tidy
                   1904:             sessionStorage.removeItem('anchor_'+resource);
                   1905:         }
                   1906:     }
                   1907: 
                   1908:     function restoreScrollPosition(resource){
                   1909: 
                   1910:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1911:         if(elem != null){
                   1912:             var tag_list = elem.split(';');
                   1913:             var elem_list;
                   1914: 
                   1915:             for(var i = 0; i < tag_list.length; i++){
                   1916:                 elem_list = document.getElementsByName(tag_list[i]);
                   1917: 
                   1918:                 if(elem_list.length > 0){
                   1919:                     elem = elem_list[0];
                   1920:                     break;
                   1921:                 }
                   1922:             }
                   1923:             elem.scrollIntoView();
                   1924:         }
                   1925:     }
                   1926: 
                   1927:     function isElementInViewport(el) {
                   1928: 
                   1929:         // change to last element instead of first
                   1930:         var elem = document.getElementsByName(el);
                   1931:         var rect = elem[0].getBoundingClientRect();
                   1932: 
                   1933:         return (
                   1934:             rect.top >= 0 &&
                   1935:             rect.left >= 0 &&
                   1936:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1937:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1938:         );
                   1939:     }
                   1940: 
                   1941:     function autosize(depth){
                   1942:         var cmInst = window['cm'+depth];
                   1943:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1944: 
                   1945:         // is fixed size, switching to dynamic
                   1946:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1947:             cmInst.setSize("","auto");
                   1948:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1949:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1950: 
                   1951:         // is dynamic size, switching to fixed
                   1952:         } else {
                   1953:             cmInst.setSize("","300px");
                   1954:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1955:             sessionStorage.removeItem("autosized_"+depth);
                   1956:         }
                   1957:     }
                   1958: 
                   1959: 
                   1960: 
                   1961: // ]]>
                   1962: </script>
                   1963: COLORFULEDIT
                   1964: }
                   1965: 
                   1966: sub xmleditor_js {
                   1967:     return <<XMLEDIT
                   1968: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1969: <script type="text/javascript">
                   1970: // <![CDATA[>
                   1971: 
                   1972:     function saveScrollPosition (resource) {
                   1973: 
                   1974:         var scrollPos = \$(window).scrollTop();
                   1975:         sessionStorage.setItem(resource,scrollPos);
                   1976:     }
                   1977: 
                   1978:     function restoreScrollPosition(resource){
                   1979: 
                   1980:         var scrollPos = sessionStorage.getItem(resource);
                   1981:         \$(window).scrollTop(scrollPos);
                   1982:     }
                   1983: 
                   1984:     // unless internet explorer
                   1985:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1986: 
                   1987:         \$(document).ready(function() {
                   1988:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1989:         });
                   1990:     }
                   1991: 
                   1992:     // inserts text at cursor position into codemirror (xml editor only)
                   1993:     function insertText(text){
                   1994:         cm.focus();
                   1995:         var curPos = cm.getCursor();
                   1996:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1997:     }
                   1998: // ]]>
                   1999: </script>
                   2000: XMLEDIT
                   2001: }
                   2002: 
                   2003: sub insert_folding_button {
                   2004:     my $curDepth = $Apache::lonxml::curdepth;
                   2005:     my $lastresource = $env{'request.ambiguous'};
                   2006: 
                   2007:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   2008:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2009: }
                   2010: 
                   2011: 
1.565     albertel 2012: =pod
                   2013: 
1.256     matthew  2014: =head1 Excel and CSV file utility routines
                   2015: 
                   2016: =cut
                   2017: 
                   2018: ###############################################################
                   2019: ###############################################################
                   2020: 
                   2021: =pod
                   2022: 
1.1075.2.56  raeburn  2023: =over 4
                   2024: 
1.648     raeburn  2025: =item * &csv_translate($text) 
1.37      matthew  2026: 
1.185     www      2027: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2028: format.
                   2029: 
                   2030: =cut
                   2031: 
1.180     matthew  2032: ###############################################################
                   2033: ###############################################################
1.37      matthew  2034: sub csv_translate {
                   2035:     my $text = shift;
                   2036:     $text =~ s/\"/\"\"/g;
1.209     albertel 2037:     $text =~ s/\n/ /g;
1.37      matthew  2038:     return $text;
                   2039: }
1.180     matthew  2040: 
                   2041: ###############################################################
                   2042: ###############################################################
                   2043: 
                   2044: =pod
                   2045: 
1.648     raeburn  2046: =item * &define_excel_formats()
1.180     matthew  2047: 
                   2048: Define some commonly used Excel cell formats.
                   2049: 
                   2050: Currently supported formats:
                   2051: 
                   2052: =over 4
                   2053: 
                   2054: =item header
                   2055: 
                   2056: =item bold
                   2057: 
                   2058: =item h1
                   2059: 
                   2060: =item h2
                   2061: 
                   2062: =item h3
                   2063: 
1.256     matthew  2064: =item h4
                   2065: 
                   2066: =item i
                   2067: 
1.180     matthew  2068: =item date
                   2069: 
                   2070: =back
                   2071: 
                   2072: Inputs: $workbook
                   2073: 
                   2074: Returns: $format, a hash reference.
                   2075: 
1.1057    foxr     2076: 
1.180     matthew  2077: =cut
                   2078: 
                   2079: ###############################################################
                   2080: ###############################################################
                   2081: sub define_excel_formats {
                   2082:     my ($workbook) = @_;
                   2083:     my $format;
                   2084:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2085:                                                 bottom    => 1,
                   2086:                                                 align     => 'center');
                   2087:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2088:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2089:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2090:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2091:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2092:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2093:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2094:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2095:     return $format;
                   2096: }
                   2097: 
                   2098: ###############################################################
                   2099: ###############################################################
1.113     bowersj2 2100: 
                   2101: =pod
                   2102: 
1.648     raeburn  2103: =item * &create_workbook()
1.255     matthew  2104: 
                   2105: Create an Excel worksheet.  If it fails, output message on the
                   2106: request object and return undefs.
                   2107: 
                   2108: Inputs: Apache request object
                   2109: 
                   2110: Returns (undef) on failure, 
                   2111:     Excel worksheet object, scalar with filename, and formats 
                   2112:     from &Apache::loncommon::define_excel_formats on success
                   2113: 
                   2114: =cut
                   2115: 
                   2116: ###############################################################
                   2117: ###############################################################
                   2118: sub create_workbook {
                   2119:     my ($r) = @_;
                   2120:         #
                   2121:     # Create the excel spreadsheet
                   2122:     my $filename = '/prtspool/'.
1.258     albertel 2123:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2124:         time.'_'.rand(1000000000).'.xls';
                   2125:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2126:     if (! defined($workbook)) {
                   2127:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2128:         $r->print(
                   2129:             '<p class="LC_error">'
                   2130:            .&mt('Problems occurred in creating the new Excel file.')
                   2131:            .' '.&mt('This error has been logged.')
                   2132:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2133:            .'</p>'
                   2134:         );
1.255     matthew  2135:         return (undef);
                   2136:     }
                   2137:     #
1.1014    foxr     2138:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2139:     #
                   2140:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2141:     return ($workbook,$filename,$format);
                   2142: }
                   2143: 
                   2144: ###############################################################
                   2145: ###############################################################
                   2146: 
                   2147: =pod
                   2148: 
1.648     raeburn  2149: =item * &create_text_file()
1.113     bowersj2 2150: 
1.542     raeburn  2151: Create a file to write to and eventually make available to the user.
1.256     matthew  2152: If file creation fails, outputs an error message on the request object and 
                   2153: return undefs.
1.113     bowersj2 2154: 
1.256     matthew  2155: Inputs: Apache request object, and file suffix
1.113     bowersj2 2156: 
1.256     matthew  2157: Returns (undef) on failure, 
                   2158:     Filehandle and filename on success.
1.113     bowersj2 2159: 
                   2160: =cut
                   2161: 
1.256     matthew  2162: ###############################################################
                   2163: ###############################################################
                   2164: sub create_text_file {
                   2165:     my ($r,$suffix) = @_;
                   2166:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2167:     my $fh;
                   2168:     my $filename = '/prtspool/'.
1.258     albertel 2169:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2170:         time.'_'.rand(1000000000).'.'.$suffix;
                   2171:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2172:     if (! defined($fh)) {
                   2173:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2174:         $r->print(
                   2175:             '<p class="LC_error">'
                   2176:            .&mt('Problems occurred in creating the output file.')
                   2177:            .' '.&mt('This error has been logged.')
                   2178:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2179:            .'</p>'
                   2180:         );
1.113     bowersj2 2181:     }
1.256     matthew  2182:     return ($fh,$filename)
1.113     bowersj2 2183: }
                   2184: 
                   2185: 
1.256     matthew  2186: =pod 
1.113     bowersj2 2187: 
                   2188: =back
                   2189: 
                   2190: =cut
1.37      matthew  2191: 
                   2192: ###############################################################
1.33      matthew  2193: ##        Home server <option> list generating code          ##
                   2194: ###############################################################
1.35      matthew  2195: 
1.169     www      2196: # ------------------------------------------
                   2197: 
                   2198: sub domain_select {
                   2199:     my ($name,$value,$multiple)=@_;
                   2200:     my %domains=map { 
1.514     albertel 2201: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2202:     } &Apache::lonnet::all_domains();
1.169     www      2203:     if ($multiple) {
                   2204: 	$domains{''}=&mt('Any domain');
1.550     albertel 2205: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2206: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2207:     } else {
1.550     albertel 2208: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2209: 	return &select_form($name,$value,\%domains);
1.169     www      2210:     }
                   2211: }
                   2212: 
1.282     albertel 2213: #-------------------------------------------
                   2214: 
                   2215: =pod
                   2216: 
1.519     raeburn  2217: =head1 Routines for form select boxes
                   2218: 
                   2219: =over 4
                   2220: 
1.648     raeburn  2221: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2222: 
                   2223: Returns a string containing a <select> element int multiple mode
                   2224: 
                   2225: 
                   2226: Args:
                   2227:   $name - name of the <select> element
1.506     raeburn  2228:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2229:   $size - number of rows long the select element is
1.283     albertel 2230:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2231:           (shown text should already have been &mt())
1.506     raeburn  2232:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2233: 
1.282     albertel 2234: =cut
                   2235: 
                   2236: #-------------------------------------------
1.169     www      2237: sub multiple_select_form {
1.284     albertel 2238:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2239:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2240:     my $output='';
1.191     matthew  2241:     if (! defined($size)) {
                   2242:         $size = 4;
1.283     albertel 2243:         if (scalar(keys(%$hash))<4) {
                   2244:             $size = scalar(keys(%$hash));
1.191     matthew  2245:         }
                   2246:     }
1.734     bisitz   2247:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2248:     my @order;
1.506     raeburn  2249:     if (ref($order) eq 'ARRAY')  {
                   2250:         @order = @{$order};
                   2251:     } else {
                   2252:         @order = sort(keys(%$hash));
1.501     banghart 2253:     }
                   2254:     if (exists($$hash{'select_form_order'})) {
                   2255:         @order = @{$$hash{'select_form_order'}};
                   2256:     }
                   2257:         
1.284     albertel 2258:     foreach my $key (@order) {
1.356     albertel 2259:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2260:         $output.='selected="selected" ' if ($selected{$key});
                   2261:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2262:     }
                   2263:     $output.="</select>\n";
                   2264:     return $output;
                   2265: }
                   2266: 
1.88      www      2267: #-------------------------------------------
                   2268: 
                   2269: =pod
                   2270: 
1.1075.2.115  raeburn  2271: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2272: 
                   2273: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2274: allow a user to select options from a ref to a hash containing:
                   2275: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2276: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2277: An optional arg -- $readonly -- if true will cause the select form
                   2278: to be disabled, e.g., for the case where an instructor has a section-
                   2279: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2280: 
1.88      www      2281: See lonrights.pm for an example invocation and use.
                   2282: 
                   2283: =cut
                   2284: 
                   2285: #-------------------------------------------
                   2286: sub select_form {
1.1075.2.115  raeburn  2287:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2288:     return unless (ref($hashref) eq 'HASH');
                   2289:     if ($onchange) {
                   2290:         $onchange = ' onchange="'.$onchange.'"';
                   2291:     }
1.1075.2.129  raeburn  2292:     my $disabled;
                   2293:     if ($readonly) {
                   2294:         $disabled = ' disabled="disabled"';
                   2295:     }
                   2296:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2297:     my @keys;
1.970     raeburn  2298:     if (exists($hashref->{'select_form_order'})) {
                   2299: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2300:     } else {
1.970     raeburn  2301: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2302:     }
1.356     albertel 2303:     foreach my $key (@keys) {
                   2304:         $selectform.=
                   2305: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2306:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2307:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2308:     }
                   2309:     $selectform.="</select>";
                   2310:     return $selectform;
                   2311: }
                   2312: 
1.475     www      2313: # For display filters
                   2314: 
                   2315: sub display_filter {
1.1074    raeburn  2316:     my ($context) = @_;
1.475     www      2317:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2318:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2319:     my $phraseinput = 'hidden';
                   2320:     my $includeinput = 'hidden';
                   2321:     my ($checked,$includetypestext);
                   2322:     if ($env{'form.displayfilter'} eq 'containing') {
                   2323:         $phraseinput = 'text'; 
                   2324:         if ($context eq 'parmslog') {
                   2325:             $includeinput = 'checkbox';
                   2326:             if ($env{'form.includetypes'}) {
                   2327:                 $checked = ' checked="checked"';
                   2328:             }
                   2329:             $includetypestext = &mt('Include parameter types');
                   2330:         }
                   2331:     } else {
                   2332:         $includetypestext = '&nbsp;';
                   2333:     }
                   2334:     my ($additional,$secondid,$thirdid);
                   2335:     if ($context eq 'parmslog') {
                   2336:         $additional = 
                   2337:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2338:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2339:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2340:             '</label>';
                   2341:         $secondid = 'includetypes';
                   2342:         $thirdid = 'includetypestext';
                   2343:     }
                   2344:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2345:                                                     '$secondid','$thirdid')";
                   2346:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2347: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2348: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2349: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2350:            &mt('Filter: [_1]',
1.477     www      2351: 	   &select_form($env{'form.displayfilter'},
                   2352: 			'displayfilter',
1.970     raeburn  2353: 			{'currentfolder' => 'Current folder/page',
1.477     www      2354: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2355: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2356: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2357:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2358:                          '" />'.$additional;
                   2359: }
                   2360: 
                   2361: sub display_filter_js {
                   2362:     my $includetext = &mt('Include parameter types');
                   2363:     return <<"ENDJS";
                   2364:   
                   2365: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2366:     var firstType = 'hidden';
                   2367:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2368:         firstType = 'text';
                   2369:     }
                   2370:     firstObject = document.getElementById(firstid);
                   2371:     if (typeof(firstObject) == 'object') {
                   2372:         if (firstObject.type != firstType) {
                   2373:             changeInputType(firstObject,firstType);
                   2374:         }
                   2375:     }
                   2376:     if (context == 'parmslog') {
                   2377:         var secondType = 'hidden';
                   2378:         if (firstType == 'text') {
                   2379:             secondType = 'checkbox';
                   2380:         }
                   2381:         secondObject = document.getElementById(secondid);  
                   2382:         if (typeof(secondObject) == 'object') {
                   2383:             if (secondObject.type != secondType) {
                   2384:                 changeInputType(secondObject,secondType);
                   2385:             }
                   2386:         }
                   2387:         var textItem = document.getElementById(thirdid);
                   2388:         var currtext = textItem.innerHTML;
                   2389:         var newtext;
                   2390:         if (firstType == 'text') {
                   2391:             newtext = '$includetext';
                   2392:         } else {
                   2393:             newtext = '&nbsp;';
                   2394:         }
                   2395:         if (currtext != newtext) {
                   2396:             textItem.innerHTML = newtext;
                   2397:         }
                   2398:     }
                   2399:     return;
                   2400: }
                   2401: 
                   2402: function changeInputType(oldObject,newType) {
                   2403:     var newObject = document.createElement('input');
                   2404:     newObject.type = newType;
                   2405:     if (oldObject.size) {
                   2406:         newObject.size = oldObject.size;
                   2407:     }
                   2408:     if (oldObject.value) {
                   2409:         newObject.value = oldObject.value;
                   2410:     }
                   2411:     if (oldObject.name) {
                   2412:         newObject.name = oldObject.name;
                   2413:     }
                   2414:     if (oldObject.id) {
                   2415:         newObject.id = oldObject.id;
                   2416:     }
                   2417:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2418:     return;
                   2419: }
                   2420: 
                   2421: ENDJS
1.475     www      2422: }
                   2423: 
1.167     www      2424: sub gradeleveldescription {
                   2425:     my $gradelevel=shift;
                   2426:     my %gradelevels=(0 => 'Not specified',
                   2427: 		     1 => 'Grade 1',
                   2428: 		     2 => 'Grade 2',
                   2429: 		     3 => 'Grade 3',
                   2430: 		     4 => 'Grade 4',
                   2431: 		     5 => 'Grade 5',
                   2432: 		     6 => 'Grade 6',
                   2433: 		     7 => 'Grade 7',
                   2434: 		     8 => 'Grade 8',
                   2435: 		     9 => 'Grade 9',
                   2436: 		     10 => 'Grade 10',
                   2437: 		     11 => 'Grade 11',
                   2438: 		     12 => 'Grade 12',
                   2439: 		     13 => 'Grade 13',
                   2440: 		     14 => '100 Level',
                   2441: 		     15 => '200 Level',
                   2442: 		     16 => '300 Level',
                   2443: 		     17 => '400 Level',
                   2444: 		     18 => 'Graduate Level');
                   2445:     return &mt($gradelevels{$gradelevel});
                   2446: }
                   2447: 
1.163     www      2448: sub select_level_form {
                   2449:     my ($deflevel,$name)=@_;
                   2450:     unless ($deflevel) { $deflevel=0; }
1.167     www      2451:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2452:     for (my $i=0; $i<=18; $i++) {
                   2453:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2454:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2455:                 ">".&gradeleveldescription($i)."</option>\n";
                   2456:     }
                   2457:     $selectform.="</select>";
                   2458:     return $selectform;
1.163     www      2459: }
1.167     www      2460: 
1.35      matthew  2461: #-------------------------------------------
                   2462: 
1.45      matthew  2463: =pod
                   2464: 
1.1075.2.115  raeburn  2465: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2466: 
                   2467: Returns a string containing a <select name='$name' size='1'> form to 
                   2468: allow a user to select the domain to preform an operation in.  
                   2469: See loncreateuser.pm for an example invocation and use.
                   2470: 
1.90      www      2471: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2472: selected");
                   2473: 
1.743     raeburn  2474: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2475: 
1.910     raeburn  2476: 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.
                   2477: 
1.1075.2.36  raeburn  2478: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2479: 
1.1075.2.115  raeburn  2480: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2481: 
                   2482: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2483: 
1.35      matthew  2484: =cut
                   2485: 
                   2486: #-------------------------------------------
1.34      matthew  2487: sub select_dom_form {
1.1075.2.115  raeburn  2488:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2489:     if ($onchange) {
1.874     raeburn  2490:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2491:     }
1.1075.2.115  raeburn  2492:     if ($disabled) {
                   2493:         $disabled = ' disabled="disabled"';
                   2494:     }
1.1075.2.36  raeburn  2495:     my (@domains,%exclude);
1.910     raeburn  2496:     if (ref($incdoms) eq 'ARRAY') {
                   2497:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2498:     } else {
                   2499:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2500:     }
1.90      www      2501:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2502:     if (ref($excdoms) eq 'ARRAY') {
                   2503:         map { $exclude{$_} = 1; } @{$excdoms};
                   2504:     }
1.1075.2.115  raeburn  2505:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2506:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2507:         next if ($exclude{$dom});
1.356     albertel 2508:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2509:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2510:         if ($showdomdesc) {
                   2511:             if ($dom ne '') {
                   2512:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2513:                 if ($domdesc ne '') {
                   2514:                     $selectdomain .= ' ('.$domdesc.')';
                   2515:                 }
                   2516:             } 
                   2517:         }
                   2518:         $selectdomain .= "</option>\n";
1.34      matthew  2519:     }
                   2520:     $selectdomain.="</select>";
                   2521:     return $selectdomain;
                   2522: }
                   2523: 
1.35      matthew  2524: #-------------------------------------------
                   2525: 
1.45      matthew  2526: =pod
                   2527: 
1.648     raeburn  2528: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2529: 
1.586     raeburn  2530: input: 4 arguments (two required, two optional) - 
                   2531:     $domain - domain of new user
                   2532:     $name - name of form element
                   2533:     $default - Value of 'default' causes a default item to be first 
                   2534:                             option, and selected by default. 
                   2535:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2536:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2537: output: returns 2 items: 
1.586     raeburn  2538: (a) form element which contains either:
                   2539:    (i) <select name="$name">
                   2540:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2541:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2542:        </select>
                   2543:        form item if there are multiple library servers in $domain, or
                   2544:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2545:        if there is only one library server in $domain.
                   2546: 
                   2547: (b) number of library servers found.
                   2548: 
                   2549: See loncreateuser.pm for example of use.
1.35      matthew  2550: 
                   2551: =cut
                   2552: 
                   2553: #-------------------------------------------
1.586     raeburn  2554: sub home_server_form_item {
                   2555:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2556:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2557:     my $result;
                   2558:     my $numlib = keys(%servers);
                   2559:     if ($numlib > 1) {
                   2560:         $result .= '<select name="'.$name.'" />'."\n";
                   2561:         if ($default) {
1.804     bisitz   2562:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2563:                        '</option>'."\n";
                   2564:         }
                   2565:         foreach my $hostid (sort(keys(%servers))) {
                   2566:             $result.= '<option value="'.$hostid.'">'.
                   2567: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2568:         }
                   2569:         $result .= '</select>'."\n";
                   2570:     } elsif ($numlib == 1) {
                   2571:         my $hostid;
                   2572:         foreach my $item (keys(%servers)) {
                   2573:             $hostid = $item;
                   2574:         }
                   2575:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2576:                    $hostid.'" />';
                   2577:                    if (!$hide) {
                   2578:                        $result .= $hostid.' '.$servers{$hostid};
                   2579:                    }
                   2580:                    $result .= "\n";
                   2581:     } elsif ($default) {
                   2582:         $result .= '<input type="hidden" name="'.$name.
                   2583:                    '" value="default" />';
                   2584:                    if (!$hide) {
                   2585:                        $result .= &mt('default');
                   2586:                    }
                   2587:                    $result .= "\n";
1.33      matthew  2588:     }
1.586     raeburn  2589:     return ($result,$numlib);
1.33      matthew  2590: }
1.112     bowersj2 2591: 
                   2592: =pod
                   2593: 
1.534     albertel 2594: =back 
                   2595: 
1.112     bowersj2 2596: =cut
1.87      matthew  2597: 
                   2598: ###############################################################
1.112     bowersj2 2599: ##                  Decoding User Agent                      ##
1.87      matthew  2600: ###############################################################
                   2601: 
                   2602: =pod
                   2603: 
1.112     bowersj2 2604: =head1 Decoding the User Agent
                   2605: 
                   2606: =over 4
                   2607: 
                   2608: =item * &decode_user_agent()
1.87      matthew  2609: 
                   2610: Inputs: $r
                   2611: 
                   2612: Outputs:
                   2613: 
                   2614: =over 4
                   2615: 
1.112     bowersj2 2616: =item * $httpbrowser
1.87      matthew  2617: 
1.112     bowersj2 2618: =item * $clientbrowser
1.87      matthew  2619: 
1.112     bowersj2 2620: =item * $clientversion
1.87      matthew  2621: 
1.112     bowersj2 2622: =item * $clientmathml
1.87      matthew  2623: 
1.112     bowersj2 2624: =item * $clientunicode
1.87      matthew  2625: 
1.112     bowersj2 2626: =item * $clientos
1.87      matthew  2627: 
1.1075.2.42  raeburn  2628: =item * $clientmobile
                   2629: 
                   2630: =item * $clientinfo
                   2631: 
1.1075.2.77  raeburn  2632: =item * $clientosversion
                   2633: 
1.87      matthew  2634: =back
                   2635: 
1.157     matthew  2636: =back 
                   2637: 
1.87      matthew  2638: =cut
                   2639: 
                   2640: ###############################################################
                   2641: ###############################################################
                   2642: sub decode_user_agent {
1.247     albertel 2643:     my ($r)=@_;
1.87      matthew  2644:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2645:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2646:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2647:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2648:     my $clientbrowser='unknown';
                   2649:     my $clientversion='0';
                   2650:     my $clientmathml='';
                   2651:     my $clientunicode='0';
1.1075.2.42  raeburn  2652:     my $clientmobile=0;
1.1075.2.77  raeburn  2653:     my $clientosversion='';
1.87      matthew  2654:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2655:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2656: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2657: 	    $clientbrowser=$bname;
                   2658:             $httpbrowser=~/$vreg/i;
                   2659: 	    $clientversion=$1;
                   2660:             $clientmathml=($clientversion>=$minv);
                   2661:             $clientunicode=($clientversion>=$univ);
                   2662: 	}
                   2663:     }
                   2664:     my $clientos='unknown';
1.1075.2.42  raeburn  2665:     my $clientinfo;
1.87      matthew  2666:     if (($httpbrowser=~/linux/i) ||
                   2667:         ($httpbrowser=~/unix/i) ||
                   2668:         ($httpbrowser=~/ux/i) ||
                   2669:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2670:     if (($httpbrowser=~/vax/i) ||
                   2671:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2672:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2673:     if (($httpbrowser=~/mac/i) ||
                   2674:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2675:     if ($httpbrowser=~/win/i) {
                   2676:         $clientos='win';
                   2677:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2678:             $clientosversion = $1;
                   2679:         }
                   2680:     }
1.87      matthew  2681:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2682:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2683:         $clientmobile=lc($1);
                   2684:     }
                   2685:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2686:         $clientinfo = 'firefox-'.$1;
                   2687:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2688:         $clientinfo = 'chromeframe-'.$1;
                   2689:     }
1.87      matthew  2690:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2691:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2692:             $clientosversion);
1.87      matthew  2693: }
                   2694: 
1.32      matthew  2695: ###############################################################
                   2696: ##    Authentication changing form generation subroutines    ##
                   2697: ###############################################################
                   2698: ##
                   2699: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2700: ## hash, and have reasonable default values.
                   2701: ##
                   2702: ##    formname = the name given in the <form> tag.
1.35      matthew  2703: #-------------------------------------------
                   2704: 
1.45      matthew  2705: =pod
                   2706: 
1.112     bowersj2 2707: =head1 Authentication Routines
                   2708: 
                   2709: =over 4
                   2710: 
1.648     raeburn  2711: =item * &authform_xxxxxx()
1.35      matthew  2712: 
                   2713: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2714: handle some of the conveniences required for authentication forms.  
                   2715: This is not an optimal method, but it works.  
                   2716: 
                   2717: =over 4
                   2718: 
1.112     bowersj2 2719: =item * authform_header
1.35      matthew  2720: 
1.112     bowersj2 2721: =item * authform_authorwarning
1.35      matthew  2722: 
1.112     bowersj2 2723: =item * authform_nochange
1.35      matthew  2724: 
1.112     bowersj2 2725: =item * authform_kerberos
1.35      matthew  2726: 
1.112     bowersj2 2727: =item * authform_internal
1.35      matthew  2728: 
1.112     bowersj2 2729: =item * authform_filesystem
1.35      matthew  2730: 
                   2731: =back
                   2732: 
1.648     raeburn  2733: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2734: 
1.35      matthew  2735: =cut
                   2736: 
                   2737: #-------------------------------------------
1.32      matthew  2738: sub authform_header{  
                   2739:     my %in = (
                   2740:         formname => 'cu',
1.80      albertel 2741:         kerb_def_dom => '',
1.32      matthew  2742:         @_,
                   2743:     );
                   2744:     $in{'formname'} = 'document.' . $in{'formname'};
                   2745:     my $result='';
1.80      albertel 2746: 
                   2747: #---------------------------------------------- Code for upper case translation
                   2748:     my $Javascript_toUpperCase;
                   2749:     unless ($in{kerb_def_dom}) {
                   2750:         $Javascript_toUpperCase =<<"END";
                   2751:         switch (choice) {
                   2752:            case 'krb': currentform.elements[choicearg].value =
                   2753:                currentform.elements[choicearg].value.toUpperCase();
                   2754:                break;
                   2755:            default:
                   2756:         }
                   2757: END
                   2758:     } else {
                   2759:         $Javascript_toUpperCase = "";
                   2760:     }
                   2761: 
1.165     raeburn  2762:     my $radioval = "'nochange'";
1.591     raeburn  2763:     if (defined($in{'curr_authtype'})) {
                   2764:         if ($in{'curr_authtype'} ne '') {
                   2765:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2766:         }
1.174     matthew  2767:     }
1.165     raeburn  2768:     my $argfield = 'null';
1.591     raeburn  2769:     if (defined($in{'mode'})) {
1.165     raeburn  2770:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2771:             if (defined($in{'curr_autharg'})) {
                   2772:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2773:                     $argfield = "'$in{'curr_autharg'}'";
                   2774:                 }
                   2775:             }
                   2776:         }
                   2777:     }
                   2778: 
1.32      matthew  2779:     $result.=<<"END";
                   2780: var current = new Object();
1.165     raeburn  2781: current.radiovalue = $radioval;
                   2782: current.argfield = $argfield;
1.32      matthew  2783: 
                   2784: function changed_radio(choice,currentform) {
                   2785:     var choicearg = choice + 'arg';
                   2786:     // If a radio button in changed, we need to change the argfield
                   2787:     if (current.radiovalue != choice) {
                   2788:         current.radiovalue = choice;
                   2789:         if (current.argfield != null) {
                   2790:             currentform.elements[current.argfield].value = '';
                   2791:         }
                   2792:         if (choice == 'nochange') {
                   2793:             current.argfield = null;
                   2794:         } else {
                   2795:             current.argfield = choicearg;
                   2796:             switch(choice) {
                   2797:                 case 'krb': 
                   2798:                     currentform.elements[current.argfield].value = 
                   2799:                         "$in{'kerb_def_dom'}";
                   2800:                 break;
                   2801:               default:
                   2802:                 break;
                   2803:             }
                   2804:         }
                   2805:     }
                   2806:     return;
                   2807: }
1.22      www      2808: 
1.32      matthew  2809: function changed_text(choice,currentform) {
                   2810:     var choicearg = choice + 'arg';
                   2811:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2812:         $Javascript_toUpperCase
1.32      matthew  2813:         // clear old field
                   2814:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2815:             currentform.elements[current.argfield].value = '';
                   2816:         }
                   2817:         current.argfield = choicearg;
                   2818:     }
                   2819:     set_auth_radio_buttons(choice,currentform);
                   2820:     return;
1.20      www      2821: }
1.32      matthew  2822: 
                   2823: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2824:     var numauthchoices = currentform.login.length;
                   2825:     if (typeof numauthchoices  == "undefined") {
                   2826:         return;
                   2827:     } 
1.32      matthew  2828:     var i=0;
1.986     raeburn  2829:     while (i < numauthchoices) {
1.32      matthew  2830:         if (currentform.login[i].value == newvalue) { break; }
                   2831:         i++;
                   2832:     }
1.986     raeburn  2833:     if (i == numauthchoices) {
1.32      matthew  2834:         return;
                   2835:     }
                   2836:     current.radiovalue = newvalue;
                   2837:     currentform.login[i].checked = true;
                   2838:     return;
                   2839: }
                   2840: END
                   2841:     return $result;
                   2842: }
                   2843: 
1.1075.2.20  raeburn  2844: sub authform_authorwarning {
1.32      matthew  2845:     my $result='';
1.144     matthew  2846:     $result='<i>'.
                   2847:         &mt('As a general rule, only authors or co-authors should be '.
                   2848:             'filesystem authenticated '.
                   2849:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2850:     return $result;
                   2851: }
                   2852: 
1.1075.2.20  raeburn  2853: sub authform_nochange {
1.32      matthew  2854:     my %in = (
                   2855:               formname => 'document.cu',
                   2856:               kerb_def_dom => 'MSU.EDU',
                   2857:               @_,
                   2858:           );
1.1075.2.20  raeburn  2859:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2860:     my $result;
1.1075.2.20  raeburn  2861:     if (!$authnum) {
                   2862:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2863:     } else {
                   2864:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2865:                   '<input type="radio" name="login" value="nochange" '.
                   2866:                   'checked="checked" onclick="'.
1.281     albertel 2867:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2868: 	    '</label>';
1.586     raeburn  2869:     }
1.32      matthew  2870:     return $result;
                   2871: }
                   2872: 
1.591     raeburn  2873: sub authform_kerberos {
1.32      matthew  2874:     my %in = (
                   2875:               formname => 'document.cu',
                   2876:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2877:               kerb_def_auth => 'krb4',
1.32      matthew  2878:               @_,
                   2879:               );
1.586     raeburn  2880:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2881:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2882:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2883:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2884:        $check5 = ' checked="checked"';
1.80      albertel 2885:     } else {
1.772     bisitz   2886:        $check4 = ' checked="checked"';
1.80      albertel 2887:     }
1.1075.2.117  raeburn  2888:     if ($in{'readonly'}) {
                   2889:         $disabled = ' disabled="disabled"';
                   2890:     }
1.165     raeburn  2891:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2892:     if (defined($in{'curr_authtype'})) {
                   2893:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2894:             $krbcheck = ' checked="checked"';
1.623     raeburn  2895:             if (defined($in{'mode'})) {
                   2896:                 if ($in{'mode'} eq 'modifyuser') {
                   2897:                     $krbcheck = '';
                   2898:                 }
                   2899:             }
1.591     raeburn  2900:             if (defined($in{'curr_kerb_ver'})) {
                   2901:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2902:                     $check5 = ' checked="checked"';
1.591     raeburn  2903:                     $check4 = '';
                   2904:                 } else {
1.772     bisitz   2905:                     $check4 = ' checked="checked"';
1.591     raeburn  2906:                     $check5 = '';
                   2907:                 }
1.586     raeburn  2908:             }
1.591     raeburn  2909:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2910:                 $krbarg = $in{'curr_autharg'};
                   2911:             }
1.586     raeburn  2912:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2913:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2914:                     $result = 
                   2915:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2916:         $in{'curr_autharg'},$krbver);
                   2917:                 } else {
                   2918:                     $result =
                   2919:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2920:                 }
                   2921:                 return $result; 
                   2922:             }
                   2923:         }
                   2924:     } else {
                   2925:         if ($authnum == 1) {
1.784     bisitz   2926:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2927:         }
                   2928:     }
1.586     raeburn  2929:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2930:         return;
1.587     raeburn  2931:     } elsif ($authtype eq '') {
1.591     raeburn  2932:         if (defined($in{'mode'})) {
1.587     raeburn  2933:             if ($in{'mode'} eq 'modifycourse') {
                   2934:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2935:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2936:                 }
                   2937:             }
                   2938:         }
1.586     raeburn  2939:     }
                   2940:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2941:     if ($authtype eq '') {
                   2942:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2943:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2944:                     $krbcheck.$disabled.' />';
1.586     raeburn  2945:     }
                   2946:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2947:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2948:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2949:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2950:          $in{'curr_authtype'} eq 'krb4')) {
                   2951:         $result .= &mt
1.144     matthew  2952:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2953:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2954:          '<label>'.$authtype,
1.281     albertel 2955:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2956:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2957:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2958:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2959:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2960: 	 '</label>');
1.586     raeburn  2961:     } elsif ($can_assign{'krb4'}) {
                   2962:         $result .= &mt
                   2963:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2964:          '[_3] Version 4 [_4]',
                   2965:          '<label>'.$authtype,
                   2966:          '</label><input type="text" size="10" name="krbarg" '.
                   2967:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2968:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2969:          '<label><input type="hidden" name="krbver" value="4" />',
                   2970:          '</label>');
                   2971:     } elsif ($can_assign{'krb5'}) {
                   2972:         $result .= &mt
                   2973:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2974:          '[_3] Version 5 [_4]',
                   2975:          '<label>'.$authtype,
                   2976:          '</label><input type="text" size="10" name="krbarg" '.
                   2977:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2978:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2979:          '<label><input type="hidden" name="krbver" value="5" />',
                   2980:          '</label>');
                   2981:     }
1.32      matthew  2982:     return $result;
                   2983: }
                   2984: 
1.1075.2.20  raeburn  2985: sub authform_internal {
1.586     raeburn  2986:     my %in = (
1.32      matthew  2987:                 formname => 'document.cu',
                   2988:                 kerb_def_dom => 'MSU.EDU',
                   2989:                 @_,
                   2990:                 );
1.1075.2.117  raeburn  2991:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2992:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2993:     if ($in{'readonly'}) {
                   2994:         $disabled = ' disabled="disabled"';
                   2995:     }
1.591     raeburn  2996:     if (defined($in{'curr_authtype'})) {
                   2997:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2998:             if ($can_assign{'int'}) {
1.772     bisitz   2999:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3000:                 if (defined($in{'mode'})) {
                   3001:                     if ($in{'mode'} eq 'modifyuser') {
                   3002:                         $intcheck = '';
                   3003:                     }
                   3004:                 }
1.591     raeburn  3005:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3006:                     $intarg = $in{'curr_autharg'};
                   3007:                 }
                   3008:             } else {
                   3009:                 $result = &mt('Currently internally authenticated.');
                   3010:                 return $result;
1.165     raeburn  3011:             }
                   3012:         }
1.586     raeburn  3013:     } else {
                   3014:         if ($authnum == 1) {
1.784     bisitz   3015:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3016:         }
                   3017:     }
                   3018:     if (!$can_assign{'int'}) {
                   3019:         return;
1.587     raeburn  3020:     } elsif ($authtype eq '') {
1.591     raeburn  3021:         if (defined($in{'mode'})) {
1.587     raeburn  3022:             if ($in{'mode'} eq 'modifycourse') {
                   3023:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3024:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3025:                 }
                   3026:             }
                   3027:         }
1.165     raeburn  3028:     }
1.586     raeburn  3029:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3030:     if ($authtype eq '') {
                   3031:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3032:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3033:     }
1.605     bisitz   3034:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3035:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3036:     $result = &mt
1.144     matthew  3037:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3038:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3039:     $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  3040:     return $result;
                   3041: }
                   3042: 
1.1075.2.20  raeburn  3043: sub authform_local {
1.32      matthew  3044:     my %in = (
                   3045:               formname => 'document.cu',
                   3046:               kerb_def_dom => 'MSU.EDU',
                   3047:               @_,
                   3048:               );
1.1075.2.117  raeburn  3049:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3050:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3051:     if ($in{'readonly'}) {
                   3052:         $disabled = ' disabled="disabled"';
                   3053:     }
1.591     raeburn  3054:     if (defined($in{'curr_authtype'})) {
                   3055:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3056:             if ($can_assign{'loc'}) {
1.772     bisitz   3057:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3058:                 if (defined($in{'mode'})) {
                   3059:                     if ($in{'mode'} eq 'modifyuser') {
                   3060:                         $loccheck = '';
                   3061:                     }
                   3062:                 }
1.591     raeburn  3063:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3064:                     $locarg = $in{'curr_autharg'};
                   3065:                 }
                   3066:             } else {
                   3067:                 $result = &mt('Currently using local (institutional) authentication.');
                   3068:                 return $result;
1.165     raeburn  3069:             }
                   3070:         }
1.586     raeburn  3071:     } else {
                   3072:         if ($authnum == 1) {
1.784     bisitz   3073:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3074:         }
                   3075:     }
                   3076:     if (!$can_assign{'loc'}) {
                   3077:         return;
1.587     raeburn  3078:     } elsif ($authtype eq '') {
1.591     raeburn  3079:         if (defined($in{'mode'})) {
1.587     raeburn  3080:             if ($in{'mode'} eq 'modifycourse') {
                   3081:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3082:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3083:                 }
                   3084:             }
                   3085:         }
1.165     raeburn  3086:     }
1.586     raeburn  3087:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3088:     if ($authtype eq '') {
                   3089:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3090:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3091:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3092:     }
                   3093:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3094:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3095:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3096:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3097:     return $result;
                   3098: }
                   3099: 
1.1075.2.20  raeburn  3100: sub authform_filesystem {
1.32      matthew  3101:     my %in = (
                   3102:               formname => 'document.cu',
                   3103:               kerb_def_dom => 'MSU.EDU',
                   3104:               @_,
                   3105:               );
1.1075.2.117  raeburn  3106:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3107:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3108:     if ($in{'readonly'}) {
                   3109:         $disabled = ' disabled="disabled"';
                   3110:     }
1.591     raeburn  3111:     if (defined($in{'curr_authtype'})) {
                   3112:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3113:             if ($can_assign{'fsys'}) {
1.772     bisitz   3114:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3115:                 if (defined($in{'mode'})) {
                   3116:                     if ($in{'mode'} eq 'modifyuser') {
                   3117:                         $fsyscheck = '';
                   3118:                     }
                   3119:                 }
1.586     raeburn  3120:             } else {
                   3121:                 $result = &mt('Currently Filesystem Authenticated.');
                   3122:                 return $result;
                   3123:             }           
                   3124:         }
                   3125:     } else {
                   3126:         if ($authnum == 1) {
1.784     bisitz   3127:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3128:         }
                   3129:     }
                   3130:     if (!$can_assign{'fsys'}) {
                   3131:         return;
1.587     raeburn  3132:     } elsif ($authtype eq '') {
1.591     raeburn  3133:         if (defined($in{'mode'})) {
1.587     raeburn  3134:             if ($in{'mode'} eq 'modifycourse') {
                   3135:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3136:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3137:                 }
                   3138:             }
                   3139:         }
1.586     raeburn  3140:     }
                   3141:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3142:     if ($authtype eq '') {
                   3143:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3144:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3145:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3146:     }
1.1075.2.158  raeburn  3147:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3148:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3149:     $result = &mt
1.144     matthew  3150:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3151:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3152:     return $result;
                   3153: }
                   3154: 
1.586     raeburn  3155: sub get_assignable_auth {
                   3156:     my ($dom) = @_;
                   3157:     if ($dom eq '') {
                   3158:         $dom = $env{'request.role.domain'};
                   3159:     }
                   3160:     my %can_assign = (
                   3161:                           krb4 => 1,
                   3162:                           krb5 => 1,
                   3163:                           int  => 1,
                   3164:                           loc  => 1,
                   3165:                      );
                   3166:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3167:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3168:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3169:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3170:             my $context;
                   3171:             if ($env{'request.role'} =~ /^au/) {
                   3172:                 $context = 'author';
1.1075.2.117  raeburn  3173:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3174:                 $context = 'domain';
                   3175:             } elsif ($env{'request.course.id'}) {
                   3176:                 $context = 'course';
                   3177:             }
                   3178:             if ($context) {
                   3179:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3180:                    %can_assign = %{$authhash->{$context}}; 
                   3181:                 }
                   3182:             }
                   3183:         }
                   3184:     }
                   3185:     my $authnum = 0;
                   3186:     foreach my $key (keys(%can_assign)) {
                   3187:         if ($can_assign{$key}) {
                   3188:             $authnum ++;
                   3189:         }
                   3190:     }
                   3191:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3192:         $authnum --;
                   3193:     }
                   3194:     return ($authnum,%can_assign);
                   3195: }
                   3196: 
1.1075.2.137  raeburn  3197: sub check_passwd_rules {
                   3198:     my ($domain,$plainpass) = @_;
                   3199:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3200:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3201:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3202:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3203:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3204:             if ($passwdconf{'min'} > $min) {
                   3205:                 $min = $passwdconf{'min'};
                   3206:             }
1.1075.2.137  raeburn  3207:         }
                   3208:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3209:             $max = $passwdconf{'max'};
                   3210:         }
                   3211:         @chars = @{$passwdconf{'chars'}};
                   3212:     }
                   3213:     if (($min) && (length($plainpass) < $min)) {
                   3214:         push(@brokerule,'min');
                   3215:     }
                   3216:     if (($max) && (length($plainpass) > $max)) {
                   3217:         push(@brokerule,'max');
                   3218:     }
                   3219:     if (@chars) {
                   3220:         my %rules;
                   3221:         map { $rules{$_} = 1; } @chars;
                   3222:         if ($rules{'uc'}) {
                   3223:             unless ($plainpass =~ /[A-Z]/) {
                   3224:                 push(@brokerule,'uc');
                   3225:             }
                   3226:         }
                   3227:         if ($rules{'lc'}) {
                   3228:             unless ($plainpass =~ /[a-z]/) {
                   3229:                 push(@brokerule,'lc');
                   3230:             }
                   3231:         }
                   3232:         if ($rules{'num'}) {
                   3233:             unless ($plainpass =~ /\d/) {
                   3234:                 push(@brokerule,'num');
                   3235:             }
                   3236:         }
                   3237:         if ($rules{'spec'}) {
                   3238:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3239:                 push(@brokerule,'spec');
                   3240:             }
                   3241:         }
                   3242:     }
                   3243:     if (@brokerule) {
                   3244:         my %rulenames = &Apache::lonlocal::texthash(
                   3245:             uc   => 'At least one upper case letter',
                   3246:             lc   => 'At least one lower case letter',
                   3247:             num  => 'At least one number',
                   3248:             spec => 'At least one non-alphanumeric',
                   3249:         );
                   3250:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3251:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3252:         $rulenames{'num'} .= ': 0123456789';
                   3253:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3254:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3255:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3256:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3257:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3258:             if (grep(/^$rule$/,@brokerule)) {
                   3259:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3260:             }
                   3261:         }
                   3262:         $warning .= '</ul>';
                   3263:     }
                   3264:     if (wantarray) {
                   3265:         return @brokerule;
                   3266:     }
                   3267:     return $warning;
                   3268: }
                   3269: 
1.1075.2.161.  .5(raebu 3270:22): sub passwd_validation_js {
                   3271:22):     my ($currpasswdval,$domain,$context,$id) = @_;
                   3272:22):     my (%passwdconf,$alertmsg);
                   3273:22):     if ($context eq 'linkprot') {
                   3274:22):         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3275:22):         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3276:22):             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3277:22):                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3278:22):             }
                   3279:22):         }
                   3280:22):         if ($id eq 'add') {
                   3281:22):             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3282:22):         } elsif ($id =~ /^\d+$/) {
                   3283:22):             my $pos = $id+1;
                   3284:22):             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3285:22):         } else {
                   3286:22):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3287:22):         }
                   3288:22):     } else {
                   3289:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3290:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3291:22):     }
                   3292:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3293:22):     $numrules = 0;
                   3294:22):     $min = $Apache::lonnet::passwdmin;
                   3295:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3296:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3297:22):             if ($passwdconf{'min'} > $min) {
                   3298:22):                 $min = $passwdconf{'min'};
                   3299:22):             }
                   3300:22):         }
                   3301:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3302:22):             $max = $passwdconf{'max'};
                   3303:22):             $numrules ++;
                   3304:22):         }
                   3305:22):         @chars = @{$passwdconf{'chars'}};
                   3306:22):         if (@chars) {
                   3307:22):             $numrules ++;
                   3308:22):         }
                   3309:22):     }
                   3310:22):     if ($min > 0) {
                   3311:22):         $numrules ++;
                   3312:22):     }
                   3313:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3314:22):         if ($min) {
                   3315:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3316:22):         }
                   3317:22):         if ($max) {
                   3318:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3319:22):         }
                   3320:22):         my (@charalerts,@charrules);
                   3321:22):         if (@chars) {
                   3322:22):             if (grep(/^uc$/,@chars)) {
                   3323:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3324:22):                 push(@charrules,'uc');
                   3325:22):             }
                   3326:22):             if (grep(/^lc$/,@chars)) {
                   3327:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3328:22):                 push(@charrules,'lc');
                   3329:22):             }
                   3330:22):             if (grep(/^num$/,@chars)) {
                   3331:22):                 push(@charalerts,&mt('contain at least one number'));
                   3332:22):                 push(@charrules,'num');
                   3333:22):             }
                   3334:22):             if (grep(/^spec$/,@chars)) {
                   3335:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3336:22):                 push(@charrules,'spec');
                   3337:22):             }
                   3338:22):         }
                   3339:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3340:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3341:22):             if ($min) {
                   3342:22):                 $intargjs .= qq|
                   3343:22):             if (currpwval.length < $min) {
                   3344:22):                 rulesmsg += ' - $alert{min}';
                   3345:22):             }
                   3346:22): |;
                   3347:22):             }
                   3348:22):             if ($max) {
                   3349:22):                 $intargjs .= qq|
                   3350:22):             if (currpwval.length > $max) {
                   3351:22):                 rulesmsg += ' - $alert{max}';
                   3352:22):             }
                   3353:22): |;
                   3354:22):             }
                   3355:22):             if (@chars > 0) {
                   3356:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3357:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3358:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3359:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3360:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3361:22):                 my %rules;
                   3362:22):                 map { $rules{$_} = 1; } @chars;
                   3363:22):                 if ($rules{'uc'}) {
                   3364:22):                     $intargjs .= qq|
                   3365:22):             var ucRegExp = /[A-Z]/;
                   3366:22):             if (!ucRegExp.test(currpwval)) {
                   3367:22):                 brokerules.push('uc');
                   3368:22):             }
                   3369:22): |;
                   3370:22):                 }
                   3371:22):                 if ($rules{'lc'}) {
                   3372:22):                     $intargjs .= qq|
                   3373:22):             var lcRegExp = /[a-z]/;
                   3374:22):             if (!lcRegExp.test(currpwval)) {
                   3375:22):                 brokerules.push('lc');
                   3376:22):             }
                   3377:22): |;
                   3378:22):                 }
                   3379:22):                 if ($rules{'num'}) {
                   3380:22):                      $intargjs .= qq|
                   3381:22):             var numRegExp = /[0-9]/;
                   3382:22):             if (!numRegExp.test(currpwval)) {
                   3383:22):                 brokerules.push('num');
                   3384:22):             }
                   3385:22): |;
                   3386:22):                 }
                   3387:22):                 if ($rules{'spec'}) {
                   3388:22):                      $intargjs .= q|
                   3389:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3390:22):             if (!specRegExp.test(currpwval)) {
                   3391:22):                 brokerules.push('spec');
                   3392:22):             }
                   3393:22): |;
                   3394:22):                 }
                   3395:22):                 $intargjs .= qq|
                   3396:22):             if (brokerules.length > 0) {
                   3397:22):                 for (var i=0; i<brokerules.length; i++) {
                   3398:22):                     for (var j=0; j<charrules.length; j++) {
                   3399:22):                         if (brokerules[i] == charrules[j]) {
                   3400:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3401:22):                             break;
                   3402:22):                         }
                   3403:22):                     }
                   3404:22):                 }
                   3405:22):             }
                   3406:22): |;
                   3407:22):             }
                   3408:22):             $intargjs .= qq|
                   3409:22):             if (rulesmsg != '') {
                   3410:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3411:22):                 alert(rulesmsg);
                   3412:22):                 return false;
                   3413:22):             }
                   3414:22): |;
                   3415:22):     }
                   3416:22):     return ($numrules,$intargjs);
                   3417:22): }
                   3418:22): 
1.80      albertel 3419: ###############################################################
                   3420: ##    Get Kerberos Defaults for Domain                 ##
                   3421: ###############################################################
                   3422: ##
                   3423: ## Returns default kerberos version and an associated argument
                   3424: ## as listed in file domain.tab. If not listed, provides
                   3425: ## appropriate default domain and kerberos version.
                   3426: ##
                   3427: #-------------------------------------------
                   3428: 
                   3429: =pod
                   3430: 
1.648     raeburn  3431: =item * &get_kerberos_defaults()
1.80      albertel 3432: 
                   3433: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3434: version and domain. If not found, it defaults to version 4 and the 
                   3435: domain of the server.
1.80      albertel 3436: 
1.648     raeburn  3437: =over 4
                   3438: 
1.80      albertel 3439: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3440: 
1.648     raeburn  3441: =back
                   3442: 
                   3443: =back
                   3444: 
1.80      albertel 3445: =cut
                   3446: 
                   3447: #-------------------------------------------
                   3448: sub get_kerberos_defaults {
                   3449:     my $domain=shift;
1.641     raeburn  3450:     my ($krbdef,$krbdefdom);
                   3451:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3452:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3453:         $krbdef = $domdefaults{'auth_def'};
                   3454:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3455:     } else {
1.80      albertel 3456:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3457:         my $krbdefdom=$1;
                   3458:         $krbdefdom=~tr/a-z/A-Z/;
                   3459:         $krbdef = "krb4";
                   3460:     }
                   3461:     return ($krbdef,$krbdefdom);
                   3462: }
1.112     bowersj2 3463: 
1.32      matthew  3464: 
1.46      matthew  3465: ###############################################################
                   3466: ##                Thesaurus Functions                        ##
                   3467: ###############################################################
1.20      www      3468: 
1.46      matthew  3469: =pod
1.20      www      3470: 
1.112     bowersj2 3471: =head1 Thesaurus Functions
                   3472: 
                   3473: =over 4
                   3474: 
1.648     raeburn  3475: =item * &initialize_keywords()
1.46      matthew  3476: 
                   3477: Initializes the package variable %Keywords if it is empty.  Uses the
                   3478: package variable $thesaurus_db_file.
                   3479: 
                   3480: =cut
                   3481: 
                   3482: ###################################################
                   3483: 
                   3484: sub initialize_keywords {
                   3485:     return 1 if (scalar keys(%Keywords));
                   3486:     # If we are here, %Keywords is empty, so fill it up
                   3487:     #   Make sure the file we need exists...
                   3488:     if (! -e $thesaurus_db_file) {
                   3489:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3490:                                  " failed because it does not exist");
                   3491:         return 0;
                   3492:     }
                   3493:     #   Set up the hash as a database
                   3494:     my %thesaurus_db;
                   3495:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3496:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3497:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3498:                                  $thesaurus_db_file);
                   3499:         return 0;
                   3500:     } 
                   3501:     #  Get the average number of appearances of a word.
                   3502:     my $avecount = $thesaurus_db{'average.count'};
                   3503:     #  Put keywords (those that appear > average) into %Keywords
                   3504:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3505:         my ($count,undef) = split /:/,$data;
                   3506:         $Keywords{$word}++ if ($count > $avecount);
                   3507:     }
                   3508:     untie %thesaurus_db;
                   3509:     # Remove special values from %Keywords.
1.356     albertel 3510:     foreach my $value ('total.count','average.count') {
                   3511:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3512:   }
1.46      matthew  3513:     return 1;
                   3514: }
                   3515: 
                   3516: ###################################################
                   3517: 
                   3518: =pod
                   3519: 
1.648     raeburn  3520: =item * &keyword($word)
1.46      matthew  3521: 
                   3522: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3523: than the average number of times in the thesaurus database.  Calls 
                   3524: &initialize_keywords
                   3525: 
                   3526: =cut
                   3527: 
                   3528: ###################################################
1.20      www      3529: 
                   3530: sub keyword {
1.46      matthew  3531:     return if (!&initialize_keywords());
                   3532:     my $word=lc(shift());
                   3533:     $word=~s/\W//g;
                   3534:     return exists($Keywords{$word});
1.20      www      3535: }
1.46      matthew  3536: 
                   3537: ###############################################################
                   3538: 
                   3539: =pod 
1.20      www      3540: 
1.648     raeburn  3541: =item * &get_related_words()
1.46      matthew  3542: 
1.160     matthew  3543: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3544: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3545: will be returned.  The order of the words returned is determined by the
                   3546: database which holds them.
                   3547: 
                   3548: Uses global $thesaurus_db_file.
                   3549: 
1.1057    foxr     3550: 
1.46      matthew  3551: =cut
                   3552: 
                   3553: ###############################################################
                   3554: sub get_related_words {
                   3555:     my $keyword = shift;
                   3556:     my %thesaurus_db;
                   3557:     if (! -e $thesaurus_db_file) {
                   3558:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3559:                                  "failed because the file does not exist");
                   3560:         return ();
                   3561:     }
                   3562:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3563:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3564:         return ();
                   3565:     } 
                   3566:     my @Words=();
1.429     www      3567:     my $count=0;
1.46      matthew  3568:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3569: 	# The first element is the number of times
                   3570: 	# the word appears.  We do not need it now.
1.429     www      3571: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3572: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3573: 	my $threshold=$mostfrequentcount/10;
                   3574:         foreach my $possibleword (@RelatedWords) {
                   3575:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3576:             if ($wordcount>$threshold) {
                   3577: 		push(@Words,$word);
                   3578:                 $count++;
                   3579:                 if ($count>10) { last; }
                   3580: 	    }
1.20      www      3581:         }
                   3582:     }
1.46      matthew  3583:     untie %thesaurus_db;
                   3584:     return @Words;
1.14      harris41 3585: }
1.46      matthew  3586: 
1.112     bowersj2 3587: =pod
                   3588: 
                   3589: =back
                   3590: 
                   3591: =cut
1.61      www      3592: 
                   3593: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3594: =pod
                   3595: 
1.112     bowersj2 3596: =head1 User Name Functions
                   3597: 
                   3598: =over 4
                   3599: 
1.648     raeburn  3600: =item * &plainname($uname,$udom,$first)
1.81      albertel 3601: 
1.112     bowersj2 3602: Takes a users logon name and returns it as a string in
1.226     albertel 3603: "first middle last generation" form 
                   3604: if $first is set to 'lastname' then it returns it as
                   3605: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3606: 
                   3607: =cut
1.61      www      3608: 
1.295     www      3609: 
1.81      albertel 3610: ###############################################################
1.61      www      3611: sub plainname {
1.226     albertel 3612:     my ($uname,$udom,$first)=@_;
1.537     albertel 3613:     return if (!defined($uname) || !defined($udom));
1.295     www      3614:     my %names=&getnames($uname,$udom);
1.226     albertel 3615:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3616: 					  $names{'middlename'},
                   3617: 					  $names{'lastname'},
                   3618: 					  $names{'generation'},$first);
                   3619:     $name=~s/^\s+//;
1.62      www      3620:     $name=~s/\s+$//;
                   3621:     $name=~s/\s+/ /g;
1.353     albertel 3622:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3623:     return $name;
1.61      www      3624: }
1.66      www      3625: 
                   3626: # -------------------------------------------------------------------- Nickname
1.81      albertel 3627: =pod
                   3628: 
1.648     raeburn  3629: =item * &nickname($uname,$udom)
1.81      albertel 3630: 
                   3631: Gets a users name and returns it as a string as
                   3632: 
                   3633: "&quot;nickname&quot;"
1.66      www      3634: 
1.81      albertel 3635: if the user has a nickname or
                   3636: 
                   3637: "first middle last generation"
                   3638: 
                   3639: if the user does not
                   3640: 
                   3641: =cut
1.66      www      3642: 
                   3643: sub nickname {
                   3644:     my ($uname,$udom)=@_;
1.537     albertel 3645:     return if (!defined($uname) || !defined($udom));
1.295     www      3646:     my %names=&getnames($uname,$udom);
1.68      albertel 3647:     my $name=$names{'nickname'};
1.66      www      3648:     if ($name) {
                   3649:        $name='&quot;'.$name.'&quot;'; 
                   3650:     } else {
                   3651:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3652: 	     $names{'lastname'}.' '.$names{'generation'};
                   3653:        $name=~s/\s+$//;
                   3654:        $name=~s/\s+/ /g;
                   3655:     }
                   3656:     return $name;
                   3657: }
                   3658: 
1.295     www      3659: sub getnames {
                   3660:     my ($uname,$udom)=@_;
1.537     albertel 3661:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3662:     if ($udom eq 'public' && $uname eq 'public') {
                   3663: 	return ('lastname' => &mt('Public'));
                   3664:     }
1.295     www      3665:     my $id=$uname.':'.$udom;
                   3666:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3667:     if ($cached) {
                   3668: 	return %{$names};
                   3669:     } else {
                   3670: 	my %loadnames=&Apache::lonnet::get('environment',
                   3671:                     ['firstname','middlename','lastname','generation','nickname'],
                   3672: 					 $udom,$uname);
                   3673: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3674: 	return %loadnames;
                   3675:     }
                   3676: }
1.61      www      3677: 
1.542     raeburn  3678: # -------------------------------------------------------------------- getemails
1.648     raeburn  3679: 
1.542     raeburn  3680: =pod
                   3681: 
1.648     raeburn  3682: =item * &getemails($uname,$udom)
1.542     raeburn  3683: 
                   3684: Gets a user's email information and returns it as a hash with keys:
                   3685: notification, critnotification, permanentemail
                   3686: 
                   3687: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3688: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3689:  
1.648     raeburn  3690: 
1.542     raeburn  3691: =cut
                   3692: 
1.648     raeburn  3693: 
1.466     albertel 3694: sub getemails {
                   3695:     my ($uname,$udom)=@_;
                   3696:     if ($udom eq 'public' && $uname eq 'public') {
                   3697: 	return;
                   3698:     }
1.467     www      3699:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3700:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3701:     my $id=$uname.':'.$udom;
                   3702:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3703:     if ($cached) {
                   3704: 	return %{$names};
                   3705:     } else {
                   3706: 	my %loadnames=&Apache::lonnet::get('environment',
                   3707:                     			   ['notification','critnotification',
                   3708: 					    'permanentemail'],
                   3709: 					   $udom,$uname);
                   3710: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3711: 	return %loadnames;
                   3712:     }
                   3713: }
                   3714: 
1.551     albertel 3715: sub flush_email_cache {
                   3716:     my ($uname,$udom)=@_;
                   3717:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3718:     if (!$uname) { $uname=$env{'user.name'};   }
                   3719:     return if ($udom eq 'public' && $uname eq 'public');
                   3720:     my $id=$uname.':'.$udom;
                   3721:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3722: }
                   3723: 
1.728     raeburn  3724: # -------------------------------------------------------------------- getlangs
                   3725: 
                   3726: =pod
                   3727: 
                   3728: =item * &getlangs($uname,$udom)
                   3729: 
                   3730: Gets a user's language preference and returns it as a hash with key:
                   3731: language.
                   3732: 
                   3733: =cut
                   3734: 
                   3735: 
                   3736: sub getlangs {
                   3737:     my ($uname,$udom) = @_;
                   3738:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3739:     if (!$uname) { $uname=$env{'user.name'};   }
                   3740:     my $id=$uname.':'.$udom;
                   3741:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3742:     if ($cached) {
                   3743:         return %{$langs};
                   3744:     } else {
                   3745:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3746:                                            $udom,$uname);
                   3747:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3748:         return %loadlangs;
                   3749:     }
                   3750: }
                   3751: 
                   3752: sub flush_langs_cache {
                   3753:     my ($uname,$udom)=@_;
                   3754:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3755:     if (!$uname) { $uname=$env{'user.name'};   }
                   3756:     return if ($udom eq 'public' && $uname eq 'public');
                   3757:     my $id=$uname.':'.$udom;
                   3758:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3759: }
                   3760: 
1.61      www      3761: # ------------------------------------------------------------------ Screenname
1.81      albertel 3762: 
                   3763: =pod
                   3764: 
1.648     raeburn  3765: =item * &screenname($uname,$udom)
1.81      albertel 3766: 
                   3767: Gets a users screenname and returns it as a string
                   3768: 
                   3769: =cut
1.61      www      3770: 
                   3771: sub screenname {
                   3772:     my ($uname,$udom)=@_;
1.258     albertel 3773:     if ($uname eq $env{'user.name'} &&
                   3774: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3775:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3776:     return $names{'screenname'};
1.62      www      3777: }
                   3778: 
1.212     albertel 3779: 
1.802     bisitz   3780: # ------------------------------------------------------------- Confirm Wrapper
                   3781: =pod
                   3782: 
1.1075.2.42  raeburn  3783: =item * &confirmwrapper($message)
1.802     bisitz   3784: 
                   3785: Wrap messages about completion of operation in box
                   3786: 
                   3787: =cut
                   3788: 
                   3789: sub confirmwrapper {
                   3790:     my ($message)=@_;
                   3791:     if ($message) {
                   3792:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3793:                .$message."\n"
                   3794:                .'</div>'."\n";
                   3795:     } else {
                   3796:         return $message;
                   3797:     }
                   3798: }
                   3799: 
1.62      www      3800: # ------------------------------------------------------------- Message Wrapper
                   3801: 
                   3802: sub messagewrapper {
1.369     www      3803:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3804:     return 
1.441     albertel 3805:         '<a href="/adm/email?compose=individual&amp;'.
                   3806:         'recname='.$username.'&amp;recdom='.$domain.
                   3807: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3808:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3809: }
1.802     bisitz   3810: 
1.74      www      3811: # --------------------------------------------------------------- Notes Wrapper
                   3812: 
                   3813: sub noteswrapper {
                   3814:     my ($link,$un,$do)=@_;
                   3815:     return 
1.896     amueller 3816: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3817: }
1.802     bisitz   3818: 
1.62      www      3819: # ------------------------------------------------------------- Aboutme Wrapper
                   3820: 
                   3821: sub aboutmewrapper {
1.1070    raeburn  3822:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3823:     if (!defined($username)  && !defined($domain)) {
                   3824:         return;
                   3825:     }
1.1075.2.15  raeburn  3826:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3827: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3828: }
                   3829: 
                   3830: # ------------------------------------------------------------ Syllabus Wrapper
                   3831: 
                   3832: sub syllabuswrapper {
1.707     bisitz   3833:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3834:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3835: }
1.14      harris41 3836: 
1.1075.2.161.  .11(raeb 3837:-22): sub aboutme_on {
                   3838:-22):     my ($uname,$udom)=@_;
                   3839:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   3840:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   3841:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3842:-22):     my $hashkey=$uname.':'.$udom;
                   3843:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   3844:-22):     if ($cached) {
                   3845:-22):         return $aboutme;
                   3846:-22):     }
                   3847:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   3848:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   3849:-22):     return $aboutme;
                   3850:-22): }
                   3851:-22): 
                   3852:-22): sub devalidate_aboutme_cache {
                   3853:-22):     my ($uname,$udom)=@_;
                   3854:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3855:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   3856:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3857:-22):     my $id=$uname.':'.$udom;
                   3858:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   3859:-22): }
                   3860:-22): 
1.802     bisitz   3861: # -----------------------------------------------------------------------------
                   3862: 
1.208     matthew  3863: sub track_student_link {
1.887     raeburn  3864:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3865:     my $link ="/adm/trackstudent?";
1.208     matthew  3866:     my $title = 'View recent activity';
                   3867:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3868:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3869:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3870:         $title .= ' of this student';
1.268     albertel 3871:     } 
1.208     matthew  3872:     if (defined($target) && $target !~ /^\s*$/) {
                   3873:         $target = qq{target="$target"};
                   3874:     } else {
                   3875:         $target = '';
                   3876:     }
1.268     albertel 3877:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3878:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3879:     $title = &mt($title);
                   3880:     $linktext = &mt($linktext);
1.448     albertel 3881:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3882: 	&help_open_topic('View_recent_activity');
1.208     matthew  3883: }
                   3884: 
1.781     raeburn  3885: sub slot_reservations_link {
                   3886:     my ($linktext,$sname,$sdom,$target) = @_;
                   3887:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3888:     my $title = 'View slot reservation history';
                   3889:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3890:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3891:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3892:         $title .= ' of this student';
                   3893:     }
                   3894:     if (defined($target) && $target !~ /^\s*$/) {
                   3895:         $target = qq{target="$target"};
                   3896:     } else {
                   3897:         $target = '';
                   3898:     }
                   3899:     $title = &mt($title);
                   3900:     $linktext = &mt($linktext);
                   3901:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3902: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3903: 
                   3904: }
                   3905: 
1.508     www      3906: # ===================================================== Display a student photo
                   3907: 
                   3908: 
1.509     albertel 3909: sub student_image_tag {
1.508     www      3910:     my ($domain,$user)=@_;
                   3911:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3912:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3913: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3914:     } else {
                   3915: 	return '';
                   3916:     }
                   3917: }
                   3918: 
1.112     bowersj2 3919: =pod
                   3920: 
                   3921: =back
                   3922: 
                   3923: =head1 Access .tab File Data
                   3924: 
                   3925: =over 4
                   3926: 
1.648     raeburn  3927: =item * &languageids() 
1.112     bowersj2 3928: 
                   3929: returns list of all language ids
                   3930: 
                   3931: =cut
                   3932: 
1.14      harris41 3933: sub languageids {
1.16      harris41 3934:     return sort(keys(%language));
1.14      harris41 3935: }
                   3936: 
1.112     bowersj2 3937: =pod
                   3938: 
1.648     raeburn  3939: =item * &languagedescription() 
1.112     bowersj2 3940: 
                   3941: returns description of a specified language id
                   3942: 
                   3943: =cut
                   3944: 
1.14      harris41 3945: sub languagedescription {
1.125     www      3946:     my $code=shift;
                   3947:     return  ($supported_language{$code}?'* ':'').
                   3948:             $language{$code}.
1.126     www      3949: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3950: }
                   3951: 
1.1048    foxr     3952: =pod
                   3953: 
                   3954: =item * &plainlanguagedescription
                   3955: 
                   3956: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3957: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3958: 
                   3959: =cut
                   3960: 
1.145     www      3961: sub plainlanguagedescription {
                   3962:     my $code=shift;
                   3963:     return $language{$code};
                   3964: }
                   3965: 
1.1048    foxr     3966: =pod
                   3967: 
                   3968: =item * &supportedlanguagecode
                   3969: 
                   3970: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3971: code.
                   3972: 
                   3973: =cut
                   3974: 
1.145     www      3975: sub supportedlanguagecode {
                   3976:     my $code=shift;
                   3977:     return $supported_language{$code};
1.97      www      3978: }
                   3979: 
1.112     bowersj2 3980: =pod
                   3981: 
1.1048    foxr     3982: =item * &latexlanguage()
                   3983: 
                   3984: Given a language key code returns the correspondnig language to use
                   3985: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3986: is no supported hyphenation for the language code.
                   3987: 
                   3988: =cut
                   3989: 
                   3990: sub latexlanguage {
                   3991:     my $code = shift;
                   3992:     return $latex_language{$code};
                   3993: }
                   3994: 
                   3995: =pod
                   3996: 
                   3997: =item * &latexhyphenation()
                   3998: 
                   3999: Same as above but what's supplied is the language as it might be stored
                   4000: in the metadata.
                   4001: 
                   4002: =cut
                   4003: 
                   4004: sub latexhyphenation {
                   4005:     my $key = shift;
                   4006:     return $latex_language_bykey{$key};
                   4007: }
                   4008: 
                   4009: =pod
                   4010: 
1.648     raeburn  4011: =item * &copyrightids() 
1.112     bowersj2 4012: 
                   4013: returns list of all copyrights
                   4014: 
                   4015: =cut
                   4016: 
                   4017: sub copyrightids {
                   4018:     return sort(keys(%cprtag));
                   4019: }
                   4020: 
                   4021: =pod
                   4022: 
1.648     raeburn  4023: =item * &copyrightdescription() 
1.112     bowersj2 4024: 
                   4025: returns description of a specified copyright id
                   4026: 
                   4027: =cut
                   4028: 
                   4029: sub copyrightdescription {
1.166     www      4030:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4031: }
1.197     matthew  4032: 
                   4033: =pod
                   4034: 
1.648     raeburn  4035: =item * &source_copyrightids() 
1.192     taceyjo1 4036: 
                   4037: returns list of all source copyrights
                   4038: 
                   4039: =cut
                   4040: 
                   4041: sub source_copyrightids {
                   4042:     return sort(keys(%scprtag));
                   4043: }
                   4044: 
                   4045: =pod
                   4046: 
1.648     raeburn  4047: =item * &source_copyrightdescription() 
1.192     taceyjo1 4048: 
                   4049: returns description of a specified source copyright id
                   4050: 
                   4051: =cut
                   4052: 
                   4053: sub source_copyrightdescription {
                   4054:     return &mt($scprtag{shift(@_)});
                   4055: }
1.112     bowersj2 4056: 
                   4057: =pod
                   4058: 
1.648     raeburn  4059: =item * &filecategories() 
1.112     bowersj2 4060: 
                   4061: returns list of all file categories
                   4062: 
                   4063: =cut
                   4064: 
                   4065: sub filecategories {
                   4066:     return sort(keys(%category_extensions));
                   4067: }
                   4068: 
                   4069: =pod
                   4070: 
1.648     raeburn  4071: =item * &filecategorytypes() 
1.112     bowersj2 4072: 
                   4073: returns list of file types belonging to a given file
                   4074: category
                   4075: 
                   4076: =cut
                   4077: 
                   4078: sub filecategorytypes {
1.356     albertel 4079:     my ($cat) = @_;
                   4080:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4081: }
                   4082: 
                   4083: =pod
                   4084: 
1.648     raeburn  4085: =item * &fileembstyle() 
1.112     bowersj2 4086: 
                   4087: returns embedding style for a specified file type
                   4088: 
                   4089: =cut
                   4090: 
                   4091: sub fileembstyle {
                   4092:     return $fe{lc(shift(@_))};
1.169     www      4093: }
                   4094: 
1.351     www      4095: sub filemimetype {
                   4096:     return $fm{lc(shift(@_))};
                   4097: }
                   4098: 
1.169     www      4099: 
                   4100: sub filecategoryselect {
                   4101:     my ($name,$value)=@_;
1.189     matthew  4102:     return &select_form($value,$name,
1.970     raeburn  4103:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4104: }
                   4105: 
                   4106: =pod
                   4107: 
1.648     raeburn  4108: =item * &filedescription() 
1.112     bowersj2 4109: 
                   4110: returns description for a specified file type
                   4111: 
                   4112: =cut
                   4113: 
                   4114: sub filedescription {
1.188     matthew  4115:     my $file_description = $fd{lc(shift())};
                   4116:     $file_description =~ s:([\[\]]):~$1:g;
                   4117:     return &mt($file_description);
1.112     bowersj2 4118: }
                   4119: 
                   4120: =pod
                   4121: 
1.648     raeburn  4122: =item * &filedescriptionex() 
1.112     bowersj2 4123: 
                   4124: returns description for a specified file type with
                   4125: extra formatting
                   4126: 
                   4127: =cut
                   4128: 
                   4129: sub filedescriptionex {
                   4130:     my $ex=shift;
1.188     matthew  4131:     my $file_description = $fd{lc($ex)};
                   4132:     $file_description =~ s:([\[\]]):~$1:g;
                   4133:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4134: }
                   4135: 
                   4136: # End of .tab access
                   4137: =pod
                   4138: 
                   4139: =back
                   4140: 
                   4141: =cut
                   4142: 
                   4143: # ------------------------------------------------------------------ File Types
                   4144: sub fileextensions {
                   4145:     return sort(keys(%fe));
                   4146: }
                   4147: 
1.97      www      4148: # ----------------------------------------------------------- Display Languages
                   4149: # returns a hash with all desired display languages
                   4150: #
                   4151: 
                   4152: sub display_languages {
                   4153:     my %languages=();
1.695     raeburn  4154:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4155: 	$languages{$lang}=1;
1.97      www      4156:     }
                   4157:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4158:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4159: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4160: 	    $languages{$lang}=1;
1.97      www      4161:         }
                   4162:     }
                   4163:     return %languages;
1.14      harris41 4164: }
                   4165: 
1.582     albertel 4166: sub languages {
                   4167:     my ($possible_langs) = @_;
1.695     raeburn  4168:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4169:     if (!ref($possible_langs)) {
                   4170: 	if( wantarray ) {
                   4171: 	    return @preferred_langs;
                   4172: 	} else {
                   4173: 	    return $preferred_langs[0];
                   4174: 	}
                   4175:     }
                   4176:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4177:     my @preferred_possibilities;
                   4178:     foreach my $preferred_lang (@preferred_langs) {
                   4179: 	if (exists($possibilities{$preferred_lang})) {
                   4180: 	    push(@preferred_possibilities, $preferred_lang);
                   4181: 	}
                   4182:     }
                   4183:     if( wantarray ) {
                   4184: 	return @preferred_possibilities;
                   4185:     }
                   4186:     return $preferred_possibilities[0];
                   4187: }
                   4188: 
1.742     raeburn  4189: sub user_lang {
                   4190:     my ($touname,$toudom,$fromcid) = @_;
                   4191:     my @userlangs;
                   4192:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4193:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4194:                     $env{'course.'.$fromcid.'.languages'}));
                   4195:     } else {
                   4196:         my %langhash = &getlangs($touname,$toudom);
                   4197:         if ($langhash{'languages'} ne '') {
                   4198:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4199:         } else {
                   4200:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4201:             if ($domdefs{'lang_def'} ne '') {
                   4202:                 @userlangs = ($domdefs{'lang_def'});
                   4203:             }
                   4204:         }
                   4205:     }
                   4206:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4207:     my $user_lh = Apache::localize->get_handle(@languages);
                   4208:     return $user_lh;
                   4209: }
                   4210: 
                   4211: 
1.112     bowersj2 4212: ###############################################################
                   4213: ##               Student Answer Attempts                     ##
                   4214: ###############################################################
                   4215: 
                   4216: =pod
                   4217: 
                   4218: =head1 Alternate Problem Views
                   4219: 
                   4220: =over 4
                   4221: 
1.648     raeburn  4222: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4223:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4224: 
                   4225: Return string with previous attempt on problem. Arguments:
                   4226: 
                   4227: =over 4
                   4228: 
                   4229: =item * $symb: Problem, including path
                   4230: 
                   4231: =item * $username: username of the desired student
                   4232: 
                   4233: =item * $domain: domain of the desired student
1.14      harris41 4234: 
1.112     bowersj2 4235: =item * $course: Course ID
1.14      harris41 4236: 
1.112     bowersj2 4237: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4238:     something
1.14      harris41 4239: 
1.112     bowersj2 4240: =item * $regexp: if string matches this regexp, the string will be
                   4241:     sent to $gradesub
1.14      harris41 4242: 
1.112     bowersj2 4243: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4244: 
1.1075.2.86  raeburn  4245: =item * $usec: section of the desired student
                   4246: 
                   4247: =item * $identifier: counter for student (multiple students one problem) or
                   4248:     problem (one student; whole sequence).
                   4249: 
1.112     bowersj2 4250: =back
1.14      harris41 4251: 
1.112     bowersj2 4252: The output string is a table containing all desired attempts, if any.
1.16      harris41 4253: 
1.112     bowersj2 4254: =cut
1.1       albertel 4255: 
                   4256: sub get_previous_attempt {
1.1075.2.86  raeburn  4257:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4258:   my $prevattempts='';
1.43      ng       4259:   no strict 'refs';
1.1       albertel 4260:   if ($symb) {
1.3       albertel 4261:     my (%returnhash)=
                   4262:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4263:     if ($returnhash{'version'}) {
                   4264:       my %lasthash=();
                   4265:       my $version;
                   4266:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4267:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4268:             if ($key =~ /\.rawrndseed$/) {
                   4269:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4270:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4271:             } else {
                   4272:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4273:             }
1.19      harris41 4274:         }
1.1       albertel 4275:       }
1.596     albertel 4276:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4277:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4278:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4279:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4280:       foreach my $key (sort(keys(%lasthash))) {
                   4281: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4282: 	if ($#parts > 0) {
1.31      albertel 4283: 	  my $data=$parts[-1];
1.989     raeburn  4284:           next if ($data eq 'foilorder');
1.31      albertel 4285: 	  pop(@parts);
1.1010    www      4286:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4287:           if ($data eq 'type') {
                   4288:               unless ($showsurv) {
                   4289:                   my $id = join(',',@parts);
                   4290:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4291:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4292:                       $lasthidden{$ign.'.'.$id} = 1;
                   4293:                   }
1.945     raeburn  4294:               }
1.1075.2.86  raeburn  4295:               if ($identifier ne '') {
                   4296:                   my $id = join(',',@parts);
                   4297:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4298:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4299:                       $hidestatus{$ign.'.'.$id} = 1;
                   4300:                   }
                   4301:               }
                   4302:           } elsif ($data eq 'regrader') {
                   4303:               if (($identifier ne '') && (@parts)) {
                   4304:                   my $id = join(',',@parts);
                   4305:                   $regraded{$ign.'.'.$id} = 1;
                   4306:               }
1.1010    www      4307:           } 
1.31      albertel 4308: 	} else {
1.41      ng       4309: 	  if ($#parts == 0) {
                   4310: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4311: 	  } else {
                   4312: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4313: 	  }
1.31      albertel 4314: 	}
1.16      harris41 4315:       }
1.596     albertel 4316:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4317:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4318:         my (%solved,%resets,%probstatus);
                   4319:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4320:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4321:                 foreach my $id (keys(%regraded)) {
                   4322:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4323:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4324:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4325:                         push(@{$resets{$id}},$version);
                   4326:                     }
                   4327:                 }
                   4328:             }
                   4329:         }
1.40      ng       4330: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4331:             my (@hidden,@unsolved);
1.945     raeburn  4332:             if (%typeparts) {
                   4333:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4334:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4335:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4336:                         push(@hidden,$id);
1.1075.2.86  raeburn  4337:                     } elsif ($identifier ne '') {
                   4338:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4339:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4340:                                 ($hidestatus{$id})) {
                   4341:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4342:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4343:                                 push(@{$solved{$id}},$version);
                   4344:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4345:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4346:                                 my $skip;
                   4347:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4348:                                     foreach my $reset (@{$resets{$id}}) {
                   4349:                                         if ($reset > $solved{$id}[-1]) {
                   4350:                                             $skip=1;
                   4351:                                             last;
                   4352:                                         }
                   4353:                                     }
                   4354:                                 }
                   4355:                                 unless ($skip) {
                   4356:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4357:                                     push(@unsolved,$partslist);
                   4358:                                 }
                   4359:                             }
                   4360:                         }
1.945     raeburn  4361:                     }
                   4362:                 }
                   4363:             }
                   4364:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4365:                            '<td>'.&mt('Transaction [_1]',$version);
                   4366:             if (@unsolved) {
                   4367:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4368:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4369:                                  &mt('Hide').'</label></span>';
                   4370:             }
                   4371:             $prevattempts .= '</td>';
1.945     raeburn  4372:             if (@hidden) {
                   4373:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4374:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4375:                     my $hide;
                   4376:                     foreach my $id (@hidden) {
                   4377:                         if ($key =~ /^\Q$id\E/) {
                   4378:                             $hide = 1;
                   4379:                             last;
                   4380:                         }
                   4381:                     }
                   4382:                     if ($hide) {
                   4383:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4384:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4385:                             my $value = &format_previous_attempt_value($key,
                   4386:                                              $returnhash{$version.':'.$key});
                   4387:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4388:                         } else {
                   4389:                             $prevattempts.='<td>&nbsp;</td>';
                   4390:                         }
                   4391:                     } else {
                   4392:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4393:                             my $value = $returnhash{$version.':'.$key};
                   4394:                             if ($key =~ /\.rndseed$/) {
                   4395:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4396:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4397:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4398:                                 }
                   4399:                             }
                   4400:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4401:                                            '&nbsp;</td>';
1.945     raeburn  4402:                         } else {
                   4403:                             $prevattempts.='<td>&nbsp;</td>';
                   4404:                         }
                   4405:                     }
                   4406:                 }
                   4407:             } else {
                   4408: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4409:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4410:                     my $value = $returnhash{$version.':'.$key};
                   4411:                     if ($key =~ /\.rndseed$/) {
                   4412:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4413:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4414:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4415:                         }
                   4416:                     }
                   4417:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4418:                                    '&nbsp;</td>';
1.945     raeburn  4419: 	        }
                   4420:             }
                   4421: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4422: 	 }
1.1       albertel 4423:       }
1.945     raeburn  4424:       my @currhidden = keys(%lasthidden);
1.596     albertel 4425:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4426:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4427:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4428:           if (%typeparts) {
                   4429:               my $hidden;
                   4430:               foreach my $id (@currhidden) {
                   4431:                   if ($key =~ /^\Q$id\E/) {
                   4432:                       $hidden = 1;
                   4433:                       last;
                   4434:                   }
                   4435:               }
                   4436:               if ($hidden) {
                   4437:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4438:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4439:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4440:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4441:                           $value = &$gradesub($value);
                   4442:                       }
                   4443:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4444:                   } else {
                   4445:                       $prevattempts.='<td>&nbsp;</td>';
                   4446:                   }
                   4447:               } else {
                   4448:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4449:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4450:                       $value = &$gradesub($value);
                   4451:                   }
                   4452:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4453:               }
                   4454:           } else {
                   4455: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4456: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4457:                   $value = &$gradesub($value);
                   4458:               }
                   4459: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4460:           }
1.16      harris41 4461:       }
1.596     albertel 4462:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4463:     } else {
1.596     albertel 4464:       $prevattempts=
                   4465: 	  &start_data_table().&start_data_table_row().
                   4466: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4467: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4468:     }
                   4469:   } else {
1.596     albertel 4470:     $prevattempts=
                   4471: 	  &start_data_table().&start_data_table_row().
                   4472: 	  '<td>'.&mt('No data.').'</td>'.
                   4473: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4474:   }
1.10      albertel 4475: }
                   4476: 
1.581     albertel 4477: sub format_previous_attempt_value {
                   4478:     my ($key,$value) = @_;
1.1011    www      4479:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4480: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4481:     } elsif (ref($value) eq 'ARRAY') {
                   4482: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4483:     } elsif ($key =~ /answerstring$/) {
                   4484:         my %answers = &Apache::lonnet::str2hash($value);
                   4485:         my @anskeys = sort(keys(%answers));
                   4486:         if (@anskeys == 1) {
                   4487:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4488:             if ($answer =~ m{\0}) {
                   4489:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4490:             }
                   4491:             my $tag_internal_answer_name = 'INTERNAL';
                   4492:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4493:                 $value = $answer; 
                   4494:             } else {
                   4495:                 $value = $anskeys[0].'='.$answer;
                   4496:             }
                   4497:         } else {
                   4498:             foreach my $ans (@anskeys) {
                   4499:                 my $answer = $answers{$ans};
1.1001    raeburn  4500:                 if ($answer =~ m{\0}) {
                   4501:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4502:                 }
                   4503:                 $value .=  $ans.'='.$answer.'<br />';;
                   4504:             } 
                   4505:         }
1.581     albertel 4506:     } else {
                   4507: 	$value = &unescape($value);
                   4508:     }
                   4509:     return $value;
                   4510: }
                   4511: 
                   4512: 
1.107     albertel 4513: sub relative_to_absolute {
                   4514:     my ($url,$output)=@_;
                   4515:     my $parser=HTML::TokeParser->new(\$output);
                   4516:     my $token;
                   4517:     my $thisdir=$url;
                   4518:     my @rlinks=();
                   4519:     while ($token=$parser->get_token) {
                   4520: 	if ($token->[0] eq 'S') {
                   4521: 	    if ($token->[1] eq 'a') {
                   4522: 		if ($token->[2]->{'href'}) {
                   4523: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4524: 		}
                   4525: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4526: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4527: 	    } elsif ($token->[1] eq 'base') {
                   4528: 		$thisdir=$token->[2]->{'href'};
                   4529: 	    }
                   4530: 	}
                   4531:     }
                   4532:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4533:     foreach my $link (@rlinks) {
1.726     raeburn  4534: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4535: 		($link=~/^\//) ||
                   4536: 		($link=~/^javascript:/i) ||
                   4537: 		($link=~/^mailto:/i) ||
                   4538: 		($link=~/^\#/)) {
                   4539: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4540: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4541: 	}
                   4542:     }
                   4543: # -------------------------------------------------- Deal with Applet codebases
                   4544:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4545:     return $output;
                   4546: }
                   4547: 
1.112     bowersj2 4548: =pod
                   4549: 
1.648     raeburn  4550: =item * &get_student_view()
1.112     bowersj2 4551: 
                   4552: show a snapshot of what student was looking at
                   4553: 
                   4554: =cut
                   4555: 
1.10      albertel 4556: sub get_student_view {
1.186     albertel 4557:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4558:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4559:   my (%form);
1.10      albertel 4560:   my @elements=('symb','courseid','domain','username');
                   4561:   foreach my $element (@elements) {
1.186     albertel 4562:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4563:   }
1.186     albertel 4564:   if (defined($moreenv)) {
                   4565:       %form=(%form,%{$moreenv});
                   4566:   }
1.236     albertel 4567:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4568:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4569:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4570:   $userview=~s/\<body[^\>]*\>//gi;
                   4571:   $userview=~s/\<\/body\>//gi;
                   4572:   $userview=~s/\<html\>//gi;
                   4573:   $userview=~s/\<\/html\>//gi;
                   4574:   $userview=~s/\<head\>//gi;
                   4575:   $userview=~s/\<\/head\>//gi;
                   4576:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4577:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4578:   if (wantarray) {
                   4579:      return ($userview,$response);
                   4580:   } else {
                   4581:      return $userview;
                   4582:   }
                   4583: }
                   4584: 
                   4585: sub get_student_view_with_retries {
                   4586:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4587: 
                   4588:     my $ok = 0;                 # True if we got a good response.
                   4589:     my $content;
                   4590:     my $response;
                   4591: 
                   4592:     # Try to get the student_view done. within the retries count:
                   4593:     
                   4594:     do {
                   4595:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4596:          $ok      = $response->is_success;
                   4597:          if (!$ok) {
                   4598:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4599:          }
                   4600:          $retries--;
                   4601:     } while (!$ok && ($retries > 0));
                   4602:     
                   4603:     if (!$ok) {
                   4604:        $content = '';          # On error return an empty content.
                   4605:     }
1.651     www      4606:     if (wantarray) {
                   4607:        return ($content, $response);
                   4608:     } else {
                   4609:        return $content;
                   4610:     }
1.11      albertel 4611: }
                   4612: 
1.1075.2.149  raeburn  4613: sub css_links {
                   4614:     my ($currsymb,$level) = @_;
                   4615:     my ($links,@symbs,%cssrefs,%httpref);
                   4616:     if ($level eq 'map') {
                   4617:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4618:         if (ref($navmap)) {
                   4619:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4620:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4621:             foreach my $res (@resources) {
                   4622:                 if (ref($res) && $res->symb()) {
                   4623:                     push(@symbs,$res->symb());
                   4624:                 }
                   4625:             }
                   4626:         }
                   4627:     } else {
                   4628:         @symbs = ($currsymb);
                   4629:     }
                   4630:     foreach my $symb (@symbs) {
                   4631:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4632:         if ($css_href =~ /\S/) {
                   4633:             unless ($css_href =~ m{https?://}) {
                   4634:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4635:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4636:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4637:                 unless ($css_href =~ m{^/}) {
                   4638:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4639:                 }
                   4640:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4641:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4642:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4643:                         my $thisurl = $proburl;
                   4644:                         if ($env{'httpref.'.$proburl}) {
                   4645:                             $thisurl = $env{'httpref.'.$proburl};
                   4646:                         }
                   4647:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4648:                     }
                   4649:                 }
                   4650:             }
                   4651:             $cssrefs{$css_href} = 1;
                   4652:         }
                   4653:     }
                   4654:     if (keys(%httpref)) {
                   4655:         &Apache::lonnet::appenv(\%httpref);
                   4656:     }
                   4657:     if (keys(%cssrefs)) {
                   4658:         foreach my $css_href (keys(%cssrefs)) {
                   4659:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4660:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4661:         }
                   4662:     }
                   4663:     return $links;
                   4664: }
                   4665: 
1.112     bowersj2 4666: =pod
                   4667: 
1.648     raeburn  4668: =item * &get_student_answers() 
1.112     bowersj2 4669: 
                   4670: show a snapshot of how student was answering problem
                   4671: 
                   4672: =cut
                   4673: 
1.11      albertel 4674: sub get_student_answers {
1.100     sakharuk 4675:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4676:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4677:   my (%moreenv);
1.11      albertel 4678:   my @elements=('symb','courseid','domain','username');
                   4679:   foreach my $element (@elements) {
1.186     albertel 4680:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4681:   }
1.186     albertel 4682:   $moreenv{'grade_target'}='answer';
                   4683:   %moreenv=(%form,%moreenv);
1.497     raeburn  4684:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4685:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4686:   return $userview;
1.1       albertel 4687: }
1.116     albertel 4688: 
                   4689: =pod
                   4690: 
                   4691: =item * &submlink()
                   4692: 
1.242     albertel 4693: Inputs: $text $uname $udom $symb $target
1.116     albertel 4694: 
                   4695: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4696: 
                   4697: =cut
                   4698: 
                   4699: ###############################################
                   4700: sub submlink {
1.242     albertel 4701:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4702:     if (!($uname && $udom)) {
                   4703: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4704: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4705: 	if (!$symb) { $symb=$cursymb; }
                   4706:     }
1.254     matthew  4707:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4708:     $symb=&escape($symb);
1.960     bisitz   4709:     if ($target) { $target=" target=\"$target\""; }
                   4710:     return
                   4711:         '<a href="/adm/grades?command=submission'.
                   4712:         '&amp;symb='.$symb.
                   4713:         '&amp;student='.$uname.
                   4714:         '&amp;userdom='.$udom.'"'.
                   4715:         $target.'>'.$text.'</a>';
1.242     albertel 4716: }
                   4717: ##############################################
                   4718: 
                   4719: =pod
                   4720: 
                   4721: =item * &pgrdlink()
                   4722: 
                   4723: Inputs: $text $uname $udom $symb $target
                   4724: 
                   4725: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4726: 
                   4727: =cut
                   4728: 
                   4729: ###############################################
                   4730: sub pgrdlink {
                   4731:     my $link=&submlink(@_);
                   4732:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4733:     return $link;
                   4734: }
                   4735: ##############################################
                   4736: 
                   4737: =pod
                   4738: 
                   4739: =item * &pprmlink()
                   4740: 
                   4741: Inputs: $text $uname $udom $symb $target
                   4742: 
                   4743: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4744: student and a specific resource
1.242     albertel 4745: 
                   4746: =cut
                   4747: 
                   4748: ###############################################
                   4749: sub pprmlink {
                   4750:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4751:     if (!($uname && $udom)) {
                   4752: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4753: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4754: 	if (!$symb) { $symb=$cursymb; }
                   4755:     }
1.254     matthew  4756:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4757:     $symb=&escape($symb);
1.242     albertel 4758:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4759:     return '<a href="/adm/parmset?command=set&amp;'.
                   4760: 	'symb='.$symb.'&amp;uname='.$uname.
                   4761: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4762: }
                   4763: ##############################################
1.37      matthew  4764: 
1.112     bowersj2 4765: =pod
                   4766: 
                   4767: =back
                   4768: 
                   4769: =cut
                   4770: 
1.37      matthew  4771: ###############################################
1.51      www      4772: 
                   4773: 
                   4774: sub timehash {
1.687     raeburn  4775:     my ($thistime) = @_;
                   4776:     my $timezone = &Apache::lonlocal::gettimezone();
                   4777:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4778:                      ->set_time_zone($timezone);
                   4779:     my $wday = $dt->day_of_week();
                   4780:     if ($wday == 7) { $wday = 0; }
                   4781:     return ( 'second' => $dt->second(),
                   4782:              'minute' => $dt->minute(),
                   4783:              'hour'   => $dt->hour(),
                   4784:              'day'     => $dt->day_of_month(),
                   4785:              'month'   => $dt->month(),
                   4786:              'year'    => $dt->year(),
                   4787:              'weekday' => $wday,
                   4788:              'dayyear' => $dt->day_of_year(),
                   4789:              'dlsav'   => $dt->is_dst() );
1.51      www      4790: }
                   4791: 
1.370     www      4792: sub utc_string {
                   4793:     my ($date)=@_;
1.371     www      4794:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4795: }
                   4796: 
1.51      www      4797: sub maketime {
                   4798:     my %th=@_;
1.687     raeburn  4799:     my ($epoch_time,$timezone,$dt);
                   4800:     $timezone = &Apache::lonlocal::gettimezone();
                   4801:     eval {
                   4802:         $dt = DateTime->new( year   => $th{'year'},
                   4803:                              month  => $th{'month'},
                   4804:                              day    => $th{'day'},
                   4805:                              hour   => $th{'hour'},
                   4806:                              minute => $th{'minute'},
                   4807:                              second => $th{'second'},
                   4808:                              time_zone => $timezone,
                   4809:                          );
                   4810:     };
                   4811:     if (!$@) {
                   4812:         $epoch_time = $dt->epoch;
                   4813:         if ($epoch_time) {
                   4814:             return $epoch_time;
                   4815:         }
                   4816:     }
1.51      www      4817:     return POSIX::mktime(
                   4818:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4819:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4820: }
                   4821: 
                   4822: #########################################
1.51      www      4823: 
                   4824: sub findallcourses {
1.482     raeburn  4825:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4826:     my %roles;
                   4827:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4828:     my %courses;
1.51      www      4829:     my $now=time;
1.482     raeburn  4830:     if (!defined($uname)) {
                   4831:         $uname = $env{'user.name'};
                   4832:     }
                   4833:     if (!defined($udom)) {
                   4834:         $udom = $env{'user.domain'};
                   4835:     }
                   4836:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4837:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4838:         if (!%roles) {
                   4839:             %roles = (
                   4840:                        cc => 1,
1.907     raeburn  4841:                        co => 1,
1.482     raeburn  4842:                        in => 1,
                   4843:                        ep => 1,
                   4844:                        ta => 1,
                   4845:                        cr => 1,
                   4846:                        st => 1,
                   4847:              );
                   4848:         }
                   4849:         foreach my $entry (keys(%roleshash)) {
                   4850:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4851:             if ($trole =~ /^cr/) { 
                   4852:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4853:             } else {
                   4854:                 next if (!exists($roles{$trole}));
                   4855:             }
                   4856:             if ($tend) {
                   4857:                 next if ($tend < $now);
                   4858:             }
                   4859:             if ($tstart) {
                   4860:                 next if ($tstart > $now);
                   4861:             }
1.1058    raeburn  4862:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4863:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4864:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4865:             if ($secpart eq '') {
                   4866:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4867:                 $sec = 'none';
1.1058    raeburn  4868:                 $value .= $cnum.'/';
1.482     raeburn  4869:             } else {
                   4870:                 $cnum = $cnumpart;
                   4871:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4872:                 $value .= $cnum.'/'.$sec;
                   4873:             }
                   4874:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4875:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4876:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4877:                 }
                   4878:             } else {
                   4879:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4880:             }
1.482     raeburn  4881:         }
                   4882:     } else {
                   4883:         foreach my $key (keys(%env)) {
1.483     albertel 4884: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4885:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4886: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4887: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4888: 	        next if (%roles && !exists($roles{$role}));
                   4889: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4890:                 my $active=1;
                   4891:                 if ($starttime) {
                   4892: 		    if ($now<$starttime) { $active=0; }
                   4893:                 }
                   4894:                 if ($endtime) {
                   4895:                     if ($now>$endtime) { $active=0; }
                   4896:                 }
                   4897:                 if ($active) {
1.1058    raeburn  4898:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4899:                     if ($sec eq '') {
                   4900:                         $sec = 'none';
1.1058    raeburn  4901:                     } else {
                   4902:                         $value .= $sec;
                   4903:                     }
                   4904:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4905:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4906:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4907:                         }
                   4908:                     } else {
                   4909:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4910:                     }
1.474     raeburn  4911:                 }
                   4912:             }
1.51      www      4913:         }
                   4914:     }
1.474     raeburn  4915:     return %courses;
1.51      www      4916: }
1.37      matthew  4917: 
1.54      www      4918: ###############################################
1.474     raeburn  4919: 
                   4920: sub blockcheck {
1.1075.2.158  raeburn  4921:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4922: 
1.1075.2.161.  .4(raebu 4923:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  4924:         my ($has_evb,$check_ipaccess);
                   4925:         my $dom = $env{'user.domain'};
                   4926:         if ($env{'request.course.id'}) {
                   4927:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4928:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4929:             my $checkrole = "cm./$cdom/$cnum";
                   4930:             my $sec = $env{'request.course.sec'};
                   4931:             if ($sec ne '') {
                   4932:                 $checkrole .= "/$sec";
                   4933:             }
                   4934:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   4935:                 ($env{'request.role'} !~ /^st/)) {
                   4936:                 $has_evb = 1;
                   4937:             }
                   4938:             unless ($has_evb) {
                   4939:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   4940:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   4941:                     if ($udom eq $cdom) {
                   4942:                         $check_ipaccess = 1;
                   4943:                     }
                   4944:                 }
                   4945:             }
1.1075.2.161.  .3(raebu 4946:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   4947:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   4948:22):             my $checkrole;
                   4949:22):             if ($env{'request.role.domain'} eq '') {
                   4950:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   4951:22):             } else {
                   4952:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   4953:22):             }
                   4954:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   4955:22):                 $has_evb = 1;
                   4956:22):             }
1.1075.2.158  raeburn  4957:         }
                   4958:         unless ($has_evb || $check_ipaccess) {
                   4959:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   4960:             if (($dom eq 'public') && ($activity eq 'port')) {
                   4961:                 $dom = $udom;
                   4962:             }
                   4963:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   4964:                 $check_ipaccess = 1;
                   4965:             } else {
                   4966:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   4967:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   4968:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   4969:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   4970:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   4971:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   4972:                         $check_ipaccess = 1;
                   4973:                     }
                   4974:                 }
                   4975:             }
                   4976:         }
                   4977:         if ($check_ipaccess) {
                   4978:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   4979:             unless (defined($cached)) {
                   4980:                 my %domconfig =
                   4981:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   4982:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   4983:             }
                   4984:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   4985:                 foreach my $id (keys(%{$ipaccessref})) {
                   4986:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   4987:                         my $range = $ipaccessref->{$id}->{'ip'};
                   4988:                         if ($range) {
                   4989:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   4990:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   4991:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   4992:                                         return ('','','',$id,$dom);
                   4993:                                         last;
                   4994:                                     }
                   4995:                                 }
                   4996:                             }
                   4997:                         }
                   4998:                     }
                   4999:                 }
                   5000:             }
                   5001:         }
1.1075.2.161.  .4(raebu 5002:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5003:22):             return ();
                   5004:22):         }
1.1075.2.158  raeburn  5005:     }
1.1075.2.73  raeburn  5006:     if (defined($udom) && defined($uname)) {
                   5007:         # If uname and udom are for a course, check for blocks in the course.
                   5008:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5009:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5010:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5011:             return ($startblock,$endblock,$triggerblock);
                   5012:         }
                   5013:     } else {
1.490     raeburn  5014:         $udom = $env{'user.domain'};
                   5015:         $uname = $env{'user.name'};
                   5016:     }
                   5017: 
1.502     raeburn  5018:     my $startblock = 0;
                   5019:     my $endblock = 0;
1.1062    raeburn  5020:     my $triggerblock = '';
1.1075.2.160  raeburn  5021:     my %live_courses;
                   5022:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5023:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5024:     }
1.474     raeburn  5025: 
1.490     raeburn  5026:     # If uname is for a user, and activity is course-specific, i.e.,
                   5027:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5028: 
1.490     raeburn  5029:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5030:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5031:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5032:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5033:         foreach my $key (keys(%live_courses)) {
                   5034:             if ($key ne $env{'request.course.id'}) {
                   5035:                 delete($live_courses{$key});
                   5036:             }
                   5037:         }
                   5038:     }
                   5039: 
                   5040:     my $otheruser = 0;
                   5041:     my %own_courses;
                   5042:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5043:         # Resource belongs to user other than current user.
                   5044:         $otheruser = 1;
                   5045:         # Gather courses for current user
                   5046:         %own_courses = 
                   5047:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5048:     }
                   5049: 
                   5050:     # Gather active course roles - course coordinator, instructor, 
                   5051:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5052: 
                   5053:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5054:         my ($cdom,$cnum);
                   5055:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5056:             $cdom = $env{'course.'.$course.'.domain'};
                   5057:             $cnum = $env{'course.'.$course.'.num'};
                   5058:         } else {
1.490     raeburn  5059:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5060:         }
                   5061:         my $no_ownblock = 0;
                   5062:         my $no_userblock = 0;
1.533     raeburn  5063:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5064:             # Check if current user has 'evb' priv for this
                   5065:             if (defined($own_courses{$course})) {
                   5066:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5067:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5068:                     if ($sec ne 'none') {
                   5069:                         $checkrole .= '/'.$sec;
                   5070:                     }
                   5071:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5072:                         $no_ownblock = 1;
                   5073:                         last;
                   5074:                     }
                   5075:                 }
                   5076:             }
                   5077:             # if they have 'evb' priv and are currently not playing student
                   5078:             next if (($no_ownblock) &&
                   5079:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5080:         }
1.474     raeburn  5081:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5082:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5083:             if ($sec ne 'none') {
1.482     raeburn  5084:                 $checkrole .= '/'.$sec;
1.474     raeburn  5085:             }
1.490     raeburn  5086:             if ($otheruser) {
                   5087:                 # Resource belongs to user other than current user.
                   5088:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5089:                 my (%allroles,%userroles);
                   5090:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5091:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5092:                         my ($trole,$tdom,$tnum,$tsec);
                   5093:                         if ($entry =~ /^cr/) {
                   5094:                             ($trole,$tdom,$tnum,$tsec) = 
                   5095:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5096:                         } else {
                   5097:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5098:                         }
                   5099:                         my ($spec,$area,$trest);
                   5100:                         $area = '/'.$tdom.'/'.$tnum;
                   5101:                         $trest = $tnum;
                   5102:                         if ($tsec ne '') {
                   5103:                             $area .= '/'.$tsec;
                   5104:                             $trest .= '/'.$tsec;
                   5105:                         }
                   5106:                         $spec = $trole.'.'.$area;
                   5107:                         if ($trole =~ /^cr/) {
                   5108:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5109:                                                               $tdom,$spec,$trest,$area);
                   5110:                         } else {
                   5111:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5112:                                                                 $tdom,$spec,$trest,$area);
                   5113:                         }
                   5114:                     }
1.1075.2.124  raeburn  5115:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5116:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5117:                         if ($1) {
                   5118:                             $no_userblock = 1;
                   5119:                             last;
                   5120:                         }
1.486     raeburn  5121:                     }
                   5122:                 }
1.490     raeburn  5123:             } else {
                   5124:                 # Resource belongs to current user
                   5125:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5126:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5127:                     $no_ownblock = 1;
                   5128:                     last;
                   5129:                 }
1.474     raeburn  5130:             }
                   5131:         }
                   5132:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5133:         next if (($no_ownblock) &&
1.491     albertel 5134:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5135:         next if ($no_userblock);
1.474     raeburn  5136: 
1.1075.2.128  raeburn  5137:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5138:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5139:         
1.1062    raeburn  5140:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5141:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5142:         if (($start != 0) && 
                   5143:             (($startblock == 0) || ($startblock > $start))) {
                   5144:             $startblock = $start;
1.1062    raeburn  5145:             if ($trigger ne '') {
                   5146:                 $triggerblock = $trigger;
                   5147:             }
1.502     raeburn  5148:         }
                   5149:         if (($end != 0)  &&
                   5150:             (($endblock == 0) || ($endblock < $end))) {
                   5151:             $endblock = $end;
1.1062    raeburn  5152:             if ($trigger ne '') {
                   5153:                 $triggerblock = $trigger;
                   5154:             }
1.502     raeburn  5155:         }
1.490     raeburn  5156:     }
1.1062    raeburn  5157:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5158: }
                   5159: 
                   5160: sub get_blocks {
1.1075.2.147  raeburn  5161:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5162:     my $startblock = 0;
                   5163:     my $endblock = 0;
1.1062    raeburn  5164:     my $triggerblock = '';
1.490     raeburn  5165:     my $course = $cdom.'_'.$cnum;
                   5166:     $setters->{$course} = {};
                   5167:     $setters->{$course}{'staff'} = [];
                   5168:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5169:     $setters->{$course}{'triggers'} = [];
                   5170:     my (@blockers,%triggered);
                   5171:     my $now = time;
                   5172:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5173:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5174:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5175:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5176:             $blocked = 1;
                   5177:             $nosymbcache = 1;
1.1075.2.148  raeburn  5178:             $noenccheck = 1;
1.1075.2.147  raeburn  5179:         }
1.1075.2.148  raeburn  5180:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5181:         foreach my $block (@blockers) {
                   5182:             if ($block =~ /^firstaccess____(.+)$/) {
                   5183:                 my $item = $1;
                   5184:                 my $type = 'map';
                   5185:                 my $timersymb = $item;
                   5186:                 if ($item eq 'course') {
                   5187:                     $type = 'course';
                   5188:                 } elsif ($item =~ /___\d+___/) {
                   5189:                     $type = 'resource';
                   5190:                 } else {
                   5191:                     $timersymb = &Apache::lonnet::symbread($item);
                   5192:                 }
                   5193:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5194:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5195:                 $triggered{$block} = {
                   5196:                                        start => $start,
                   5197:                                        end   => $end,
                   5198:                                        type  => $type,
                   5199:                                      };
                   5200:             }
                   5201:         }
                   5202:     } else {
                   5203:         foreach my $block (keys(%commblocks)) {
                   5204:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5205:                 my ($start,$end) = ($1,$2);
                   5206:                 if ($start <= time && $end >= time) {
                   5207:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5208:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5209:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5210:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5211:                                     push(@blockers,$block);
                   5212:                                 }
                   5213:                             }
                   5214:                         }
                   5215:                     }
                   5216:                 }
                   5217:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5218:                 my $item = $1;
                   5219:                 my $timersymb = $item; 
                   5220:                 my $type = 'map';
                   5221:                 if ($item eq 'course') {
                   5222:                     $type = 'course';
                   5223:                 } elsif ($item =~ /___\d+___/) {
                   5224:                     $type = 'resource';
                   5225:                 } else {
                   5226:                     $timersymb = &Apache::lonnet::symbread($item);
                   5227:                 }
                   5228:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5229:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5230:                 if ($start && $end) {
                   5231:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5232:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5233:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5234:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5235:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5236:                                         push(@blockers,$block);
                   5237:                                         $triggered{$block} = {
                   5238:                                                                start => $start,
                   5239:                                                                end   => $end,
                   5240:                                                                type  => $type,
                   5241:                                                              };
                   5242:                                     }
                   5243:                                 }
                   5244:                             }
1.1062    raeburn  5245:                         }
                   5246:                     }
1.490     raeburn  5247:                 }
1.1062    raeburn  5248:             }
                   5249:         }
                   5250:     }
                   5251:     foreach my $blocker (@blockers) {
                   5252:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5253:             &parse_block_record($commblocks{$blocker});
                   5254:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5255:         my ($start,$end,$triggertype);
                   5256:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5257:             ($start,$end) = ($1,$2);
                   5258:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5259:             $start = $triggered{$blocker}{'start'};
                   5260:             $end = $triggered{$blocker}{'end'};
                   5261:             $triggertype = $triggered{$blocker}{'type'};
                   5262:         }
                   5263:         if ($start) {
                   5264:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5265:             if ($triggertype) {
                   5266:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5267:             } else {
                   5268:                 push(@{$$setters{$course}{'triggers'}},0);
                   5269:             }
                   5270:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5271:                 $startblock = $start;
                   5272:                 if ($triggertype) {
                   5273:                     $triggerblock = $blocker;
1.474     raeburn  5274:                 }
                   5275:             }
1.1062    raeburn  5276:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5277:                $endblock = $end;
                   5278:                if ($triggertype) {
                   5279:                    $triggerblock = $blocker;
                   5280:                }
                   5281:             }
1.474     raeburn  5282:         }
                   5283:     }
1.1062    raeburn  5284:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5285: }
                   5286: 
                   5287: sub parse_block_record {
                   5288:     my ($record) = @_;
                   5289:     my ($setuname,$setudom,$title,$blocks);
                   5290:     if (ref($record) eq 'HASH') {
                   5291:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5292:         $title = &unescape($record->{'event'});
                   5293:         $blocks = $record->{'blocks'};
                   5294:     } else {
                   5295:         my @data = split(/:/,$record,3);
                   5296:         if (scalar(@data) eq 2) {
                   5297:             $title = $data[1];
                   5298:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5299:         } else {
                   5300:             ($setuname,$setudom,$title) = @data;
                   5301:         }
                   5302:         $blocks = { 'com' => 'on' };
                   5303:     }
                   5304:     return ($setuname,$setudom,$title,$blocks);
                   5305: }
                   5306: 
1.854     kalberla 5307: sub blocking_status {
1.1075.2.158  raeburn  5308:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5309:     my %setters;
1.890     droeschl 5310: 
1.1061    raeburn  5311: # check for active blocking
1.1075.2.158  raeburn  5312:     if ($clientip eq '') {
                   5313:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5314:     }
                   5315:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5316:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5317:     my $blocked = 0;
1.1075.2.158  raeburn  5318:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5319:         $blocked = 1;
                   5320:     }
1.890     droeschl 5321: 
1.1061    raeburn  5322: # caller just wants to know whether a block is active
                   5323:     if (!wantarray) { return $blocked; }
                   5324: 
                   5325: # build a link to a popup window containing the details
                   5326:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5327: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5328:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5329:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5330:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5331:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5332:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5333:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5334:         if ($symb) {
                   5335:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5336:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5337:         }
1.1062    raeburn  5338:     }
1.1061    raeburn  5339: 
                   5340:     my $output .= <<'END_MYBLOCK';
                   5341: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5342:     var options = "width=" + w + ",height=" + h + ",";
                   5343:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5344:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5345:     var newWin = window.open(url, wdwName, options);
                   5346:     newWin.focus();
                   5347: }
1.890     droeschl 5348: END_MYBLOCK
1.854     kalberla 5349: 
1.1061    raeburn  5350:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5351:   
1.1061    raeburn  5352:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5353:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5354:     my $class = 'LC_comblock';
1.1062    raeburn  5355:     if ($activity eq 'docs') {
                   5356:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5357:         $class = '';
1.1063    raeburn  5358:     } elsif ($activity eq 'printout') {
                   5359:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5360:     } elsif ($activity eq 'passwd') {
                   5361:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5362:     } elsif ($activity eq 'grades') {
                   5363:         $text = &mt('Gradebook Blocked');
                   5364:     } elsif ($activity eq 'search') {
                   5365:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5366:21):     } elsif ($activity eq 'alert') {
                   5367:21):         $text = &mt('Checking Critical Messages Blocked');
                   5368:21):     } elsif ($activity eq 'reinit') {
                   5369:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5370:     } elsif ($activity eq 'about') {
                   5371:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5372:     } elsif ($activity eq 'wishlist') {
                   5373:         $text = &mt('Access to Stored Links Blocked');
                   5374:     } elsif ($activity eq 'annotate') {
                   5375:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5376:     }
1.1061    raeburn  5377:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5378: <div class='$class'>
1.869     kalberla 5379:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5380:   title='$text'>
                   5381:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5382:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5383:   title='$text'>$text</a>
1.867     kalberla 5384: </div>
                   5385: 
                   5386: END_BLOCK
1.474     raeburn  5387: 
1.1061    raeburn  5388:     return ($blocked, $output);
1.854     kalberla 5389: }
1.490     raeburn  5390: 
1.60      matthew  5391: ###############################################
                   5392: 
1.682     raeburn  5393: sub check_ip_acc {
1.1075.2.105  raeburn  5394:     my ($acc,$clientip)=@_;
1.682     raeburn  5395:     &Apache::lonxml::debug("acc is $acc");
                   5396:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5397:         return 1;
                   5398:     }
                   5399:     my $allowed=0;
1.1075.2.144  raeburn  5400:     my $ip;
                   5401:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5402:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5403:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5404:     } else {
1.1075.2.150  raeburn  5405:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5406:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5407:     }
1.682     raeburn  5408: 
                   5409:     my $name;
1.1075.2.161.  .1(raebu 5410:21):     my %access = (
                   5411:21):                      allowfrom => 1,
                   5412:21):                      denyfrom  => 0,
                   5413:21):                  );
                   5414:21):     my @allows;
                   5415:21):     my @denies;
                   5416:21):     foreach my $item (split(',',$acc)) {
                   5417:21):         $item =~ s/^\s*//;
                   5418:21):         $item =~ s/\s*$//;
                   5419:21):         if ($item =~ /^\!(.+)$/) {
                   5420:21):             push(@denies,$1);
                   5421:21):         } else {
                   5422:21):             push(@allows,$item);
                   5423:21):         }
                   5424:21):     }
                   5425:21):     my $numdenies = scalar(@denies);
                   5426:21):     my $numallows = scalar(@allows);
                   5427:21):     my $count = 0;
                   5428:21):     foreach my $pattern (@denies,@allows) {
                   5429:21):         $count ++;
                   5430:21):         my $acctype = 'allowfrom';
                   5431:21):         if ($count <= $numdenies) {
                   5432:21):             $acctype = 'denyfrom';
                   5433:21):         }
1.682     raeburn  5434:         if ($pattern =~ /\*$/) {
                   5435:             #35.8.*
                   5436:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5437:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5438:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5439:             #35.8.3.[34-56]
                   5440:             my $low=$2;
                   5441:             my $high=$3;
                   5442:             $pattern=$1;
                   5443:             if ($ip =~ /^\Q$pattern\E/) {
                   5444:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5445:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5446:             }
                   5447:         } elsif ($pattern =~ /^\*/) {
                   5448:             #*.msu.edu
                   5449:             $pattern=~s/\*//;
                   5450:             if (!defined($name)) {
                   5451:                 use Socket;
                   5452:                 my $netaddr=inet_aton($ip);
                   5453:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5454:             }
1.1075.2.161.  .1(raebu 5455:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5456:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5457:             #127.0.0.1
1.1075.2.161.  .1(raebu 5458:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5459:         } else {
                   5460:             #some.name.com
                   5461:             if (!defined($name)) {
                   5462:                 use Socket;
                   5463:                 my $netaddr=inet_aton($ip);
                   5464:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5465:             }
1.1075.2.161.  .1(raebu 5466:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5467:21):         }
                   5468:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5469:21):     }
                   5470:21):     if ($allowed eq '') {
                   5471:21):         if ($numdenies && !$numallows) {
                   5472:21):             $allowed = 1;
                   5473:21):         } else {
                   5474:21):             $allowed = 0;
1.682     raeburn  5475:         }
                   5476:     }
                   5477:     return $allowed;
                   5478: }
                   5479: 
                   5480: ###############################################
                   5481: 
1.60      matthew  5482: =pod
                   5483: 
1.112     bowersj2 5484: =head1 Domain Template Functions
                   5485: 
                   5486: =over 4
                   5487: 
                   5488: =item * &determinedomain()
1.60      matthew  5489: 
                   5490: Inputs: $domain (usually will be undef)
                   5491: 
1.63      www      5492: Returns: Determines which domain should be used for designs
1.60      matthew  5493: 
                   5494: =cut
1.54      www      5495: 
1.60      matthew  5496: ###############################################
1.63      www      5497: sub determinedomain {
                   5498:     my $domain=shift;
1.531     albertel 5499:     if (! $domain) {
1.60      matthew  5500:         # Determine domain if we have not been given one
1.893     raeburn  5501:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5502:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5503:         if ($env{'request.role.domain'}) { 
                   5504:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5505:         }
                   5506:     }
1.63      www      5507:     return $domain;
                   5508: }
                   5509: ###############################################
1.517     raeburn  5510: 
1.518     albertel 5511: sub devalidate_domconfig_cache {
                   5512:     my ($udom)=@_;
                   5513:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5514: }
                   5515: 
                   5516: # ---------------------- Get domain configuration for a domain
                   5517: sub get_domainconf {
                   5518:     my ($udom) = @_;
                   5519:     my $cachetime=1800;
                   5520:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5521:     if (defined($cached)) { return %{$result}; }
                   5522: 
                   5523:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5524: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5525:     my (%designhash,%legacy);
1.518     albertel 5526:     if (keys(%domconfig) > 0) {
                   5527:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5528:             if (keys(%{$domconfig{'login'}})) {
                   5529:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5530:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5531:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5532:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5533:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5534:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5535:                                         if ($key eq 'loginvia') {
                   5536:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5537:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5538:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5539:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5540:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5541:                                                 } else {
                   5542:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5543:                                                 }
1.948     raeburn  5544:                                             }
1.1075.2.87  raeburn  5545:                                         } elsif ($key eq 'headtag') {
                   5546:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5547:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5548:                                             }
1.946     raeburn  5549:                                         }
1.1075.2.87  raeburn  5550:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5551:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5552:                                         }
1.946     raeburn  5553:                                     }
                   5554:                                 }
                   5555:                             }
1.1075.2.158  raeburn  5556:                         } elsif ($key eq 'saml') {
                   5557:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5558:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5559:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5560:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5561:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5562:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5563:                                         }
                   5564:                                     }
                   5565:                                 }
                   5566:                             }
1.946     raeburn  5567:                         } else {
                   5568:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5569:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5570:                                     $domconfig{'login'}{$key}{$img};
                   5571:                             }
1.699     raeburn  5572:                         }
                   5573:                     } else {
                   5574:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5575:                     }
1.632     raeburn  5576:                 }
                   5577:             } else {
                   5578:                 $legacy{'login'} = 1;
1.518     albertel 5579:             }
1.632     raeburn  5580:         } else {
                   5581:             $legacy{'login'} = 1;
1.518     albertel 5582:         }
                   5583:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5584:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5585:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5586:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5587:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5588:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5589:                         }
1.518     albertel 5590:                     }
                   5591:                 }
1.632     raeburn  5592:             } else {
                   5593:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5594:             }
1.632     raeburn  5595:         } else {
                   5596:             $legacy{'rolecolors'} = 1;
1.518     albertel 5597:         }
1.948     raeburn  5598:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5599:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5600:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5601:             }
                   5602:         }
1.632     raeburn  5603:         if (keys(%legacy) > 0) {
                   5604:             my %legacyhash = &get_legacy_domconf($udom);
                   5605:             foreach my $item (keys(%legacyhash)) {
                   5606:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5607:                     if ($legacy{'login'}) { 
                   5608:                         $designhash{$item} = $legacyhash{$item};
                   5609:                     }
                   5610:                 } else {
                   5611:                     if ($legacy{'rolecolors'}) {
                   5612:                         $designhash{$item} = $legacyhash{$item};
                   5613:                     }
1.518     albertel 5614:                 }
                   5615:             }
                   5616:         }
1.632     raeburn  5617:     } else {
                   5618:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5619:     }
                   5620:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5621: 				  $cachetime);
                   5622:     return %designhash;
                   5623: }
                   5624: 
1.632     raeburn  5625: sub get_legacy_domconf {
                   5626:     my ($udom) = @_;
                   5627:     my %legacyhash;
                   5628:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5629:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5630:     if (-e $designfile) {
1.1075.2.128  raeburn  5631:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5632:             while (my $line = <$fh>) {
                   5633:                 next if ($line =~ /^\#/);
                   5634:                 chomp($line);
                   5635:                 my ($key,$val)=(split(/\=/,$line));
                   5636:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5637:             }
                   5638:             close($fh);
                   5639:         }
                   5640:     }
1.1026    raeburn  5641:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5642:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5643:     }
                   5644:     return %legacyhash;
                   5645: }
                   5646: 
1.63      www      5647: =pod
                   5648: 
1.112     bowersj2 5649: =item * &domainlogo()
1.63      www      5650: 
                   5651: Inputs: $domain (usually will be undef)
                   5652: 
                   5653: Returns: A link to a domain logo, if the domain logo exists.
                   5654: If the domain logo does not exist, a description of the domain.
                   5655: 
                   5656: =cut
1.112     bowersj2 5657: 
1.63      www      5658: ###############################################
                   5659: sub domainlogo {
1.517     raeburn  5660:     my $domain = &determinedomain(shift);
1.518     albertel 5661:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5662:     # See if there is a logo
                   5663:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5664:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5665:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5666: 	    if ($imgsrc =~ m{^/res/}) {
                   5667: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5668: 		&Apache::lonnet::repcopy($local_name);
                   5669: 	    }
                   5670: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5671:22):         }
                   5672:22):         my $alttext = $domain;
                   5673:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5674:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5675:22):         }
                   5676:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5677:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5678:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5679:     } else {
1.60      matthew  5680:         return '';
1.59      www      5681:     }
                   5682: }
1.63      www      5683: ##############################################
                   5684: 
                   5685: =pod
                   5686: 
1.112     bowersj2 5687: =item * &designparm()
1.63      www      5688: 
                   5689: Inputs: $which parameter; $domain (usually will be undef)
                   5690: 
                   5691: Returns: value of designparamter $which
                   5692: 
                   5693: =cut
1.112     bowersj2 5694: 
1.397     albertel 5695: 
1.400     albertel 5696: ##############################################
1.397     albertel 5697: sub designparm {
                   5698:     my ($which,$domain)=@_;
                   5699:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5700:         return $env{'environment.color.'.$which};
1.96      www      5701:     }
1.63      www      5702:     $domain=&determinedomain($domain);
1.1016    raeburn  5703:     my %domdesign;
                   5704:     unless ($domain eq 'public') {
                   5705:         %domdesign = &get_domainconf($domain);
                   5706:     }
1.520     raeburn  5707:     my $output;
1.517     raeburn  5708:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5709:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5710:     } else {
1.520     raeburn  5711:         $output = $defaultdesign{$which};
                   5712:     }
                   5713:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5714:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5715:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5716:             if ($output =~ m{^/res/}) {
                   5717:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5718:                 &Apache::lonnet::repcopy($local_name);
                   5719:             }
1.520     raeburn  5720:             $output = &lonhttpdurl($output);
                   5721:         }
1.63      www      5722:     }
1.520     raeburn  5723:     return $output;
1.63      www      5724: }
1.59      www      5725: 
1.822     bisitz   5726: ##############################################
                   5727: =pod
                   5728: 
1.832     bisitz   5729: =item * &authorspace()
                   5730: 
1.1028    raeburn  5731: Inputs: $url (usually will be undef).
1.832     bisitz   5732: 
1.1075.2.40  raeburn  5733: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5734:          directory being viewed (or for which action is being taken). 
                   5735:          If $url is provided, and begins /priv/<domain>/<uname>
                   5736:          the path will be that portion of the $context argument.
                   5737:          Otherwise the path will be for the author space of the current
                   5738:          user when the current role is author, or for that of the 
                   5739:          co-author/assistant co-author space when the current role 
                   5740:          is co-author or assistant co-author.
1.832     bisitz   5741: 
                   5742: =cut
                   5743: 
                   5744: sub authorspace {
1.1028    raeburn  5745:     my ($url) = @_;
                   5746:     if ($url ne '') {
                   5747:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5748:            return $1;
                   5749:         }
                   5750:     }
1.832     bisitz   5751:     my $caname = '';
1.1024    www      5752:     my $cadom = '';
1.1028    raeburn  5753:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5754:         ($cadom,$caname) =
1.832     bisitz   5755:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5756:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5757:         $caname = $env{'user.name'};
1.1024    www      5758:         $cadom = $env{'user.domain'};
1.832     bisitz   5759:     }
1.1028    raeburn  5760:     if (($caname ne '') && ($cadom ne '')) {
                   5761:         return "/priv/$cadom/$caname/";
                   5762:     }
                   5763:     return;
1.832     bisitz   5764: }
                   5765: 
                   5766: ##############################################
                   5767: =pod
                   5768: 
1.822     bisitz   5769: =item * &head_subbox()
                   5770: 
                   5771: Inputs: $content (contains HTML code with page functions, etc.)
                   5772: 
                   5773: Returns: HTML div with $content
                   5774:          To be included in page header
                   5775: 
                   5776: =cut
                   5777: 
                   5778: sub head_subbox {
                   5779:     my ($content)=@_;
                   5780:     my $output =
1.993     raeburn  5781:         '<div class="LC_head_subbox">'
1.822     bisitz   5782:        .$content
                   5783:        .'</div>'
                   5784: }
                   5785: 
                   5786: ##############################################
                   5787: =pod
                   5788: 
                   5789: =item * &CSTR_pageheader()
                   5790: 
1.1026    raeburn  5791: Input: (optional) filename from which breadcrumb trail is built.
                   5792:        In most cases no input as needed, as $env{'request.filename'}
                   5793:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5794:22):        frameset flag
                   5795:22):        If page header is being requested for use in a frameset, then
                   5796:22):        the second (option) argument -- frameset will be true, and
                   5797:22):        the target attribute set for links should be target="_parent".
1.822     bisitz   5798: 
                   5799: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5800:          To be included on Authoring Space pages
1.822     bisitz   5801: 
                   5802: =cut
                   5803: 
                   5804: sub CSTR_pageheader {
1.1075.2.161.  .6(raebu 5805:22):     my ($trailfile,$frameset) = @_;
1.1026    raeburn  5806:     if ($trailfile eq '') {
                   5807:         $trailfile = $env{'request.filename'};
                   5808:     }
                   5809: 
                   5810: # this is for resources; directories have customtitle, and crumbs
                   5811: # and select recent are created in lonpubdir.pm
                   5812: 
                   5813:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5814:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5815:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5816:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5817:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5818: 
                   5819:     my $parentpath = '';
                   5820:     my $lastitem = '';
                   5821:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5822:         $parentpath = $1;
                   5823:         $lastitem = $2;
                   5824:     } else {
                   5825:         $lastitem = $thisdisfn;
                   5826:     }
1.921     bisitz   5827: 
1.1075.2.161.  .6(raebu 5828:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   5829:22):     if ($frameset) {
                   5830:22):         $target = ' target="_parent"';
                   5831:22):         $crumbtarget = '_parent';
                   5832:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   5833:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   5834:22):         $crumbtarget = $env{'request.deeplink.target'};
                   5835:22):     }
                   5836:22): 
1.921     bisitz   5837:     my $output =
1.822     bisitz   5838:          '<div>'
                   5839:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5840:         .'<b>'.&mt('Authoring Space:').'</b> '
1.1075.2.161.  .6(raebu 5841:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5842:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5843: 
                   5844:     if ($lastitem) {
                   5845:         $output .=
                   5846:              '<span class="LC_filename">'
                   5847:             .$lastitem
                   5848:             .'</span>';
                   5849:     }
                   5850:     $output .=
                   5851:          '<br />'
1.1075.2.161.  .6(raebu 5852:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   5853:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5854:         .'</form>'
1.1075.2.161.  .6(raebu 5855:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   5856:         .'</div>';
1.921     bisitz   5857: 
                   5858:     return $output;
1.822     bisitz   5859: }
                   5860: 
1.60      matthew  5861: ###############################################
                   5862: ###############################################
                   5863: 
                   5864: =pod
                   5865: 
1.112     bowersj2 5866: =back
                   5867: 
1.549     albertel 5868: =head1 HTML Helpers
1.112     bowersj2 5869: 
                   5870: =over 4
                   5871: 
                   5872: =item * &bodytag()
1.60      matthew  5873: 
                   5874: Returns a uniform header for LON-CAPA web pages.
                   5875: 
                   5876: Inputs: 
                   5877: 
1.112     bowersj2 5878: =over 4
                   5879: 
                   5880: =item * $title, A title to be displayed on the page.
                   5881: 
                   5882: =item * $function, the current role (can be undef).
                   5883: 
                   5884: =item * $addentries, extra parameters for the <body> tag.
                   5885: 
                   5886: =item * $bodyonly, if defined, only return the <body> tag.
                   5887: 
                   5888: =item * $domain, if defined, force a given domain.
                   5889: 
                   5890: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5891:             text interface only)
1.60      matthew  5892: 
1.814     bisitz   5893: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5894:                      navigational links
1.317     albertel 5895: 
1.338     albertel 5896: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5897: 
1.1075.2.12  raeburn  5898: =item * $no_inline_link, if true and in remote mode, don't show the
                   5899:          'Switch To Inline Menu' link
                   5900: 
1.460     albertel 5901: =item * $args, optional argument valid values are
                   5902:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5903:             use_absolute     -> for external resource or syllabus, this will
                   5904:                                 contain https://<hostname> if server uses
                   5905:                                 https (as per hosts.tab), but request is for http
                   5906:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5907: 
1.1075.2.15  raeburn  5908: =item * $advtoolsref, optional argument, ref to an array containing
                   5909:             inlineremote items to be added in "Functions" menu below
                   5910:             breadcrumbs.
                   5911: 
1.1075.2.161.  .1(raebu 5912:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   5913:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   5914:21):             the scope of use, i.e., launch was for access to a single, a map
                   5915:21):             or the entire course.
                   5916:21): 
                   5917:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   5918:21):             context, this will contain the URL for the landing item in
                   5919:21):             the course, after launch from an LTI Consumer
                   5920:21): 
                   5921:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   5922:21):             context, this will contain a reference to hash of items
                   5923:21):             to be included in the page header and/or inline menu.
                   5924:21): 
          .8(raebu 5925:22): =item * $menucoll, optional argument, if specific menu collection is in
                   5926:22):             effect, either set as the default for the course, or set for
                   5927:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   5928:22):             then $menucoll will be the number of that collection.
                   5929:22): 
                   5930:22): =item * $menuref, optional argument, reference to a hash, containing the
                   5931:22):             menu options included for the menu in effect, based on the
                   5932:22):             configuration for the numbered menu collection in use.
                   5933:22): 
                   5934:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   5935:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   5936:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   5937:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   5938:22):             being called a second time.
                   5939:22): 
1.112     bowersj2 5940: =back
                   5941: 
1.60      matthew  5942: Returns: A uniform header for LON-CAPA web pages.  
                   5943: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5944: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5945: other decorations will be returned.
                   5946: 
                   5947: =cut
                   5948: 
1.54      www      5949: sub bodytag {
1.831     bisitz   5950:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 5951:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 5952:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 5953: 
1.954     raeburn  5954:     my $public;
                   5955:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5956:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5957:         $public = 1;
                   5958:     }
1.460     albertel 5959:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5960:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5961:     my $hostname = $args->{'hostname'};
1.339     albertel 5962: 
1.183     matthew  5963:     $function = &get_users_function() if (!$function);
1.339     albertel 5964:     my $img =    &designparm($function.'.img',$domain);
                   5965:     my $font =   &designparm($function.'.font',$domain);
                   5966:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5967: 
1.803     bisitz   5968:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5969: 		   'bgcolor' => $pgbg,
1.339     albertel 5970: 		   'text'    => $font,
                   5971:                    'alink'   => &designparm($function.'.alink',$domain),
                   5972: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5973: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5974:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5975: 
1.63      www      5976:  # role and realm
1.1075.2.68  raeburn  5977:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5978:     if ($realm) {
                   5979:         $realm = '/'.$realm;
                   5980:     }
1.1075.2.159  raeburn  5981:     if ($role eq 'ca') {
1.479     albertel 5982:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5983:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5984:     } 
1.55      www      5985: # realm
1.1075.2.158  raeburn  5986:     my ($cid,$sec);
1.258     albertel 5987:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  5988:         $cid = $env{'request.course.id'};
                   5989:         if ($env{'request.course.sec'}) {
                   5990:             $sec = $env{'request.course.sec'};
                   5991:         }
                   5992:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   5993:         if (&Apache::lonnet::is_course($1,$2)) {
                   5994:             $cid = $1.'_'.$2;
                   5995:             $sec = $3;
                   5996:         }
                   5997:     }
                   5998:     if ($cid) {
1.378     raeburn  5999:         if ($env{'request.role'} !~ /^cr/) {
                   6000:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6001:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6002:             if ($env{'request.role.desc'}) {
                   6003:                 $role = $env{'request.role.desc'};
                   6004:             } else {
                   6005:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6006:             }
1.1075.2.115  raeburn  6007:         } else {
                   6008:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6009:         }
1.1075.2.158  raeburn  6010:         if ($sec) {
                   6011:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6012:         }   
1.1075.2.158  raeburn  6013: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6014:     } else {
                   6015:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6016:     }
1.433     albertel 6017: 
1.359     albertel 6018:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6019: 
1.438     albertel 6020:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6021: 
1.101     www      6022: # construct main body tag
1.359     albertel 6023:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6024: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6025: 
1.1075.2.38  raeburn  6026:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6027: 
                   6028:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6029:         return $bodytag;
1.1075.2.38  raeburn  6030:     }
1.359     albertel 6031: 
1.954     raeburn  6032:     if ($public) {
1.433     albertel 6033: 	undef($role);
                   6034:     }
1.1075.2.158  raeburn  6035: 
1.1075.2.161.  .1(raebu 6036:21):     my $showcrstitle = 1;
                   6037:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6038:21):         if (ref($ltimenu) eq 'HASH') {
                   6039:21):             unless ($ltimenu->{'role'}) {
                   6040:21):                 undef($role);
                   6041:21):             }
                   6042:21):             unless ($ltimenu->{'coursetitle'}) {
                   6043:21):                 $realm='&nbsp;';
                   6044:21):                 $showcrstitle = 0;
                   6045:21):             }
                   6046:21):         }
                   6047:21):     } elsif (($cid) && ($menucoll)) {
                   6048:21):         if (ref($menuref) eq 'HASH') {
                   6049:21):             unless ($menuref->{'role'}) {
                   6050:21):                 undef($role);
                   6051:21):             }
                   6052:21):             unless ($menuref->{'crs'}) {
                   6053:21):                 $realm='&nbsp;';
                   6054:21):                 $showcrstitle = 0;
                   6055:21):             }
                   6056:21):         }
                   6057:21):     }
                   6058:21): 
1.762     bisitz   6059:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6060:     #
                   6061:     # Extra info if you are the DC
                   6062:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6063:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6064:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6065:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6066:         $dc_info =~ s/\s+$//;
1.359     albertel 6067:     }
                   6068: 
1.1075.2.161.  .1(raebu 6069:21):     my $crstype;
                   6070:21):     if ($cid) {
                   6071:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6072:21):     } elsif ($args->{'crstype'}) {
                   6073:21):         $crstype = $args->{'crstype'};
                   6074:21):     }
                   6075:21): 
1.1075.2.108  raeburn  6076:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6077: 
1.1075.2.13  raeburn  6078:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6079: 
1.1075.2.38  raeburn  6080: 
                   6081: 
1.1075.2.21  raeburn  6082:     my $funclist;
                   6083:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  6084:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  6085:                     Apache::lonmenu::serverform();
                   6086:         my $forbodytag;
                   6087:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6088:                                             $forcereg,$args->{'group'},
                   6089:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6090:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  6091:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6092:             $funclist = $forbodytag;
                   6093:         }
                   6094:     } else {
1.903     droeschl 6095: 
                   6096:         #    if ($env{'request.state'} eq 'construct') {
                   6097:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6098:         #    }
                   6099: 
1.1075.2.38  raeburn  6100:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6101:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6102: 
1.1075.2.161.  .1(raebu 6103:21):         unless ($args->{'no_primary_menu'}) {
          .4(raebu 6104:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6105:22):                                                               $args->{'links_disabled'},
                   6106:22):                                                               $args->{'links_target'});
          .1(raebu 6107:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6108:21):                 if ($dc_info) {
                   6109:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6110:21):                 }
                   6111:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6112:21):                                <em>$realm</em> $dc_info</div>|;
                   6113:21):                 return $bodytag;
1.1075.2.1  raeburn  6114:             }
1.894     droeschl 6115: 
1.1075.2.161.  .1(raebu 6116:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6117:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6118:21):             }
1.916     droeschl 6119: 
1.1075.2.161.  .1(raebu 6120:21):             $bodytag .= $right;
1.852     droeschl 6121: 
1.1075.2.161.  .1(raebu 6122:21):             if ($dc_info) {
                   6123:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6124:21):             }
                   6125:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6126:         }
1.916     droeschl 6127: 
1.1075.2.61  raeburn  6128:         #if directed to not display the secondary menu, don't.
                   6129:         if ($args->{'no_secondary_menu'}) {
                   6130:             return $bodytag;
                   6131:         }
1.903     droeschl 6132:         #don't show menus for public users
1.954     raeburn  6133:         if (!$public){
1.1075.2.161.  .1(raebu 6134:21):             unless ($args->{'no_inline_menu'}) {
                   6135:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6136:21):                                                             $args->{'no_primary_menu'},
                   6137:21):                                                             $menucoll,$menuref,
          .6(raebu 6138:22):                                                             $args->{'links_disabled'},
                   6139:22):                                                             $args->{'links_target'});
          .1(raebu 6140:21):             }
1.903     droeschl 6141:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6142:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6143:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6144:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6145:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6146:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6147:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6148:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6149:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6150:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6151:             } else {
1.1075.2.21  raeburn  6152:                 my $forbodytag;
                   6153:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6154:                                                     $forcereg,$args->{'group'},
                   6155:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6156:                                                     $advtoolsref,'',$hostname,
                   6157:                                                     \$forbodytag);
1.1075.2.21  raeburn  6158:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6159:                     $bodytag .= $forbodytag;
                   6160:                 }
1.920     raeburn  6161:             }
1.903     droeschl 6162:         }else{
                   6163:             # this is to seperate menu from content when there's no secondary
                   6164:             # menu. Especially needed for public accessible ressources.
                   6165:             $bodytag .= '<hr style="clear:both" />';
                   6166:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6167:         }
1.903     droeschl 6168: 
1.235     raeburn  6169:         return $bodytag;
1.1075.2.12  raeburn  6170:     }
                   6171: 
                   6172: #
                   6173: # Top frame rendering, Remote is up
                   6174: #
                   6175: 
                   6176:     my $imgsrc = $img;
                   6177:     if ($img =~ /^\/adm/) {
                   6178:         $imgsrc = &lonhttpdurl($img);
                   6179:     }
                   6180:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   6181: 
1.1075.2.60  raeburn  6182:     my $help=($no_inline_link?''
                   6183:               :&Apache::loncommon::top_nav_help('Help'));
                   6184: 
1.1075.2.12  raeburn  6185:     # Explicit link to get inline menu
                   6186:     my $menu= ($no_inline_link?''
                   6187:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6188: 
                   6189:     if ($dc_info) {
                   6190:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6191:     }
                   6192: 
1.1075.2.38  raeburn  6193:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6194:     unless ($public) {
                   6195:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6196:                                 undef,'LC_menubuttons_link');
                   6197:     }
                   6198: 
1.1075.2.12  raeburn  6199:     unless ($env{'form.inhibitmenu'}) {
                   6200:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  6201:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  6202:                        <li>$help</li>
1.1075.2.12  raeburn  6203:                        <li>$menu</li>
                   6204:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6205:     }
1.1075.2.13  raeburn  6206:     if ($env{'request.state'} eq 'construct') {
                   6207:         if (!$public){
                   6208:             if ($env{'request.state'} eq 'construct') {
                   6209:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6210:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  6211:                             &Apache::lonhtmlcommon::scripttag('','end').
                   6212:                             &Apache::lonmenu::innerregister($forcereg,
                   6213:                                                             $args->{'bread_crumbs'});
                   6214:             }
                   6215:         }
                   6216:     }
1.1075.2.21  raeburn  6217:     return $bodytag."\n".$funclist;
1.182     matthew  6218: }
                   6219: 
1.917     raeburn  6220: sub dc_courseid_toggle {
                   6221:     my ($dc_info) = @_;
1.980     raeburn  6222:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6223:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6224:            &mt('(More ...)').'</a></span>'.
                   6225:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6226: }
                   6227: 
1.330     albertel 6228: sub make_attr_string {
                   6229:     my ($register,$attr_ref) = @_;
                   6230: 
                   6231:     if ($attr_ref && !ref($attr_ref)) {
                   6232: 	die("addentries Must be a hash ref ".
                   6233: 	    join(':',caller(1))." ".
                   6234: 	    join(':',caller(0))." ");
                   6235:     }
                   6236: 
                   6237:     if ($register) {
1.339     albertel 6238: 	my ($on_load,$on_unload);
                   6239: 	foreach my $key (keys(%{$attr_ref})) {
                   6240: 	    if      (lc($key) eq 'onload') {
                   6241: 		$on_load.=$attr_ref->{$key}.';';
                   6242: 		delete($attr_ref->{$key});
                   6243: 
                   6244: 	    } elsif (lc($key) eq 'onunload') {
                   6245: 		$on_unload.=$attr_ref->{$key}.';';
                   6246: 		delete($attr_ref->{$key});
                   6247: 	    }
                   6248: 	}
1.1075.2.12  raeburn  6249:         if ($env{'environment.remote'} eq 'on') {
                   6250:             $attr_ref->{'onload'}  =
                   6251:                 &Apache::lonmenu::loadevents().  $on_load;
                   6252:             $attr_ref->{'onunload'}=
                   6253:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6254:         } else {  
                   6255: 	    $attr_ref->{'onload'}  = $on_load;
                   6256: 	    $attr_ref->{'onunload'}= $on_unload;
                   6257:         }
1.330     albertel 6258:     }
1.339     albertel 6259: 
1.330     albertel 6260:     my $attr_string;
1.1075.2.56  raeburn  6261:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6262: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6263:     }
                   6264:     return $attr_string;
                   6265: }
                   6266: 
                   6267: 
1.182     matthew  6268: ###############################################
1.251     albertel 6269: ###############################################
                   6270: 
                   6271: =pod
                   6272: 
                   6273: =item * &endbodytag()
                   6274: 
                   6275: Returns a uniform footer for LON-CAPA web pages.
                   6276: 
1.635     raeburn  6277: Inputs: 1 - optional reference to an args hash
                   6278: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6279: a 'Continue' link is not displayed if the page contains an
                   6280: internal redirect in the <head></head> section,
                   6281: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6282: 
                   6283: =cut
                   6284: 
                   6285: sub endbodytag {
1.635     raeburn  6286:     my ($args) = @_;
1.1075.2.6  raeburn  6287:     my $endbodytag;
                   6288:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6289:         $endbodytag='</body>';
                   6290:     }
1.315     albertel 6291:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6292:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6293:22):             my ($endbodyjs,$idattr);
                   6294:22):             if ($env{'internal.head.to_opener'}) {
                   6295:22):                 my $linkid = 'LC_continue_link';
                   6296:22):                 $idattr = ' id="'.$linkid.'"';
                   6297:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6298:22):                 $endbodyjs=<<ENDJS;
                   6299:22): <script type="text/javascript">
                   6300:22): // <![CDATA[
                   6301:22): function ebFunction(evt) {
                   6302:22):     evt.preventDefault();
                   6303:22):     var dest = '$redirect_for_js';
                   6304:22):     if (window.opener != null && !window.opener.closed) {
                   6305:22):         window.opener.location.href=dest;
                   6306:22):         window.close();
                   6307:22):     } else {
                   6308:22):         window.location.href=dest;
                   6309:22):     }
                   6310:22):     return false;
                   6311:22): }
                   6312:22): 
                   6313:22): \$(document).ready(function () {
                   6314:22):   if (document.getElementById('$linkid')) {
                   6315:22):     var clickelem = document.getElementById('$linkid');
                   6316:22):     clickelem.addEventListener('click',ebFunction,false);
                   6317:22):   }
                   6318:22): });
                   6319:22): // ]]>
                   6320:22): </script>
                   6321:22): ENDJS
                   6322:22):             }
1.635     raeburn  6323: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6324:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6325: 	        &mt('Continue').'</a>'.
                   6326: 	        $endbodytag;
                   6327:         }
1.315     albertel 6328:     }
1.251     albertel 6329:     return $endbodytag;
                   6330: }
                   6331: 
1.352     albertel 6332: =pod
                   6333: 
                   6334: =item * &standard_css()
                   6335: 
                   6336: Returns a style sheet
                   6337: 
                   6338: Inputs: (all optional)
                   6339:             domain         -> force to color decorate a page for a specific
                   6340:                                domain
                   6341:             function       -> force usage of a specific rolish color scheme
                   6342:             bgcolor        -> override the default page bgcolor
                   6343: 
                   6344: =cut
                   6345: 
1.343     albertel 6346: sub standard_css {
1.345     albertel 6347:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6348:     $function  = &get_users_function() if (!$function);
                   6349:     my $img    = &designparm($function.'.img',   $domain);
                   6350:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6351:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6352:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6353: #second colour for later usage
1.345     albertel 6354:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6355:     my $pgbg_or_bgcolor =
                   6356: 	         $bgcolor ||
1.352     albertel 6357: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6358:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6359:     my $alink  = &designparm($function.'.alink', $domain);
                   6360:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6361:     my $link   = &designparm($function.'.link',  $domain);
                   6362: 
1.602     albertel 6363:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6364:     my $mono                 = 'monospace';
1.850     bisitz   6365:     my $data_table_head      = $sidebg;
                   6366:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6367:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6368:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6369:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6370:     my $mail_new             = '#FFBB77';
                   6371:     my $mail_new_hover       = '#DD9955';
                   6372:     my $mail_read            = '#BBBB77';
                   6373:     my $mail_read_hover      = '#999944';
                   6374:     my $mail_replied         = '#AAAA88';
                   6375:     my $mail_replied_hover   = '#888855';
                   6376:     my $mail_other           = '#99BBBB';
                   6377:     my $mail_other_hover     = '#669999';
1.391     albertel 6378:     my $table_header         = '#DDDDDD';
1.489     raeburn  6379:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6380:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6381:     my $button_hover         = '#BF2317';
1.392     albertel 6382: 
1.608     albertel 6383:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6384:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6385:                                              : '0 3px 0 4px';
1.448     albertel 6386: 
1.523     albertel 6387: 
1.343     albertel 6388:     return <<END;
1.947     droeschl 6389: 
                   6390: /* needed for iframe to allow 100% height in FF */
                   6391: body, html { 
                   6392:     margin: 0;
                   6393:     padding: 0 0.5%;
                   6394:     height: 99%; /* to avoid scrollbars */
                   6395: }
                   6396: 
1.795     www      6397: body {
1.911     bisitz   6398:   font-family: $sans;
                   6399:   line-height:130%;
                   6400:   font-size:0.83em;
                   6401:   color:$font;
1.795     www      6402: }
                   6403: 
1.959     onken    6404: a:focus,
                   6405: a:focus img {
1.795     www      6406:   color: red;
                   6407: }
1.698     harmsja  6408: 
1.911     bisitz   6409: form, .inline {
                   6410:   display: inline;
1.795     www      6411: }
1.721     harmsja  6412: 
1.795     www      6413: .LC_right {
1.911     bisitz   6414:   text-align:right;
1.795     www      6415: }
                   6416: 
                   6417: .LC_middle {
1.911     bisitz   6418:   vertical-align:middle;
1.795     www      6419: }
1.721     harmsja  6420: 
1.1075.2.38  raeburn  6421: .LC_floatleft {
                   6422:   float: left;
                   6423: }
                   6424: 
                   6425: .LC_floatright {
                   6426:   float: right;
                   6427: }
                   6428: 
1.911     bisitz   6429: .LC_400Box {
                   6430:   width:400px;
                   6431: }
1.721     harmsja  6432: 
1.947     droeschl 6433: .LC_iframecontainer {
                   6434:     width: 98%;
                   6435:     margin: 0;
                   6436:     position: fixed;
                   6437:     top: 8.5em;
                   6438:     bottom: 0;
                   6439: }
                   6440: 
                   6441: .LC_iframecontainer iframe{
                   6442:     border: none;
                   6443:     width: 100%;
                   6444:     height: 100%;
                   6445: }
                   6446: 
1.778     bisitz   6447: .LC_filename {
                   6448:   font-family: $mono;
                   6449:   white-space:pre;
1.921     bisitz   6450:   font-size: 120%;
1.778     bisitz   6451: }
                   6452: 
                   6453: .LC_fileicon {
                   6454:   border: none;
                   6455:   height: 1.3em;
                   6456:   vertical-align: text-bottom;
                   6457:   margin-right: 0.3em;
                   6458:   text-decoration:none;
                   6459: }
                   6460: 
1.1008    www      6461: .LC_setting {
                   6462:   text-decoration:underline;
                   6463: }
                   6464: 
1.350     albertel 6465: .LC_error {
                   6466:   color: red;
                   6467: }
1.795     www      6468: 
1.1075.2.15  raeburn  6469: .LC_warning {
                   6470:   color: darkorange;
                   6471: }
                   6472: 
1.457     albertel 6473: .LC_diff_removed {
1.733     bisitz   6474:   color: red;
1.394     albertel 6475: }
1.532     albertel 6476: 
                   6477: .LC_info,
1.457     albertel 6478: .LC_success,
                   6479: .LC_diff_added {
1.350     albertel 6480:   color: green;
                   6481: }
1.795     www      6482: 
1.802     bisitz   6483: div.LC_confirm_box {
                   6484:   background-color: #FAFAFA;
                   6485:   border: 1px solid $lg_border_color;
                   6486:   margin-right: 0;
                   6487:   padding: 5px;
                   6488: }
                   6489: 
                   6490: div.LC_confirm_box .LC_error img,
                   6491: div.LC_confirm_box .LC_success img {
                   6492:   vertical-align: middle;
                   6493: }
                   6494: 
1.1075.2.108  raeburn  6495: .LC_maxwidth {
                   6496:   max-width: 100%;
                   6497:   height: auto;
                   6498: }
                   6499: 
                   6500: .LC_textsize_mobile {
                   6501:   \@media only screen and (max-device-width: 480px) {
                   6502:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6503:   }
                   6504: }
                   6505: 
1.440     albertel 6506: .LC_icon {
1.771     droeschl 6507:   border: none;
1.790     droeschl 6508:   vertical-align: middle;
1.771     droeschl 6509: }
                   6510: 
1.543     albertel 6511: .LC_docs_spacer {
                   6512:   width: 25px;
                   6513:   height: 1px;
1.771     droeschl 6514:   border: none;
1.543     albertel 6515: }
1.346     albertel 6516: 
1.532     albertel 6517: .LC_internal_info {
1.735     bisitz   6518:   color: #999999;
1.532     albertel 6519: }
                   6520: 
1.794     www      6521: .LC_discussion {
1.1050    www      6522:   background: $data_table_dark;
1.911     bisitz   6523:   border: 1px solid black;
                   6524:   margin: 2px;
1.794     www      6525: }
                   6526: 
                   6527: .LC_disc_action_left {
1.1050    www      6528:   background: $sidebg;
1.911     bisitz   6529:   text-align: left;
1.1050    www      6530:   padding: 4px;
                   6531:   margin: 2px;
1.794     www      6532: }
                   6533: 
                   6534: .LC_disc_action_right {
1.1050    www      6535:   background: $sidebg;
1.911     bisitz   6536:   text-align: right;
1.1050    www      6537:   padding: 4px;
                   6538:   margin: 2px;
1.794     www      6539: }
                   6540: 
                   6541: .LC_disc_new_item {
1.911     bisitz   6542:   background: white;
                   6543:   border: 2px solid red;
1.1050    www      6544:   margin: 4px;
                   6545:   padding: 4px;
1.794     www      6546: }
                   6547: 
                   6548: .LC_disc_old_item {
1.911     bisitz   6549:   background: white;
1.1050    www      6550:   margin: 4px;
                   6551:   padding: 4px;
1.794     www      6552: }
                   6553: 
1.458     albertel 6554: table.LC_pastsubmission {
                   6555:   border: 1px solid black;
                   6556:   margin: 2px;
                   6557: }
                   6558: 
1.924     bisitz   6559: table#LC_menubuttons {
1.345     albertel 6560:   width: 100%;
                   6561:   background: $pgbg;
1.392     albertel 6562:   border: 2px;
1.402     albertel 6563:   border-collapse: separate;
1.803     bisitz   6564:   padding: 0;
1.345     albertel 6565: }
1.392     albertel 6566: 
1.801     tempelho 6567: table#LC_title_bar a {
                   6568:   color: $fontmenu;
                   6569: }
1.836     bisitz   6570: 
1.807     droeschl 6571: table#LC_title_bar {
1.819     tempelho 6572:   clear: both;
1.836     bisitz   6573:   display: none;
1.807     droeschl 6574: }
                   6575: 
1.795     www      6576: table#LC_title_bar,
1.933     droeschl 6577: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6578: table#LC_title_bar.LC_with_remote {
1.359     albertel 6579:   width: 100%;
1.392     albertel 6580:   border-color: $pgbg;
                   6581:   border-style: solid;
                   6582:   border-width: $border;
1.379     albertel 6583:   background: $pgbg;
1.801     tempelho 6584:   color: $fontmenu;
1.392     albertel 6585:   border-collapse: collapse;
1.803     bisitz   6586:   padding: 0;
1.819     tempelho 6587:   margin: 0;
1.359     albertel 6588: }
1.795     www      6589: 
1.933     droeschl 6590: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6591:     margin: 0;
                   6592:     padding: 0;
1.933     droeschl 6593:     position: relative;
                   6594:     list-style: none;
1.913     droeschl 6595: }
1.933     droeschl 6596: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6597:     display: inline;
                   6598: }
1.933     droeschl 6599: 
                   6600: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6601:     padding: 0;
1.933     droeschl 6602:     margin: 0;
                   6603:     float: left;
1.913     droeschl 6604: }
1.933     droeschl 6605: .LC_breadcrumb_tools_tools {
                   6606:     padding: 0;
                   6607:     margin: 0;
1.913     droeschl 6608:     float: right;
                   6609: }
                   6610: 
1.359     albertel 6611: table#LC_title_bar td {
                   6612:   background: $tabbg;
                   6613: }
1.795     www      6614: 
1.911     bisitz   6615: table#LC_menubuttons img {
1.803     bisitz   6616:   border: none;
1.346     albertel 6617: }
1.795     www      6618: 
1.842     droeschl 6619: .LC_breadcrumbs_component {
1.911     bisitz   6620:   float: right;
                   6621:   margin: 0 1em;
1.357     albertel 6622: }
1.842     droeschl 6623: .LC_breadcrumbs_component img {
1.911     bisitz   6624:   vertical-align: middle;
1.777     tempelho 6625: }
1.795     www      6626: 
1.1075.2.108  raeburn  6627: .LC_breadcrumbs_hoverable {
                   6628:   background: $sidebg;
                   6629: }
                   6630: 
1.383     albertel 6631: td.LC_table_cell_checkbox {
                   6632:   text-align: center;
                   6633: }
1.795     www      6634: 
                   6635: .LC_fontsize_small {
1.911     bisitz   6636:   font-size: 70%;
1.705     tempelho 6637: }
                   6638: 
1.844     bisitz   6639: #LC_breadcrumbs {
1.911     bisitz   6640:   clear:both;
                   6641:   background: $sidebg;
                   6642:   border-bottom: 1px solid $lg_border_color;
                   6643:   line-height: 2.5em;
1.933     droeschl 6644:   overflow: hidden;
1.911     bisitz   6645:   margin: 0;
                   6646:   padding: 0;
1.995     raeburn  6647:   text-align: left;
1.819     tempelho 6648: }
1.862     bisitz   6649: 
1.1075.2.16  raeburn  6650: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6651:   clear:both;
                   6652:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6653:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6654:   margin: 0 0 10px 0;
1.966     bisitz   6655:   padding: 3px;
1.995     raeburn  6656:   text-align: left;
1.822     bisitz   6657: }
                   6658: 
1.795     www      6659: .LC_fontsize_medium {
1.911     bisitz   6660:   font-size: 85%;
1.705     tempelho 6661: }
                   6662: 
1.795     www      6663: .LC_fontsize_large {
1.911     bisitz   6664:   font-size: 120%;
1.705     tempelho 6665: }
                   6666: 
1.346     albertel 6667: .LC_menubuttons_inline_text {
                   6668:   color: $font;
1.698     harmsja  6669:   font-size: 90%;
1.701     harmsja  6670:   padding-left:3px;
1.346     albertel 6671: }
                   6672: 
1.934     droeschl 6673: .LC_menubuttons_inline_text img{
                   6674:   vertical-align: middle;
                   6675: }
                   6676: 
1.1051    www      6677: li.LC_menubuttons_inline_text img {
1.951     onken    6678:   cursor:pointer;
1.1002    droeschl 6679:   text-decoration: none;
1.951     onken    6680: }
                   6681: 
1.526     www      6682: .LC_menubuttons_link {
                   6683:   text-decoration: none;
                   6684: }
1.795     www      6685: 
1.522     albertel 6686: .LC_menubuttons_category {
1.521     www      6687:   color: $font;
1.526     www      6688:   background: $pgbg;
1.521     www      6689:   font-size: larger;
                   6690:   font-weight: bold;
                   6691: }
                   6692: 
1.346     albertel 6693: td.LC_menubuttons_text {
1.911     bisitz   6694:   color: $font;
1.346     albertel 6695: }
1.706     harmsja  6696: 
1.346     albertel 6697: .LC_current_location {
                   6698:   background: $tabbg;
                   6699: }
1.795     www      6700: 
1.1075.2.134  raeburn  6701: td.LC_zero_height {
                   6702:   line-height: 0;
                   6703:   cellpadding: 0;
                   6704: }
                   6705: 
1.938     bisitz   6706: table.LC_data_table {
1.347     albertel 6707:   border: 1px solid #000000;
1.402     albertel 6708:   border-collapse: separate;
1.426     albertel 6709:   border-spacing: 1px;
1.610     albertel 6710:   background: $pgbg;
1.347     albertel 6711: }
1.795     www      6712: 
1.422     albertel 6713: .LC_data_table_dense {
                   6714:   font-size: small;
                   6715: }
1.795     www      6716: 
1.507     raeburn  6717: table.LC_nested_outer {
                   6718:   border: 1px solid #000000;
1.589     raeburn  6719:   border-collapse: collapse;
1.803     bisitz   6720:   border-spacing: 0;
1.507     raeburn  6721:   width: 100%;
                   6722: }
1.795     www      6723: 
1.879     raeburn  6724: table.LC_innerpickbox,
1.507     raeburn  6725: table.LC_nested {
1.803     bisitz   6726:   border: none;
1.589     raeburn  6727:   border-collapse: collapse;
1.803     bisitz   6728:   border-spacing: 0;
1.507     raeburn  6729:   width: 100%;
                   6730: }
1.795     www      6731: 
1.911     bisitz   6732: table.LC_data_table tr th,
                   6733: table.LC_calendar tr th,
1.879     raeburn  6734: table.LC_prior_tries tr th,
                   6735: table.LC_innerpickbox tr th {
1.349     albertel 6736:   font-weight: bold;
                   6737:   background-color: $data_table_head;
1.801     tempelho 6738:   color:$fontmenu;
1.701     harmsja  6739:   font-size:90%;
1.347     albertel 6740: }
1.795     www      6741: 
1.879     raeburn  6742: table.LC_innerpickbox tr th,
                   6743: table.LC_innerpickbox tr td {
                   6744:   vertical-align: top;
                   6745: }
                   6746: 
1.711     raeburn  6747: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6748:   background-color: #CCCCCC;
1.711     raeburn  6749:   font-weight: bold;
                   6750:   text-align: left;
                   6751: }
1.795     www      6752: 
1.912     bisitz   6753: table.LC_data_table tr.LC_odd_row > td {
                   6754:   background-color: $data_table_light;
                   6755:   padding: 2px;
                   6756:   vertical-align: top;
                   6757: }
                   6758: 
1.809     bisitz   6759: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6760:   background-color: $data_table_light;
1.912     bisitz   6761:   vertical-align: top;
                   6762: }
                   6763: 
                   6764: table.LC_data_table tr.LC_even_row > td {
                   6765:   background-color: $data_table_dark;
1.425     albertel 6766:   padding: 2px;
1.900     bisitz   6767:   vertical-align: top;
1.347     albertel 6768: }
1.795     www      6769: 
1.809     bisitz   6770: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6771:   background-color: $data_table_dark;
1.900     bisitz   6772:   vertical-align: top;
1.347     albertel 6773: }
1.795     www      6774: 
1.425     albertel 6775: table.LC_data_table tr.LC_data_table_highlight td {
                   6776:   background-color: $data_table_darker;
                   6777: }
1.795     www      6778: 
1.639     raeburn  6779: table.LC_data_table tr td.LC_leftcol_header {
                   6780:   background-color: $data_table_head;
                   6781:   font-weight: bold;
                   6782: }
1.795     www      6783: 
1.451     albertel 6784: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6785: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6786:   font-weight: bold;
                   6787:   font-style: italic;
                   6788:   text-align: center;
                   6789:   padding: 8px;
1.347     albertel 6790: }
1.795     www      6791: 
1.1075.2.30  raeburn  6792: table.LC_data_table tr.LC_empty_row td,
                   6793: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6794:   background-color: $sidebg;
                   6795: }
                   6796: 
                   6797: table.LC_nested tr.LC_empty_row td {
                   6798:   background-color: #FFFFFF;
                   6799: }
                   6800: 
1.890     droeschl 6801: table.LC_caption {
                   6802: }
                   6803: 
1.507     raeburn  6804: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6805:   padding: 4ex
                   6806: }
1.795     www      6807: 
1.507     raeburn  6808: table.LC_nested_outer tr th {
                   6809:   font-weight: bold;
1.801     tempelho 6810:   color:$fontmenu;
1.507     raeburn  6811:   background-color: $data_table_head;
1.701     harmsja  6812:   font-size: small;
1.507     raeburn  6813:   border-bottom: 1px solid #000000;
                   6814: }
1.795     www      6815: 
1.507     raeburn  6816: table.LC_nested_outer tr td.LC_subheader {
                   6817:   background-color: $data_table_head;
                   6818:   font-weight: bold;
                   6819:   font-size: small;
                   6820:   border-bottom: 1px solid #000000;
                   6821:   text-align: right;
1.451     albertel 6822: }
1.795     www      6823: 
1.507     raeburn  6824: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6825:   background-color: #CCCCCC;
1.451     albertel 6826:   font-weight: bold;
                   6827:   font-size: small;
1.507     raeburn  6828:   text-align: center;
                   6829: }
1.795     www      6830: 
1.589     raeburn  6831: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6832: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6833:   text-align: left;
1.451     albertel 6834: }
1.795     www      6835: 
1.507     raeburn  6836: table.LC_nested td {
1.735     bisitz   6837:   background-color: #FFFFFF;
1.451     albertel 6838:   font-size: small;
1.507     raeburn  6839: }
1.795     www      6840: 
1.507     raeburn  6841: table.LC_nested_outer tr th.LC_right_item,
                   6842: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6843: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6844: table.LC_nested tr td.LC_right_item {
1.451     albertel 6845:   text-align: right;
                   6846: }
                   6847: 
1.507     raeburn  6848: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6849:   background-color: #EEEEEE;
1.451     albertel 6850: }
                   6851: 
1.473     raeburn  6852: table.LC_createuser {
                   6853: }
                   6854: 
                   6855: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6856:   font-size: small;
1.473     raeburn  6857: }
                   6858: 
                   6859: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6860:   background-color: #CCCCCC;
1.473     raeburn  6861:   font-weight: bold;
                   6862:   text-align: center;
                   6863: }
                   6864: 
1.349     albertel 6865: table.LC_calendar {
                   6866:   border: 1px solid #000000;
                   6867:   border-collapse: collapse;
1.917     raeburn  6868:   width: 98%;
1.349     albertel 6869: }
1.795     www      6870: 
1.349     albertel 6871: table.LC_calendar_pickdate {
                   6872:   font-size: xx-small;
                   6873: }
1.795     www      6874: 
1.349     albertel 6875: table.LC_calendar tr td {
                   6876:   border: 1px solid #000000;
                   6877:   vertical-align: top;
1.917     raeburn  6878:   width: 14%;
1.349     albertel 6879: }
1.795     www      6880: 
1.349     albertel 6881: table.LC_calendar tr td.LC_calendar_day_empty {
                   6882:   background-color: $data_table_dark;
                   6883: }
1.795     www      6884: 
1.779     bisitz   6885: table.LC_calendar tr td.LC_calendar_day_current {
                   6886:   background-color: $data_table_highlight;
1.777     tempelho 6887: }
1.795     www      6888: 
1.938     bisitz   6889: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6890:   background-color: $mail_new;
                   6891: }
1.795     www      6892: 
1.938     bisitz   6893: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6894:   background-color: $mail_new_hover;
                   6895: }
1.795     www      6896: 
1.938     bisitz   6897: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6898:   background-color: $mail_read;
                   6899: }
1.795     www      6900: 
1.938     bisitz   6901: /*
                   6902: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6903:   background-color: $mail_read_hover;
                   6904: }
1.938     bisitz   6905: */
1.795     www      6906: 
1.938     bisitz   6907: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6908:   background-color: $mail_replied;
                   6909: }
1.795     www      6910: 
1.938     bisitz   6911: /*
                   6912: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6913:   background-color: $mail_replied_hover;
                   6914: }
1.938     bisitz   6915: */
1.795     www      6916: 
1.938     bisitz   6917: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6918:   background-color: $mail_other;
                   6919: }
1.795     www      6920: 
1.938     bisitz   6921: /*
                   6922: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6923:   background-color: $mail_other_hover;
                   6924: }
1.938     bisitz   6925: */
1.494     raeburn  6926: 
1.777     tempelho 6927: table.LC_data_table tr > td.LC_browser_file,
                   6928: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6929:   background: #AAEE77;
1.389     albertel 6930: }
1.795     www      6931: 
1.777     tempelho 6932: table.LC_data_table tr > td.LC_browser_file_locked,
                   6933: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6934:   background: #FFAA99;
1.387     albertel 6935: }
1.795     www      6936: 
1.777     tempelho 6937: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6938:   background: #888888;
1.779     bisitz   6939: }
1.795     www      6940: 
1.777     tempelho 6941: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6942: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6943:   background: #F8F866;
1.777     tempelho 6944: }
1.795     www      6945: 
1.696     bisitz   6946: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6947:   background: #E0E8FF;
1.387     albertel 6948: }
1.696     bisitz   6949: 
1.707     bisitz   6950: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6951:   /* background: #77FF77; */
1.707     bisitz   6952: }
1.795     www      6953: 
1.707     bisitz   6954: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6955:   border-right: 8px solid #FFFF77;
1.707     bisitz   6956: }
1.795     www      6957: 
1.707     bisitz   6958: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6959:   border-right: 8px solid #FFAA77;
1.707     bisitz   6960: }
1.795     www      6961: 
1.707     bisitz   6962: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6963:   border-right: 8px solid #FF7777;
1.707     bisitz   6964: }
1.795     www      6965: 
1.707     bisitz   6966: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6967:   border-right: 8px solid #AAFF77;
1.707     bisitz   6968: }
1.795     www      6969: 
1.707     bisitz   6970: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6971:   border-right: 8px solid #11CC55;
1.707     bisitz   6972: }
                   6973: 
1.388     albertel 6974: span.LC_current_location {
1.701     harmsja  6975:   font-size:larger;
1.388     albertel 6976:   background: $pgbg;
                   6977: }
1.387     albertel 6978: 
1.1029    www      6979: span.LC_current_nav_location {
                   6980:   font-weight:bold;
                   6981:   background: $sidebg;
                   6982: }
                   6983: 
1.395     albertel 6984: span.LC_parm_menu_item {
                   6985:   font-size: larger;
                   6986: }
1.795     www      6987: 
1.395     albertel 6988: span.LC_parm_scope_all {
                   6989:   color: red;
                   6990: }
1.795     www      6991: 
1.395     albertel 6992: span.LC_parm_scope_folder {
                   6993:   color: green;
                   6994: }
1.795     www      6995: 
1.395     albertel 6996: span.LC_parm_scope_resource {
                   6997:   color: orange;
                   6998: }
1.795     www      6999: 
1.395     albertel 7000: span.LC_parm_part {
                   7001:   color: blue;
                   7002: }
1.795     www      7003: 
1.911     bisitz   7004: span.LC_parm_folder,
                   7005: span.LC_parm_symb {
1.395     albertel 7006:   font-size: x-small;
                   7007:   font-family: $mono;
                   7008:   color: #AAAAAA;
                   7009: }
                   7010: 
1.977     bisitz   7011: ul.LC_parm_parmlist li {
                   7012:   display: inline-block;
                   7013:   padding: 0.3em 0.8em;
                   7014:   vertical-align: top;
                   7015:   width: 150px;
                   7016:   border-top:1px solid $lg_border_color;
                   7017: }
                   7018: 
1.795     www      7019: td.LC_parm_overview_level_menu,
                   7020: td.LC_parm_overview_map_menu,
                   7021: td.LC_parm_overview_parm_selectors,
                   7022: td.LC_parm_overview_restrictions  {
1.396     albertel 7023:   border: 1px solid black;
                   7024:   border-collapse: collapse;
                   7025: }
1.795     www      7026: 
1.396     albertel 7027: table.LC_parm_overview_restrictions td {
                   7028:   border-width: 1px 4px 1px 4px;
                   7029:   border-style: solid;
                   7030:   border-color: $pgbg;
                   7031:   text-align: center;
                   7032: }
1.795     www      7033: 
1.396     albertel 7034: table.LC_parm_overview_restrictions th {
                   7035:   background: $tabbg;
                   7036:   border-width: 1px 4px 1px 4px;
                   7037:   border-style: solid;
                   7038:   border-color: $pgbg;
                   7039: }
1.795     www      7040: 
1.398     albertel 7041: table#LC_helpmenu {
1.803     bisitz   7042:   border: none;
1.398     albertel 7043:   height: 55px;
1.803     bisitz   7044:   border-spacing: 0;
1.398     albertel 7045: }
                   7046: 
                   7047: table#LC_helpmenu fieldset legend {
                   7048:   font-size: larger;
                   7049: }
1.795     www      7050: 
1.397     albertel 7051: table#LC_helpmenu_links {
                   7052:   width: 100%;
                   7053:   border: 1px solid black;
                   7054:   background: $pgbg;
1.803     bisitz   7055:   padding: 0;
1.397     albertel 7056:   border-spacing: 1px;
                   7057: }
1.795     www      7058: 
1.397     albertel 7059: table#LC_helpmenu_links tr td {
                   7060:   padding: 1px;
                   7061:   background: $tabbg;
1.399     albertel 7062:   text-align: center;
                   7063:   font-weight: bold;
1.397     albertel 7064: }
1.396     albertel 7065: 
1.795     www      7066: table#LC_helpmenu_links a:link,
                   7067: table#LC_helpmenu_links a:visited,
1.397     albertel 7068: table#LC_helpmenu_links a:active {
                   7069:   text-decoration: none;
                   7070:   color: $font;
                   7071: }
1.795     www      7072: 
1.397     albertel 7073: table#LC_helpmenu_links a:hover {
                   7074:   text-decoration: underline;
                   7075:   color: $vlink;
                   7076: }
1.396     albertel 7077: 
1.417     albertel 7078: .LC_chrt_popup_exists {
                   7079:   border: 1px solid #339933;
                   7080:   margin: -1px;
                   7081: }
1.795     www      7082: 
1.417     albertel 7083: .LC_chrt_popup_up {
                   7084:   border: 1px solid yellow;
                   7085:   margin: -1px;
                   7086: }
1.795     www      7087: 
1.417     albertel 7088: .LC_chrt_popup {
                   7089:   border: 1px solid #8888FF;
                   7090:   background: #CCCCFF;
                   7091: }
1.795     www      7092: 
1.421     albertel 7093: table.LC_pick_box {
                   7094:   border-collapse: separate;
                   7095:   background: white;
                   7096:   border: 1px solid black;
                   7097:   border-spacing: 1px;
                   7098: }
1.795     www      7099: 
1.421     albertel 7100: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7101:   background: $sidebg;
1.421     albertel 7102:   font-weight: bold;
1.900     bisitz   7103:   text-align: left;
1.740     bisitz   7104:   vertical-align: top;
1.421     albertel 7105:   width: 184px;
                   7106:   padding: 8px;
                   7107: }
1.795     www      7108: 
1.579     raeburn  7109: table.LC_pick_box td.LC_pick_box_value {
                   7110:   text-align: left;
                   7111:   padding: 8px;
                   7112: }
1.795     www      7113: 
1.579     raeburn  7114: table.LC_pick_box td.LC_pick_box_select {
                   7115:   text-align: left;
                   7116:   padding: 8px;
                   7117: }
1.795     www      7118: 
1.424     albertel 7119: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7120:   padding: 0;
1.421     albertel 7121:   height: 1px;
                   7122:   background: black;
                   7123: }
1.795     www      7124: 
1.421     albertel 7125: table.LC_pick_box td.LC_pick_box_submit {
                   7126:   text-align: right;
                   7127: }
1.795     www      7128: 
1.579     raeburn  7129: table.LC_pick_box td.LC_evenrow_value {
                   7130:   text-align: left;
                   7131:   padding: 8px;
                   7132:   background-color: $data_table_light;
                   7133: }
1.795     www      7134: 
1.579     raeburn  7135: table.LC_pick_box td.LC_oddrow_value {
                   7136:   text-align: left;
                   7137:   padding: 8px;
                   7138:   background-color: $data_table_light;
                   7139: }
1.795     www      7140: 
1.579     raeburn  7141: span.LC_helpform_receipt_cat {
                   7142:   font-weight: bold;
                   7143: }
1.795     www      7144: 
1.424     albertel 7145: table.LC_group_priv_box {
                   7146:   background: white;
                   7147:   border: 1px solid black;
                   7148:   border-spacing: 1px;
                   7149: }
1.795     www      7150: 
1.424     albertel 7151: table.LC_group_priv_box td.LC_pick_box_title {
                   7152:   background: $tabbg;
                   7153:   font-weight: bold;
                   7154:   text-align: right;
                   7155:   width: 184px;
                   7156: }
1.795     www      7157: 
1.424     albertel 7158: table.LC_group_priv_box td.LC_groups_fixed {
                   7159:   background: $data_table_light;
                   7160:   text-align: center;
                   7161: }
1.795     www      7162: 
1.424     albertel 7163: table.LC_group_priv_box td.LC_groups_optional {
                   7164:   background: $data_table_dark;
                   7165:   text-align: center;
                   7166: }
1.795     www      7167: 
1.424     albertel 7168: table.LC_group_priv_box td.LC_groups_functionality {
                   7169:   background: $data_table_darker;
                   7170:   text-align: center;
                   7171:   font-weight: bold;
                   7172: }
1.795     www      7173: 
1.424     albertel 7174: table.LC_group_priv td {
                   7175:   text-align: left;
1.803     bisitz   7176:   padding: 0;
1.424     albertel 7177: }
                   7178: 
                   7179: .LC_navbuttons {
                   7180:   margin: 2ex 0ex 2ex 0ex;
                   7181: }
1.795     www      7182: 
1.423     albertel 7183: .LC_topic_bar {
                   7184:   font-weight: bold;
                   7185:   background: $tabbg;
1.918     wenzelju 7186:   margin: 1em 0em 1em 2em;
1.805     bisitz   7187:   padding: 3px;
1.918     wenzelju 7188:   font-size: 1.2em;
1.423     albertel 7189: }
1.795     www      7190: 
1.423     albertel 7191: .LC_topic_bar span {
1.918     wenzelju 7192:   left: 0.5em;
                   7193:   position: absolute;
1.423     albertel 7194:   vertical-align: middle;
1.918     wenzelju 7195:   font-size: 1.2em;
1.423     albertel 7196: }
1.795     www      7197: 
1.423     albertel 7198: table.LC_course_group_status {
                   7199:   margin: 20px;
                   7200: }
1.795     www      7201: 
1.423     albertel 7202: table.LC_status_selector td {
                   7203:   vertical-align: top;
                   7204:   text-align: center;
1.424     albertel 7205:   padding: 4px;
                   7206: }
1.795     www      7207: 
1.599     albertel 7208: div.LC_feedback_link {
1.616     albertel 7209:   clear: both;
1.829     kalberla 7210:   background: $sidebg;
1.779     bisitz   7211:   width: 100%;
1.829     kalberla 7212:   padding-bottom: 10px;
                   7213:   border: 1px $tabbg solid;
1.833     kalberla 7214:   height: 22px;
                   7215:   line-height: 22px;
                   7216:   padding-top: 5px;
                   7217: }
                   7218: 
                   7219: div.LC_feedback_link img {
                   7220:   height: 22px;
1.867     kalberla 7221:   vertical-align:middle;
1.829     kalberla 7222: }
                   7223: 
1.911     bisitz   7224: div.LC_feedback_link a {
1.829     kalberla 7225:   text-decoration: none;
1.489     raeburn  7226: }
1.795     www      7227: 
1.867     kalberla 7228: div.LC_comblock {
1.911     bisitz   7229:   display:inline;
1.867     kalberla 7230:   color:$font;
                   7231:   font-size:90%;
                   7232: }
                   7233: 
                   7234: div.LC_feedback_link div.LC_comblock {
                   7235:   padding-left:5px;
                   7236: }
                   7237: 
                   7238: div.LC_feedback_link div.LC_comblock a {
                   7239:   color:$font;
                   7240: }
                   7241: 
1.489     raeburn  7242: span.LC_feedback_link {
1.858     bisitz   7243:   /* background: $feedback_link_bg; */
1.599     albertel 7244:   font-size: larger;
                   7245: }
1.795     www      7246: 
1.599     albertel 7247: span.LC_message_link {
1.858     bisitz   7248:   /* background: $feedback_link_bg; */
1.599     albertel 7249:   font-size: larger;
                   7250:   position: absolute;
                   7251:   right: 1em;
1.489     raeburn  7252: }
1.421     albertel 7253: 
1.515     albertel 7254: table.LC_prior_tries {
1.524     albertel 7255:   border: 1px solid #000000;
                   7256:   border-collapse: separate;
                   7257:   border-spacing: 1px;
1.515     albertel 7258: }
1.523     albertel 7259: 
1.515     albertel 7260: table.LC_prior_tries td {
1.524     albertel 7261:   padding: 2px;
1.515     albertel 7262: }
1.523     albertel 7263: 
                   7264: .LC_answer_correct {
1.795     www      7265:   background: lightgreen;
                   7266:   color: darkgreen;
                   7267:   padding: 6px;
1.523     albertel 7268: }
1.795     www      7269: 
1.523     albertel 7270: .LC_answer_charged_try {
1.797     www      7271:   background: #FFAAAA;
1.795     www      7272:   color: darkred;
                   7273:   padding: 6px;
1.523     albertel 7274: }
1.795     www      7275: 
1.779     bisitz   7276: .LC_answer_not_charged_try,
1.523     albertel 7277: .LC_answer_no_grade,
                   7278: .LC_answer_late {
1.795     www      7279:   background: lightyellow;
1.523     albertel 7280:   color: black;
1.795     www      7281:   padding: 6px;
1.523     albertel 7282: }
1.795     www      7283: 
1.523     albertel 7284: .LC_answer_previous {
1.795     www      7285:   background: lightblue;
                   7286:   color: darkblue;
                   7287:   padding: 6px;
1.523     albertel 7288: }
1.795     www      7289: 
1.779     bisitz   7290: .LC_answer_no_message {
1.777     tempelho 7291:   background: #FFFFFF;
                   7292:   color: black;
1.795     www      7293:   padding: 6px;
1.779     bisitz   7294: }
1.795     www      7295: 
1.1075.2.140  raeburn  7296: .LC_answer_unknown,
                   7297: .LC_answer_warning {
1.779     bisitz   7298:   background: orange;
                   7299:   color: black;
1.795     www      7300:   padding: 6px;
1.777     tempelho 7301: }
1.795     www      7302: 
1.529     albertel 7303: span.LC_prior_numerical,
                   7304: span.LC_prior_string,
                   7305: span.LC_prior_custom,
                   7306: span.LC_prior_reaction,
                   7307: span.LC_prior_math {
1.925     bisitz   7308:   font-family: $mono;
1.523     albertel 7309:   white-space: pre;
                   7310: }
                   7311: 
1.525     albertel 7312: span.LC_prior_string {
1.925     bisitz   7313:   font-family: $mono;
1.525     albertel 7314:   white-space: pre;
                   7315: }
                   7316: 
1.523     albertel 7317: table.LC_prior_option {
                   7318:   width: 100%;
                   7319:   border-collapse: collapse;
                   7320: }
1.795     www      7321: 
1.911     bisitz   7322: table.LC_prior_rank,
1.795     www      7323: table.LC_prior_match {
1.528     albertel 7324:   border-collapse: collapse;
                   7325: }
1.795     www      7326: 
1.528     albertel 7327: table.LC_prior_option tr td,
                   7328: table.LC_prior_rank tr td,
                   7329: table.LC_prior_match tr td {
1.524     albertel 7330:   border: 1px solid #000000;
1.515     albertel 7331: }
                   7332: 
1.855     bisitz   7333: .LC_nobreak {
1.544     albertel 7334:   white-space: nowrap;
1.519     raeburn  7335: }
                   7336: 
1.576     raeburn  7337: span.LC_cusr_emph {
                   7338:   font-style: italic;
                   7339: }
                   7340: 
1.633     raeburn  7341: span.LC_cusr_subheading {
                   7342:   font-weight: normal;
                   7343:   font-size: 85%;
                   7344: }
                   7345: 
1.861     bisitz   7346: div.LC_docs_entry_move {
1.859     bisitz   7347:   border: 1px solid #BBBBBB;
1.545     albertel 7348:   background: #DDDDDD;
1.861     bisitz   7349:   width: 22px;
1.859     bisitz   7350:   padding: 1px;
                   7351:   margin: 0;
1.545     albertel 7352: }
                   7353: 
1.861     bisitz   7354: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7355: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7356:   font-size: x-small;
                   7357: }
1.795     www      7358: 
1.861     bisitz   7359: .LC_docs_entry_parameter {
                   7360:   white-space: nowrap;
                   7361: }
                   7362: 
1.544     albertel 7363: .LC_docs_copy {
1.545     albertel 7364:   color: #000099;
1.544     albertel 7365: }
1.795     www      7366: 
1.544     albertel 7367: .LC_docs_cut {
1.545     albertel 7368:   color: #550044;
1.544     albertel 7369: }
1.795     www      7370: 
1.544     albertel 7371: .LC_docs_rename {
1.545     albertel 7372:   color: #009900;
1.544     albertel 7373: }
1.795     www      7374: 
1.544     albertel 7375: .LC_docs_remove {
1.545     albertel 7376:   color: #990000;
                   7377: }
                   7378: 
1.1075.2.134  raeburn  7379: .LC_domprefs_email,
1.547     albertel 7380: .LC_docs_reinit_warn,
                   7381: .LC_docs_ext_edit {
                   7382:   font-size: x-small;
                   7383: }
                   7384: 
1.545     albertel 7385: table.LC_docs_adddocs td,
                   7386: table.LC_docs_adddocs th {
                   7387:   border: 1px solid #BBBBBB;
                   7388:   padding: 4px;
                   7389:   background: #DDDDDD;
1.543     albertel 7390: }
                   7391: 
1.584     albertel 7392: table.LC_sty_begin {
                   7393:   background: #BBFFBB;
                   7394: }
1.795     www      7395: 
1.584     albertel 7396: table.LC_sty_end {
                   7397:   background: #FFBBBB;
                   7398: }
                   7399: 
1.589     raeburn  7400: table.LC_double_column {
1.803     bisitz   7401:   border-width: 0;
1.589     raeburn  7402:   border-collapse: collapse;
                   7403:   width: 100%;
                   7404:   padding: 2px;
                   7405: }
                   7406: 
                   7407: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7408:   top: 2px;
1.589     raeburn  7409:   left: 2px;
                   7410:   width: 47%;
                   7411:   vertical-align: top;
                   7412: }
                   7413: 
                   7414: table.LC_double_column tr td.LC_right_col {
                   7415:   top: 2px;
1.779     bisitz   7416:   right: 2px;
1.589     raeburn  7417:   width: 47%;
                   7418:   vertical-align: top;
                   7419: }
                   7420: 
1.591     raeburn  7421: div.LC_left_float {
                   7422:   float: left;
                   7423:   padding-right: 5%;
1.597     albertel 7424:   padding-bottom: 4px;
1.591     raeburn  7425: }
                   7426: 
                   7427: div.LC_clear_float_header {
1.597     albertel 7428:   padding-bottom: 2px;
1.591     raeburn  7429: }
                   7430: 
                   7431: div.LC_clear_float_footer {
1.597     albertel 7432:   padding-top: 10px;
1.591     raeburn  7433:   clear: both;
                   7434: }
                   7435: 
1.597     albertel 7436: div.LC_grade_show_user {
1.941     bisitz   7437: /*  border-left: 5px solid $sidebg; */
                   7438:   border-top: 5px solid #000000;
                   7439:   margin: 50px 0 0 0;
1.936     bisitz   7440:   padding: 15px 0 5px 10px;
1.597     albertel 7441: }
1.795     www      7442: 
1.936     bisitz   7443: div.LC_grade_show_user_odd_row {
1.941     bisitz   7444: /*  border-left: 5px solid #000000; */
                   7445: }
                   7446: 
                   7447: div.LC_grade_show_user div.LC_Box {
                   7448:   margin-right: 50px;
1.597     albertel 7449: }
                   7450: 
                   7451: div.LC_grade_submissions,
                   7452: div.LC_grade_message_center,
1.936     bisitz   7453: div.LC_grade_info_links {
1.597     albertel 7454:   margin: 5px;
                   7455:   width: 99%;
                   7456:   background: #FFFFFF;
                   7457: }
1.795     www      7458: 
1.597     albertel 7459: div.LC_grade_submissions_header,
1.936     bisitz   7460: div.LC_grade_message_center_header {
1.705     tempelho 7461:   font-weight: bold;
                   7462:   font-size: large;
1.597     albertel 7463: }
1.795     www      7464: 
1.597     albertel 7465: div.LC_grade_submissions_body,
1.936     bisitz   7466: div.LC_grade_message_center_body {
1.597     albertel 7467:   border: 1px solid black;
                   7468:   width: 99%;
                   7469:   background: #FFFFFF;
                   7470: }
1.795     www      7471: 
1.613     albertel 7472: table.LC_scantron_action {
                   7473:   width: 100%;
                   7474: }
1.795     www      7475: 
1.613     albertel 7476: table.LC_scantron_action tr th {
1.698     harmsja  7477:   font-weight:bold;
                   7478:   font-style:normal;
1.613     albertel 7479: }
1.795     www      7480: 
1.779     bisitz   7481: .LC_edit_problem_header,
1.614     albertel 7482: div.LC_edit_problem_footer {
1.705     tempelho 7483:   font-weight: normal;
                   7484:   font-size:  medium;
1.602     albertel 7485:   margin: 2px;
1.1060    bisitz   7486:   background-color: $sidebg;
1.600     albertel 7487: }
1.795     www      7488: 
1.600     albertel 7489: div.LC_edit_problem_header,
1.602     albertel 7490: div.LC_edit_problem_header div,
1.614     albertel 7491: div.LC_edit_problem_footer,
                   7492: div.LC_edit_problem_footer div,
1.602     albertel 7493: div.LC_edit_problem_editxml_header,
                   7494: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7495:   z-index: 100;
1.600     albertel 7496: }
1.795     www      7497: 
1.600     albertel 7498: div.LC_edit_problem_header_title {
1.705     tempelho 7499:   font-weight: bold;
                   7500:   font-size: larger;
1.602     albertel 7501:   background: $tabbg;
                   7502:   padding: 3px;
1.1060    bisitz   7503:   margin: 0 0 5px 0;
1.602     albertel 7504: }
1.795     www      7505: 
1.602     albertel 7506: table.LC_edit_problem_header_title {
                   7507:   width: 100%;
1.600     albertel 7508:   background: $tabbg;
1.602     albertel 7509: }
                   7510: 
1.1075.2.112  raeburn  7511: div.LC_edit_actionbar {
                   7512:     background-color: $sidebg;
                   7513:     margin: 0;
                   7514:     padding: 0;
                   7515:     line-height: 200%;
1.602     albertel 7516: }
1.795     www      7517: 
1.1075.2.112  raeburn  7518: div.LC_edit_actionbar div{
                   7519:     padding: 0;
                   7520:     margin: 0;
                   7521:     display: inline-block;
1.600     albertel 7522: }
1.795     www      7523: 
1.1075.2.34  raeburn  7524: .LC_edit_opt {
                   7525:   padding-left: 1em;
                   7526:   white-space: nowrap;
                   7527: }
                   7528: 
1.1075.2.57  raeburn  7529: .LC_edit_problem_latexhelper{
                   7530:     text-align: right;
                   7531: }
                   7532: 
                   7533: #LC_edit_problem_colorful div{
                   7534:     margin-left: 40px;
                   7535: }
                   7536: 
1.1075.2.112  raeburn  7537: #LC_edit_problem_codemirror div{
                   7538:     margin-left: 0px;
                   7539: }
                   7540: 
1.911     bisitz   7541: img.stift {
1.803     bisitz   7542:   border-width: 0;
                   7543:   vertical-align: middle;
1.677     riegler  7544: }
1.680     riegler  7545: 
1.923     bisitz   7546: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7547:   vertical-align: top;
1.777     tempelho 7548: }
1.795     www      7549: 
1.716     raeburn  7550: div.LC_createcourse {
1.911     bisitz   7551:   margin: 10px 10px 10px 10px;
1.716     raeburn  7552: }
                   7553: 
1.917     raeburn  7554: .LC_dccid {
1.1075.2.38  raeburn  7555:   float: right;
1.917     raeburn  7556:   margin: 0.2em 0 0 0;
                   7557:   padding: 0;
                   7558:   font-size: 90%;
                   7559:   display:none;
                   7560: }
                   7561: 
1.897     wenzelju 7562: ol.LC_primary_menu a:hover,
1.721     harmsja  7563: ol#LC_MenuBreadcrumbs a:hover,
                   7564: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7565: ul#LC_secondary_menu a:hover,
1.721     harmsja  7566: .LC_FormSectionClearButton input:hover
1.795     www      7567: ul.LC_TabContent   li:hover a {
1.952     onken    7568:   color:$button_hover;
1.911     bisitz   7569:   text-decoration:none;
1.693     droeschl 7570: }
                   7571: 
1.779     bisitz   7572: h1 {
1.911     bisitz   7573:   padding: 0;
                   7574:   line-height:130%;
1.693     droeschl 7575: }
1.698     harmsja  7576: 
1.911     bisitz   7577: h2,
                   7578: h3,
                   7579: h4,
                   7580: h5,
                   7581: h6 {
                   7582:   margin: 5px 0 5px 0;
                   7583:   padding: 0;
                   7584:   line-height:130%;
1.693     droeschl 7585: }
1.795     www      7586: 
                   7587: .LC_hcell {
1.911     bisitz   7588:   padding:3px 15px 3px 15px;
                   7589:   margin: 0;
                   7590:   background-color:$tabbg;
                   7591:   color:$fontmenu;
                   7592:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7593: }
1.795     www      7594: 
1.840     bisitz   7595: .LC_Box > .LC_hcell {
1.911     bisitz   7596:   margin: 0 -10px 10px -10px;
1.835     bisitz   7597: }
                   7598: 
1.721     harmsja  7599: .LC_noBorder {
1.911     bisitz   7600:   border: 0;
1.698     harmsja  7601: }
1.693     droeschl 7602: 
1.721     harmsja  7603: .LC_FormSectionClearButton input {
1.911     bisitz   7604:   background-color:transparent;
                   7605:   border: none;
                   7606:   cursor:pointer;
                   7607:   text-decoration:underline;
1.693     droeschl 7608: }
1.763     bisitz   7609: 
                   7610: .LC_help_open_topic {
1.911     bisitz   7611:   color: #FFFFFF;
                   7612:   background-color: #EEEEFF;
                   7613:   margin: 1px;
                   7614:   padding: 4px;
                   7615:   border: 1px solid #000033;
                   7616:   white-space: nowrap;
                   7617:   /* vertical-align: middle; */
1.759     neumanie 7618: }
1.693     droeschl 7619: 
1.911     bisitz   7620: dl,
                   7621: ul,
                   7622: div,
                   7623: fieldset {
                   7624:   margin: 10px 10px 10px 0;
                   7625:   /* overflow: hidden; */
1.693     droeschl 7626: }
1.795     www      7627: 
1.1075.2.90  raeburn  7628: article.geogebraweb div {
                   7629:     margin: 0;
                   7630: }
                   7631: 
1.838     bisitz   7632: fieldset > legend {
1.911     bisitz   7633:   font-weight: bold;
                   7634:   padding: 0 5px 0 5px;
1.838     bisitz   7635: }
                   7636: 
1.813     bisitz   7637: #LC_nav_bar {
1.911     bisitz   7638:   float: left;
1.995     raeburn  7639:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7640:   margin: 0 0 2px 0;
1.807     droeschl 7641: }
                   7642: 
1.916     droeschl 7643: #LC_realm {
                   7644:   margin: 0.2em 0 0 0;
                   7645:   padding: 0;
                   7646:   font-weight: bold;
                   7647:   text-align: center;
1.995     raeburn  7648:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7649: }
                   7650: 
1.911     bisitz   7651: #LC_nav_bar em {
                   7652:   font-weight: bold;
                   7653:   font-style: normal;
1.807     droeschl 7654: }
                   7655: 
1.897     wenzelju 7656: ol.LC_primary_menu {
1.934     droeschl 7657:   margin: 0;
1.1075.2.2  raeburn  7658:   padding: 0;
1.807     droeschl 7659: }
                   7660: 
1.852     droeschl 7661: ol#LC_PathBreadcrumbs {
1.911     bisitz   7662:   margin: 0;
1.693     droeschl 7663: }
                   7664: 
1.897     wenzelju 7665: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7666:   color: RGB(80, 80, 80);
                   7667:   vertical-align: middle;
                   7668:   text-align: left;
                   7669:   list-style: none;
1.1075.2.112  raeburn  7670:   position: relative;
1.1075.2.2  raeburn  7671:   float: left;
1.1075.2.112  raeburn  7672:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7673:   line-height: 1.5em;
1.1075.2.2  raeburn  7674: }
                   7675: 
1.1075.2.113  raeburn  7676: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7677: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7678:   display: block;
                   7679:   margin: 0;
                   7680:   padding: 0 5px 0 10px;
                   7681:   text-decoration: none;
                   7682: }
                   7683: 
1.1075.2.112  raeburn  7684: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7685:   display: inline-block;
                   7686:   width: 95%;
                   7687:   text-align: left;
                   7688: }
                   7689: 
                   7690: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7691:   display: inline-block;
                   7692:   width: 5%;
                   7693:   float: right;
                   7694:   text-align: right;
                   7695:   font-size: 70%;
                   7696: }
                   7697: 
                   7698: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7699:   display: none;
1.1075.2.112  raeburn  7700:   width: 15em;
1.1075.2.2  raeburn  7701:   background-color: $data_table_light;
1.1075.2.112  raeburn  7702:   position: absolute;
                   7703:   top: 100%;
                   7704: }
                   7705: 
                   7706: ol.LC_primary_menu ul ul {
                   7707:   left: 100%;
                   7708:   top: 0;
1.1075.2.2  raeburn  7709: }
                   7710: 
1.1075.2.112  raeburn  7711: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7712:   display: block;
                   7713:   position: absolute;
                   7714:   margin: 0;
                   7715:   padding: 0;
1.1075.2.5  raeburn  7716:   z-index: 2;
1.1075.2.2  raeburn  7717: }
                   7718: 
                   7719: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7720: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7721:   font-size: 90%;
1.911     bisitz   7722:   vertical-align: top;
1.1075.2.2  raeburn  7723:   float: none;
1.1075.2.5  raeburn  7724:   border-left: 1px solid black;
                   7725:   border-right: 1px solid black;
1.1075.2.112  raeburn  7726: /* A dark bottom border to visualize different menu options;
                   7727: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7728:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7729: }
                   7730: 
1.1075.2.112  raeburn  7731: ol.LC_primary_menu li li p:hover {
                   7732:   color:$button_hover;
                   7733:   text-decoration:none;
                   7734:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7735: }
                   7736: 
                   7737: ol.LC_primary_menu li li a:hover {
                   7738:    color:$button_hover;
                   7739:    background-color:$data_table_dark;
1.693     droeschl 7740: }
                   7741: 
1.1075.2.112  raeburn  7742: /* Font-size equal to the size of the predecessors*/
                   7743: ol.LC_primary_menu li:hover li li {
                   7744:   font-size: 100%;
                   7745: }
                   7746: 
1.897     wenzelju 7747: ol.LC_primary_menu li img {
1.911     bisitz   7748:   vertical-align: bottom;
1.934     droeschl 7749:   height: 1.1em;
1.1075.2.3  raeburn  7750:   margin: 0.2em 0 0 0;
1.693     droeschl 7751: }
                   7752: 
1.897     wenzelju 7753: ol.LC_primary_menu a {
1.911     bisitz   7754:   color: RGB(80, 80, 80);
                   7755:   text-decoration: none;
1.693     droeschl 7756: }
1.795     www      7757: 
1.949     droeschl 7758: ol.LC_primary_menu a.LC_new_message {
                   7759:   font-weight:bold;
                   7760:   color: darkred;
                   7761: }
                   7762: 
1.975     raeburn  7763: ol.LC_docs_parameters {
                   7764:   margin-left: 0;
                   7765:   padding: 0;
                   7766:   list-style: none;
                   7767: }
                   7768: 
                   7769: ol.LC_docs_parameters li {
                   7770:   margin: 0;
                   7771:   padding-right: 20px;
                   7772:   display: inline;
                   7773: }
                   7774: 
1.976     raeburn  7775: ol.LC_docs_parameters li:before {
                   7776:   content: "\\002022 \\0020";
                   7777: }
                   7778: 
                   7779: li.LC_docs_parameters_title {
                   7780:   font-weight: bold;
                   7781: }
                   7782: 
                   7783: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7784:   content: "";
                   7785: }
                   7786: 
1.897     wenzelju 7787: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7788:   clear: right;
1.911     bisitz   7789:   color: $fontmenu;
                   7790:   background: $tabbg;
                   7791:   list-style: none;
                   7792:   padding: 0;
                   7793:   margin: 0;
                   7794:   width: 100%;
1.995     raeburn  7795:   text-align: left;
1.1075.2.4  raeburn  7796:   float: left;
1.808     droeschl 7797: }
                   7798: 
1.897     wenzelju 7799: ul#LC_secondary_menu li {
1.911     bisitz   7800:   font-weight: bold;
                   7801:   line-height: 1.8em;
                   7802:   border-right: 1px solid black;
1.1075.2.4  raeburn  7803:   float: left;
                   7804: }
                   7805: 
                   7806: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7807:   background-color: $data_table_light;
                   7808: }
                   7809: 
                   7810: ul#LC_secondary_menu li a {
                   7811:   padding: 0 0.8em;
                   7812: }
                   7813: 
                   7814: ul#LC_secondary_menu li ul {
                   7815:   display: none;
                   7816: }
                   7817: 
                   7818: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7819:   display: block;
                   7820:   position: absolute;
                   7821:   margin: 0;
                   7822:   padding: 0;
                   7823:   list-style:none;
                   7824:   float: none;
                   7825:   background-color: $data_table_light;
1.1075.2.5  raeburn  7826:   z-index: 2;
1.1075.2.10  raeburn  7827:   margin-left: -1px;
1.1075.2.4  raeburn  7828: }
                   7829: 
                   7830: ul#LC_secondary_menu li ul li {
                   7831:   font-size: 90%;
                   7832:   vertical-align: top;
                   7833:   border-left: 1px solid black;
                   7834:   border-right: 1px solid black;
1.1075.2.33  raeburn  7835:   background-color: $data_table_light;
1.1075.2.4  raeburn  7836:   list-style:none;
                   7837:   float: none;
                   7838: }
                   7839: 
                   7840: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7841:   background-color: $data_table_dark;
1.807     droeschl 7842: }
                   7843: 
1.847     tempelho 7844: ul.LC_TabContent {
1.911     bisitz   7845:   display:block;
                   7846:   background: $sidebg;
                   7847:   border-bottom: solid 1px $lg_border_color;
                   7848:   list-style:none;
1.1020    raeburn  7849:   margin: -1px -10px 0 -10px;
1.911     bisitz   7850:   padding: 0;
1.693     droeschl 7851: }
                   7852: 
1.795     www      7853: ul.LC_TabContent li,
                   7854: ul.LC_TabContentBigger li {
1.911     bisitz   7855:   float:left;
1.741     harmsja  7856: }
1.795     www      7857: 
1.897     wenzelju 7858: ul#LC_secondary_menu li a {
1.911     bisitz   7859:   color: $fontmenu;
                   7860:   text-decoration: none;
1.693     droeschl 7861: }
1.795     www      7862: 
1.721     harmsja  7863: ul.LC_TabContent {
1.952     onken    7864:   min-height:20px;
1.721     harmsja  7865: }
1.795     www      7866: 
                   7867: ul.LC_TabContent li {
1.911     bisitz   7868:   vertical-align:middle;
1.959     onken    7869:   padding: 0 16px 0 10px;
1.911     bisitz   7870:   background-color:$tabbg;
                   7871:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7872:   border-left: solid 1px $font;
1.721     harmsja  7873: }
1.795     www      7874: 
1.847     tempelho 7875: ul.LC_TabContent .right {
1.911     bisitz   7876:   float:right;
1.847     tempelho 7877: }
                   7878: 
1.911     bisitz   7879: ul.LC_TabContent li a,
                   7880: ul.LC_TabContent li {
                   7881:   color:rgb(47,47,47);
                   7882:   text-decoration:none;
                   7883:   font-size:95%;
                   7884:   font-weight:bold;
1.952     onken    7885:   min-height:20px;
                   7886: }
                   7887: 
1.959     onken    7888: ul.LC_TabContent li a:hover,
                   7889: ul.LC_TabContent li a:focus {
1.952     onken    7890:   color: $button_hover;
1.959     onken    7891:   background:none;
                   7892:   outline:none;
1.952     onken    7893: }
                   7894: 
                   7895: ul.LC_TabContent li:hover {
                   7896:   color: $button_hover;
                   7897:   cursor:pointer;
1.721     harmsja  7898: }
1.795     www      7899: 
1.911     bisitz   7900: ul.LC_TabContent li.active {
1.952     onken    7901:   color: $font;
1.911     bisitz   7902:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7903:   border-bottom:solid 1px #FFFFFF;
                   7904:   cursor: default;
1.744     ehlerst  7905: }
1.795     www      7906: 
1.959     onken    7907: ul.LC_TabContent li.active a {
                   7908:   color:$font;
                   7909:   background:#FFFFFF;
                   7910:   outline: none;
                   7911: }
1.1047    raeburn  7912: 
                   7913: ul.LC_TabContent li.goback {
                   7914:   float: left;
                   7915:   border-left: none;
                   7916: }
                   7917: 
1.870     tempelho 7918: #maincoursedoc {
1.911     bisitz   7919:   clear:both;
1.870     tempelho 7920: }
                   7921: 
                   7922: ul.LC_TabContentBigger {
1.911     bisitz   7923:   display:block;
                   7924:   list-style:none;
                   7925:   padding: 0;
1.870     tempelho 7926: }
                   7927: 
1.795     www      7928: ul.LC_TabContentBigger li {
1.911     bisitz   7929:   vertical-align:bottom;
                   7930:   height: 30px;
                   7931:   font-size:110%;
                   7932:   font-weight:bold;
                   7933:   color: #737373;
1.841     tempelho 7934: }
                   7935: 
1.957     onken    7936: ul.LC_TabContentBigger li.active {
                   7937:   position: relative;
                   7938:   top: 1px;
                   7939: }
                   7940: 
1.870     tempelho 7941: ul.LC_TabContentBigger li a {
1.911     bisitz   7942:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7943:   height: 30px;
                   7944:   line-height: 30px;
                   7945:   text-align: center;
                   7946:   display: block;
                   7947:   text-decoration: none;
1.958     onken    7948:   outline: none;  
1.741     harmsja  7949: }
1.795     www      7950: 
1.870     tempelho 7951: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7952:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7953:   color:$font;
1.744     ehlerst  7954: }
1.795     www      7955: 
1.870     tempelho 7956: ul.LC_TabContentBigger li b {
1.911     bisitz   7957:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7958:   display: block;
                   7959:   float: left;
                   7960:   padding: 0 30px;
1.957     onken    7961:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7962: }
                   7963: 
1.956     onken    7964: ul.LC_TabContentBigger li:hover b {
                   7965:   color:$button_hover;
                   7966: }
                   7967: 
1.870     tempelho 7968: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7969:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7970:   color:$font;
1.957     onken    7971:   border: 0;
1.741     harmsja  7972: }
1.693     droeschl 7973: 
1.870     tempelho 7974: 
1.862     bisitz   7975: ul.LC_CourseBreadcrumbs {
                   7976:   background: $sidebg;
1.1020    raeburn  7977:   height: 2em;
1.862     bisitz   7978:   padding-left: 10px;
1.1020    raeburn  7979:   margin: 0;
1.862     bisitz   7980:   list-style-position: inside;
                   7981: }
                   7982: 
1.911     bisitz   7983: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7984: ol#LC_PathBreadcrumbs {
1.911     bisitz   7985:   padding-left: 10px;
                   7986:   margin: 0;
1.933     droeschl 7987:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7988: }
                   7989: 
1.911     bisitz   7990: ol#LC_MenuBreadcrumbs li,
                   7991: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7992: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7993:   display: inline;
1.933     droeschl 7994:   white-space: normal;  
1.693     droeschl 7995: }
                   7996: 
1.823     bisitz   7997: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7998: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7999:   text-decoration: none;
                   8000:   font-size:90%;
1.693     droeschl 8001: }
1.795     www      8002: 
1.969     droeschl 8003: ol#LC_MenuBreadcrumbs h1 {
                   8004:   display: inline;
                   8005:   font-size: 90%;
                   8006:   line-height: 2.5em;
                   8007:   margin: 0;
                   8008:   padding: 0;
                   8009: }
                   8010: 
1.795     www      8011: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8012:   text-decoration:none;
                   8013:   font-size:100%;
                   8014:   font-weight:bold;
1.693     droeschl 8015: }
1.795     www      8016: 
1.840     bisitz   8017: .LC_Box {
1.911     bisitz   8018:   border: solid 1px $lg_border_color;
                   8019:   padding: 0 10px 10px 10px;
1.746     neumanie 8020: }
1.795     www      8021: 
1.1020    raeburn  8022: .LC_DocsBox {
                   8023:   border: solid 1px $lg_border_color;
                   8024:   padding: 0 0 10px 10px;
                   8025: }
                   8026: 
1.795     www      8027: .LC_AboutMe_Image {
1.911     bisitz   8028:   float:left;
                   8029:   margin-right:10px;
1.747     neumanie 8030: }
1.795     www      8031: 
                   8032: .LC_Clear_AboutMe_Image {
1.911     bisitz   8033:   clear:left;
1.747     neumanie 8034: }
1.795     www      8035: 
1.721     harmsja  8036: dl.LC_ListStyleClean dt {
1.911     bisitz   8037:   padding-right: 5px;
                   8038:   display: table-header-group;
1.693     droeschl 8039: }
                   8040: 
1.721     harmsja  8041: dl.LC_ListStyleClean dd {
1.911     bisitz   8042:   display: table-row;
1.693     droeschl 8043: }
                   8044: 
1.721     harmsja  8045: .LC_ListStyleClean,
                   8046: .LC_ListStyleSimple,
                   8047: .LC_ListStyleNormal,
1.795     www      8048: .LC_ListStyleSpecial {
1.911     bisitz   8049:   /* display:block; */
                   8050:   list-style-position: inside;
                   8051:   list-style-type: none;
                   8052:   overflow: hidden;
                   8053:   padding: 0;
1.693     droeschl 8054: }
                   8055: 
1.721     harmsja  8056: .LC_ListStyleSimple li,
                   8057: .LC_ListStyleSimple dd,
                   8058: .LC_ListStyleNormal li,
                   8059: .LC_ListStyleNormal dd,
                   8060: .LC_ListStyleSpecial li,
1.795     www      8061: .LC_ListStyleSpecial dd {
1.911     bisitz   8062:   margin: 0;
                   8063:   padding: 5px 5px 5px 10px;
                   8064:   clear: both;
1.693     droeschl 8065: }
                   8066: 
1.721     harmsja  8067: .LC_ListStyleClean li,
                   8068: .LC_ListStyleClean dd {
1.911     bisitz   8069:   padding-top: 0;
                   8070:   padding-bottom: 0;
1.693     droeschl 8071: }
                   8072: 
1.721     harmsja  8073: .LC_ListStyleSimple dd,
1.795     www      8074: .LC_ListStyleSimple li {
1.911     bisitz   8075:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8076: }
                   8077: 
1.721     harmsja  8078: .LC_ListStyleSpecial li,
                   8079: .LC_ListStyleSpecial dd {
1.911     bisitz   8080:   list-style-type: none;
                   8081:   background-color: RGB(220, 220, 220);
                   8082:   margin-bottom: 4px;
1.693     droeschl 8083: }
                   8084: 
1.721     harmsja  8085: table.LC_SimpleTable {
1.911     bisitz   8086:   margin:5px;
                   8087:   border:solid 1px $lg_border_color;
1.795     www      8088: }
1.693     droeschl 8089: 
1.721     harmsja  8090: table.LC_SimpleTable tr {
1.911     bisitz   8091:   padding: 0;
                   8092:   border:solid 1px $lg_border_color;
1.693     droeschl 8093: }
1.795     www      8094: 
                   8095: table.LC_SimpleTable thead {
1.911     bisitz   8096:   background:rgb(220,220,220);
1.693     droeschl 8097: }
                   8098: 
1.721     harmsja  8099: div.LC_columnSection {
1.911     bisitz   8100:   display: block;
                   8101:   clear: both;
                   8102:   overflow: hidden;
                   8103:   margin: 0;
1.693     droeschl 8104: }
                   8105: 
1.721     harmsja  8106: div.LC_columnSection>* {
1.911     bisitz   8107:   float: left;
                   8108:   margin: 10px 20px 10px 0;
                   8109:   overflow:hidden;
1.693     droeschl 8110: }
1.721     harmsja  8111: 
1.795     www      8112: table em {
1.911     bisitz   8113:   font-weight: bold;
                   8114:   font-style: normal;
1.748     schulted 8115: }
1.795     www      8116: 
1.779     bisitz   8117: table.LC_tableBrowseRes,
1.795     www      8118: table.LC_tableOfContent {
1.911     bisitz   8119:   border:none;
                   8120:   border-spacing: 1px;
                   8121:   padding: 3px;
                   8122:   background-color: #FFFFFF;
                   8123:   font-size: 90%;
1.753     droeschl 8124: }
1.789     droeschl 8125: 
1.911     bisitz   8126: table.LC_tableOfContent {
                   8127:   border-collapse: collapse;
1.789     droeschl 8128: }
                   8129: 
1.771     droeschl 8130: table.LC_tableBrowseRes a,
1.768     schulted 8131: table.LC_tableOfContent a {
1.911     bisitz   8132:   background-color: transparent;
                   8133:   text-decoration: none;
1.753     droeschl 8134: }
                   8135: 
1.795     www      8136: table.LC_tableOfContent img {
1.911     bisitz   8137:   border: none;
                   8138:   height: 1.3em;
                   8139:   vertical-align: text-bottom;
                   8140:   margin-right: 0.3em;
1.753     droeschl 8141: }
1.757     schulted 8142: 
1.795     www      8143: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8144:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8145: }
                   8146: 
1.795     www      8147: a#LC_content_toolbar_everything {
1.911     bisitz   8148:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8149: }
                   8150: 
1.795     www      8151: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8152:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8153: }
                   8154: 
1.795     www      8155: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8156:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8157: }
                   8158: 
1.795     www      8159: a#LC_content_toolbar_changefolder {
1.911     bisitz   8160:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8161: }
                   8162: 
1.795     www      8163: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8164:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8165: }
                   8166: 
1.1043    raeburn  8167: a#LC_content_toolbar_edittoplevel {
                   8168:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8169: }
                   8170: 
1.1075.2.161.  .12(raeb 8171:-23): a#LC_content_toolbar_printout {
                   8172:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8173:-23): }
                   8174:-23): 
1.795     www      8175: ul#LC_toolbar li a:hover {
1.911     bisitz   8176:   background-position: bottom center;
1.757     schulted 8177: }
                   8178: 
1.795     www      8179: ul#LC_toolbar {
1.911     bisitz   8180:   padding: 0;
                   8181:   margin: 2px;
                   8182:   list-style:none;
                   8183:   position:relative;
                   8184:   background-color:white;
1.1075.2.9  raeburn  8185:   overflow: auto;
1.757     schulted 8186: }
                   8187: 
1.795     www      8188: ul#LC_toolbar li {
1.911     bisitz   8189:   border:1px solid white;
                   8190:   padding: 0;
                   8191:   margin: 0;
                   8192:   float: left;
                   8193:   display:inline;
                   8194:   vertical-align:middle;
1.1075.2.9  raeburn  8195:   white-space: nowrap;
1.911     bisitz   8196: }
1.757     schulted 8197: 
1.783     amueller 8198: 
1.795     www      8199: a.LC_toolbarItem {
1.911     bisitz   8200:   display:block;
                   8201:   padding: 0;
                   8202:   margin: 0;
                   8203:   height: 32px;
                   8204:   width: 32px;
                   8205:   color:white;
                   8206:   border: none;
                   8207:   background-repeat:no-repeat;
                   8208:   background-color:transparent;
1.757     schulted 8209: }
                   8210: 
1.915     droeschl 8211: ul.LC_funclist {
                   8212:     margin: 0;
                   8213:     padding: 0.5em 1em 0.5em 0;
                   8214: }
                   8215: 
1.933     droeschl 8216: ul.LC_funclist > li:first-child {
                   8217:     font-weight:bold; 
                   8218:     margin-left:0.8em;
                   8219: }
                   8220: 
1.915     droeschl 8221: ul.LC_funclist + ul.LC_funclist {
                   8222:     /* 
                   8223:        left border as a seperator if we have more than
                   8224:        one list 
                   8225:     */
                   8226:     border-left: 1px solid $sidebg;
                   8227:     /* 
                   8228:        this hides the left border behind the border of the 
                   8229:        outer box if element is wrapped to the next 'line' 
                   8230:     */
                   8231:     margin-left: -1px;
                   8232: }
                   8233: 
1.843     bisitz   8234: ul.LC_funclist li {
1.915     droeschl 8235:   display: inline;
1.782     bisitz   8236:   white-space: nowrap;
1.915     droeschl 8237:   margin: 0 0 0 25px;
                   8238:   line-height: 150%;
1.782     bisitz   8239: }
                   8240: 
1.974     wenzelju 8241: .LC_hidden {
                   8242:   display: none;
                   8243: }
                   8244: 
1.1030    www      8245: .LCmodal-overlay {
                   8246: 		position:fixed;
                   8247: 		top:0;
                   8248: 		right:0;
                   8249: 		bottom:0;
                   8250: 		left:0;
                   8251: 		height:100%;
                   8252: 		width:100%;
                   8253: 		margin:0;
                   8254: 		padding:0;
                   8255: 		background:#999;
                   8256: 		opacity:.75;
                   8257: 		filter: alpha(opacity=75);
                   8258: 		-moz-opacity: 0.75;
                   8259: 		z-index:101;
                   8260: }
                   8261: 
                   8262: * html .LCmodal-overlay {   
                   8263: 		position: absolute;
                   8264: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8265: }
                   8266: 
                   8267: .LCmodal-window {
                   8268: 		position:fixed;
                   8269: 		top:50%;
                   8270: 		left:50%;
                   8271: 		margin:0;
                   8272: 		padding:0;
                   8273: 		z-index:102;
                   8274: 	}
                   8275: 
                   8276: * html .LCmodal-window {
                   8277: 		position:absolute;
                   8278: }
                   8279: 
                   8280: .LCclose-window {
                   8281: 		position:absolute;
                   8282: 		width:32px;
                   8283: 		height:32px;
                   8284: 		right:8px;
                   8285: 		top:8px;
                   8286: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8287: 		text-indent:-99999px;
                   8288: 		overflow:hidden;
                   8289: 		cursor:pointer;
                   8290: }
                   8291: 
1.1075.2.158  raeburn  8292: .LCisDisabled {
                   8293:   cursor: not-allowed;
                   8294:   opacity: 0.5;
                   8295: }
                   8296: 
                   8297: a[aria-disabled="true"] {
                   8298:   color: currentColor;
                   8299:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8300:   pointer-events: none;
                   8301:   text-decoration: none;
                   8302: }
                   8303: 
1.1075.2.141  raeburn  8304: pre.LC_wordwrap {
                   8305:   white-space: pre-wrap;
                   8306:   white-space: -moz-pre-wrap;
                   8307:   white-space: -pre-wrap;
                   8308:   white-space: -o-pre-wrap;
                   8309:   word-wrap: break-word;
                   8310: }
                   8311: 
1.1075.2.17  raeburn  8312: /*
                   8313:   styles used by TTH when "Default set of options to pass to tth/m
                   8314:   when converting TeX" in course settings has been set
                   8315: 
                   8316:   option passed: -t
                   8317: 
                   8318: */
                   8319: 
                   8320: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8321: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8322: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8323: td div.norm {line-height:normal;}
                   8324: 
                   8325: /*
                   8326:   option passed -y3
                   8327: */
                   8328: 
                   8329: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8330: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8331: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8332: 
1.1075.2.121  raeburn  8333: #LC_minitab_header {
                   8334:   float:left;
                   8335:   width:100%;
                   8336:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8337:   font-size:93%;
                   8338:   line-height:normal;
                   8339:   margin: 0.5em 0 0.5em 0;
                   8340: }
                   8341: #LC_minitab_header ul {
                   8342:   margin:0;
                   8343:   padding:10px 10px 0;
                   8344:   list-style:none;
                   8345: }
                   8346: #LC_minitab_header li {
                   8347:   float:left;
                   8348:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8349:   margin:0;
                   8350:   padding:0 0 0 9px;
                   8351: }
                   8352: #LC_minitab_header a {
                   8353:   display:block;
                   8354:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8355:   padding:5px 15px 4px 6px;
                   8356: }
                   8357: #LC_minitab_header #LC_current_minitab {
                   8358:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8359: }
                   8360: #LC_minitab_header #LC_current_minitab a {
                   8361:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8362:   padding-bottom:5px;
                   8363: }
                   8364: 
                   8365: 
1.343     albertel 8366: END
                   8367: }
                   8368: 
1.306     albertel 8369: =pod
                   8370: 
                   8371: =item * &headtag()
                   8372: 
                   8373: Returns a uniform footer for LON-CAPA web pages.
                   8374: 
1.307     albertel 8375: Inputs: $title - optional title for the head
                   8376:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8377:         $args - optional arguments
1.319     albertel 8378:             force_register - if is true call registerurl so the remote is 
                   8379:                              informed
1.415     albertel 8380:             redirect       -> array ref of
                   8381:                                    1- seconds before redirect occurs
                   8382:                                    2- url to redirect to
                   8383:                                    3- whether the side effect should occur
1.315     albertel 8384:                            (side effect of setting 
                   8385:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8386:22):                                redirected to)
                   8387:22):                                    4- whether the redirect target should be
                   8388:22):                                       the opener of the current (pop-up)
                   8389:22):                                       window (side effect of setting
                   8390:22):                                       $env{'internal.head.to_opener'} to
                   8391:22):                                       1, if true.
          .10(raeb 8392:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8393:             domain         -> force to color decorate a page for a specific
                   8394:                                domain
                   8395:             function       -> force usage of a specific rolish color scheme
                   8396:             bgcolor        -> override the default page bgcolor
1.460     albertel 8397:             no_auto_mt_title
                   8398:                            -> prevent &mt()ing the title arg
1.464     albertel 8399: 
1.306     albertel 8400: =cut
                   8401: 
                   8402: sub headtag {
1.313     albertel 8403:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8404:     
1.363     albertel 8405:     my $function = $args->{'function'} || &get_users_function();
                   8406:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8407:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8408:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8409:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8410: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8411: 		   #time(),
1.418     albertel 8412: 		   $env{'environment.color.timestamp'},
1.363     albertel 8413: 		   $function,$domain,$bgcolor);
                   8414: 
1.369     www      8415:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8416: 
1.308     albertel 8417:     my $result =
                   8418: 	'<head>'.
1.1075.2.56  raeburn  8419: 	&font_settings($args);
1.319     albertel 8420: 
1.1075.2.72  raeburn  8421:     my $inhibitprint;
                   8422:     if ($args->{'print_suppress'}) {
                   8423:         $inhibitprint = &print_suppression();
                   8424:     }
1.1064    raeburn  8425: 
1.461     albertel 8426:     if (!$args->{'frameset'}) {
                   8427: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8428:     }
1.1075.2.12  raeburn  8429:     if ($args->{'force_register'}) {
                   8430:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8431:     }
1.436     albertel 8432:     if (!$args->{'no_nav_bar'} 
                   8433: 	&& !$args->{'only_body'}
                   8434: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8435: 	$result .= &help_menu_js($httphost);
1.1032    www      8436:         $result.=&modal_window();
1.1038    www      8437:         $result.=&togglebox_script();
1.1034    www      8438:         $result.=&wishlist_window();
1.1041    www      8439:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8440:     } else {
                   8441:         if ($args->{'add_modal'}) {
                   8442:            $result.=&modal_window();
                   8443:         }
                   8444:         if ($args->{'add_wishlist'}) {
                   8445:            $result.=&wishlist_window();
                   8446:         }
1.1038    www      8447:         if ($args->{'add_togglebox'}) {
                   8448:            $result.=&togglebox_script();
                   8449:         }
1.1041    www      8450:         if ($args->{'add_progressbar'}) {
                   8451:            $result.=&LCprogressbarUpdate_script();
                   8452:         }
1.436     albertel 8453:     }
1.314     albertel 8454:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8455:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8456:-22):         if (!$skip_enc_check) {
                   8457:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8458:-22):         }
1.414     albertel 8459: 	if (!$inhibit_continue) {
                   8460: 	    $env{'internal.head.redirect'} = $url;
                   8461: 	}
1.1075.2.161.  .9(raebu 8462:22):         $result.=<<"ADDMETA";
1.313     albertel 8463: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8464:22): ADDMETA
                   8465:22):         if ($to_opener) {
                   8466:22):             $env{'internal.head.to_opener'} = 1;
                   8467:22):             my $dest = &js_escape($url);
                   8468:22):             my $timeout = int($time * 1000);
                   8469:22):             $result .=<<"ENDJS";
                   8470:22): <script type="text/javascript">
                   8471:22): // <![CDATA[
                   8472:22): function LC_To_Opener() {
                   8473:22):     var dest = '$dest';
                   8474:22):     if (dest != '') {
                   8475:22):         if (window.opener != null && !window.opener.closed) {
                   8476:22):             window.opener.location.href=dest;
                   8477:22):             window.close();
                   8478:22):         } else {
                   8479:22):             window.location.href=dest;
                   8480:22):         }
                   8481:22):     }
                   8482:22): }
                   8483:22): \$(document).ready(function () {
                   8484:22):     setTimeout('LC_To_Opener()',$timeout);
                   8485:22): });
                   8486:22): // ]]>
                   8487:22): </script>
                   8488:22): ENDJS
                   8489:22):         } else {
                   8490:22):             $result.=<<"ADDMETA";
1.344     albertel 8491: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8492: ADDMETA
1.1075.2.161.  .9(raebu 8493:22):         }
1.1075.2.89  raeburn  8494:     } else {
                   8495:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8496:             my $requrl = $env{'request.uri'};
                   8497:             if ($requrl eq '') {
                   8498:                 $requrl = $ENV{'REQUEST_URI'};
                   8499:                 $requrl =~ s/\?.+$//;
                   8500:             }
                   8501:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8502:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8503:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8504:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8505:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8506:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8507:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8508:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8509:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8510:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8511:                             $offload = 1;
1.1075.2.151  raeburn  8512:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8513:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8514:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8515:                                     $offloadoth = 1;
                   8516:                                     $dom_in_use = $env{'user.domain'};
                   8517:                                 }
                   8518:                             }
1.1075.2.145  raeburn  8519:                         }
                   8520:                     }
                   8521:                     unless ($offload) {
                   8522:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8523:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8524:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8525:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8526:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8527:                                         $offload = 1;
1.1075.2.151  raeburn  8528:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8529:                                         $dom_in_use = $env{'user.domain'};
                   8530:                                     }
1.1075.2.89  raeburn  8531:                                 }
1.1075.2.145  raeburn  8532:                             }
                   8533:                         }
                   8534:                     }
                   8535:                     if ($offload) {
1.1075.2.158  raeburn  8536:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8537:                         if (($newserver eq '') && ($offloadoth)) {
                   8538:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 8539:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  8540:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8541:                             }
                   8542:                         }
1.1075.2.145  raeburn  8543:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8544:                             my $numsec = 5;
                   8545:                             my $timeout = $numsec * 1000;
                   8546:                             my ($newurl,$locknum,%locks,$msg);
                   8547:                             if ($env{'request.role.adv'}) {
                   8548:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8549:                             }
                   8550:                             my $disable_submit = 0;
                   8551:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8552:                                 $disable_submit = 1;
                   8553:                             }
                   8554:                             if ($locknum) {
                   8555:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8556:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8557:                                        join(", ",sort(values(%locks)))."\n";
                   8558:                                 if (&show_course()) {
                   8559:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8560:                                 } else {
1.1075.2.145  raeburn  8561:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8562:                                 }
                   8563:                             } else {
                   8564:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8565:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8566:                                 }
                   8567:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8568:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8569:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8570:                                     $newurl .= '&role='.$env{'request.role'};
                   8571:                                 }
                   8572:                                 if ($env{'request.symb'}) {
                   8573:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8574:                                     if ($shownsymb =~ m{^/enc/}) {
                   8575:                                         my $reqdmajor = 2;
                   8576:                                         my $reqdminor = 11;
                   8577:                                         my $reqdsubminor = 3;
                   8578:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8579:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8580:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8581:                                         if (($major eq '' && $minor eq '') ||
                   8582:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8583:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8584:                                              ($reqdsubminor > $subminor))))) {
                   8585:                                             undef($shownsymb);
                   8586:                                         }
1.1075.2.89  raeburn  8587:                                     }
1.1075.2.145  raeburn  8588:                                     if ($shownsymb) {
                   8589:                                         &js_escape(\$shownsymb);
                   8590:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8591:                                     }
1.1075.2.145  raeburn  8592:                                 } else {
                   8593:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8594:                                     &js_escape(\$shownurl);
                   8595:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8596:                                 }
1.1075.2.145  raeburn  8597:                             }
                   8598:                             &js_escape(\$msg);
                   8599:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8600: <meta http-equiv="pragma" content="no-cache" />
                   8601: <script type="text/javascript">
1.1075.2.92  raeburn  8602: // <![CDATA[
1.1075.2.89  raeburn  8603: function LC_Offload_Now() {
                   8604:     var dest = "$newurl";
                   8605:     if (dest != '') {
                   8606:         window.location.href="$newurl";
                   8607:     }
                   8608: }
1.1075.2.92  raeburn  8609: \$(document).ready(function () {
                   8610:     window.alert('$msg');
                   8611:     if ($disable_submit) {
1.1075.2.89  raeburn  8612:         \$(".LC_hwk_submit").prop("disabled", true);
                   8613:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8614:     }
                   8615:     setTimeout('LC_Offload_Now()', $timeout);
                   8616: });
                   8617: // ]]>
1.1075.2.89  raeburn  8618: </script>
                   8619: OFFLOAD
                   8620:                         }
                   8621:                     }
                   8622:                 }
                   8623:             }
                   8624:         }
1.313     albertel 8625:     }
1.306     albertel 8626:     if (!defined($title)) {
                   8627: 	$title = 'The LearningOnline Network with CAPA';
                   8628:     }
1.460     albertel 8629:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8630:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8631: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8632:     if (!$args->{'frameset'}) {
                   8633:         $result .= ' /';
                   8634:     }
                   8635:     $result .= '>'
1.1064    raeburn  8636:         .$inhibitprint
1.414     albertel 8637: 	.$head_extra;
1.1075.2.108  raeburn  8638:     my $clientmobile;
                   8639:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8640:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8641:     } else {
                   8642:         $clientmobile = $env{'browser.mobile'};
                   8643:     }
                   8644:     if ($clientmobile) {
1.1075.2.42  raeburn  8645:         $result .= '
                   8646: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8647: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8648:     }
1.1075.2.126  raeburn  8649:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8650:     return $result.'</head>';
1.306     albertel 8651: }
                   8652: 
                   8653: =pod
                   8654: 
1.340     albertel 8655: =item * &font_settings()
                   8656: 
                   8657: Returns neccessary <meta> to set the proper encoding
                   8658: 
1.1075.2.56  raeburn  8659: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8660: 
                   8661: =cut
                   8662: 
                   8663: sub font_settings {
1.1075.2.56  raeburn  8664:     my ($args) = @_;
1.340     albertel 8665:     my $headerstring='';
1.1075.2.56  raeburn  8666:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8667:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8668: 	$headerstring.=
1.1075.2.61  raeburn  8669: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8670:         if (!$args->{'frameset'}) {
                   8671:             $headerstring.= ' /';
                   8672:         }
                   8673:         $headerstring .= '>'."\n";
1.340     albertel 8674:     }
                   8675:     return $headerstring;
                   8676: }
                   8677: 
1.341     albertel 8678: =pod
                   8679: 
1.1064    raeburn  8680: =item * &print_suppression()
                   8681: 
                   8682: In course context returns css which causes the body to be blank when media="print",
                   8683: if printout generation is unavailable for the current resource.
                   8684: 
                   8685: This could be because:
                   8686: 
                   8687: (a) printstartdate is in the future
                   8688: 
                   8689: (b) printenddate is in the past
                   8690: 
                   8691: (c) there is an active exam block with "printout"
                   8692: functionality blocked
                   8693: 
                   8694: Users with pav, pfo or evb privileges are exempt.
                   8695: 
                   8696: Inputs: none
                   8697: 
                   8698: =cut
                   8699: 
                   8700: 
                   8701: sub print_suppression {
                   8702:     my $noprint;
                   8703:     if ($env{'request.course.id'}) {
                   8704:         my $scope = $env{'request.course.id'};
                   8705:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8706:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8707:             return;
                   8708:         }
                   8709:         if ($env{'request.course.sec'} ne '') {
                   8710:             $scope .= "/$env{'request.course.sec'}";
                   8711:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8712:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8713:                 return;
1.1064    raeburn  8714:             }
                   8715:         }
                   8716:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8717:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  8718:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   8719:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8720:         if ($blocked) {
                   8721:             my $checkrole = "cm./$cdom/$cnum";
                   8722:             if ($env{'request.course.sec'} ne '') {
                   8723:                 $checkrole .= "/$env{'request.course.sec'}";
                   8724:             }
                   8725:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8726:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8727:                 $noprint = 1;
                   8728:             }
                   8729:         }
                   8730:         unless ($noprint) {
                   8731:             my $symb = &Apache::lonnet::symbread();
                   8732:             if ($symb ne '') {
                   8733:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8734:                 if (ref($navmap)) {
                   8735:                     my $res = $navmap->getBySymb($symb);
                   8736:                     if (ref($res)) {
                   8737:                         if (!$res->resprintable()) {
                   8738:                             $noprint = 1;
                   8739:                         }
                   8740:                     }
                   8741:                 }
                   8742:             }
                   8743:         }
                   8744:         if ($noprint) {
                   8745:             return <<"ENDSTYLE";
                   8746: <style type="text/css" media="print">
                   8747:     body { display:none }
                   8748: </style>
                   8749: ENDSTYLE
                   8750:         }
                   8751:     }
                   8752:     return;
                   8753: }
                   8754: 
                   8755: =pod
                   8756: 
1.341     albertel 8757: =item * &xml_begin()
                   8758: 
                   8759: Returns the needed doctype and <html>
                   8760: 
                   8761: Inputs: none
                   8762: 
                   8763: =cut
                   8764: 
                   8765: sub xml_begin {
1.1075.2.61  raeburn  8766:     my ($is_frameset) = @_;
1.341     albertel 8767:     my $output='';
                   8768: 
                   8769:     if ($env{'browser.mathml'}) {
                   8770: 	$output='<?xml version="1.0"?>'
                   8771:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8772: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8773:             
                   8774: #	    .'<!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">] >'
                   8775: 	    .'<!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">'
                   8776:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8777: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8778:     } elsif ($is_frameset) {
                   8779:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8780:                 '<html>'."\n";
1.341     albertel 8781:     } else {
1.1075.2.61  raeburn  8782: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8783:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8784:     }
                   8785:     return $output;
                   8786: }
1.340     albertel 8787: 
                   8788: =pod
                   8789: 
1.306     albertel 8790: =item * &start_page()
                   8791: 
                   8792: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8793: 
1.648     raeburn  8794: Inputs:
                   8795: 
                   8796: =over 4
                   8797: 
                   8798: $title - optional title for the page
                   8799: 
                   8800: $head_extra - optional extra HTML to incude inside the <head>
                   8801: 
                   8802: $args - additional optional args supported are:
                   8803: 
                   8804: =over 8
                   8805: 
                   8806:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8807:                                     arg on
1.814     bisitz   8808:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8809:              add_entries    -> additional attributes to add to the  <body>
                   8810:              domain         -> force to color decorate a page for a 
1.317     albertel 8811:                                     specific domain
1.648     raeburn  8812:              function       -> force usage of a specific rolish color
1.317     albertel 8813:                                     scheme
1.648     raeburn  8814:              redirect       -> see &headtag()
                   8815:              bgcolor        -> override the default page bg color
                   8816:              js_ready       -> return a string ready for being used in 
1.317     albertel 8817:                                     a javascript writeln
1.648     raeburn  8818:              html_encode    -> return a string ready for being used in 
1.320     albertel 8819:                                     a html attribute
1.648     raeburn  8820:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8821:                                     $forcereg arg
1.648     raeburn  8822:              frameset       -> if true will start with a <frameset>
1.330     albertel 8823:                                     rather than <body>
1.648     raeburn  8824:              skip_phases    -> hash ref of 
1.338     albertel 8825:                                     head -> skip the <html><head> generation
                   8826:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8827:              no_inline_link -> if true and in remote mode, don't show the
                   8828:                                     'Switch To Inline Menu' link
1.648     raeburn  8829:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8830:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8831:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8832:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8833:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8834:              group          -> includes the current group, if page is for a
                   8835:                                specific group
1.1075.2.133  raeburn  8836:              use_absolute   -> for request for external resource or syllabus, this
                   8837:                                will contain https://<hostname> if server uses
                   8838:                                https (as per hosts.tab), but request is for http
                   8839:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  8840:              links_disabled -> Links in primary and secondary menus are disabled
                   8841:                                (Can enable them once page has loaded - see lonroles.pm
                   8842:                                for an example).
1.1075.2.161.  .6(raebu 8843:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 8844: 
1.648     raeburn  8845: =back
1.460     albertel 8846: 
1.648     raeburn  8847: =back
1.562     albertel 8848: 
1.306     albertel 8849: =cut
                   8850: 
                   8851: sub start_page {
1.309     albertel 8852:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8853:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8854: 
1.315     albertel 8855:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 8856:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8857: 
1.338     albertel 8858:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8859:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8860:     }
1.1075.2.161.  .1(raebu 8861:21): 
                   8862:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   8863:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8864:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8865:21):                 $args->{'no_primary_menu'} = 1;
                   8866:21):             }
                   8867:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8868:21):                 $args->{'no_inline_menu'} = 1;
                   8869:21):             }
                   8870:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8871:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8872:21):             }
                   8873:21):         } else {
                   8874:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8875:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8876:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8877:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8878:21):                     $args->{'no_primary_menu'} = 1;
                   8879:21):                 }
                   8880:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8881:21):                     $args->{'no_inline_menu'} = 1;
                   8882:21):                 }
                   8883:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8884:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8885:21):                 }
                   8886:21):             }
                   8887:21):         }
                   8888:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8889:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8890:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8891:21):     } elsif ($env{'request.course.id'}) {
                   8892:21):         my $expiretime=600;
                   8893:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   8894:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   8895:21):         }
                   8896:21):         my ($deeplinkmenu,$menuref);
                   8897:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   8898:21):         if ($menucoll) {
                   8899:21):             if (ref($menuref) eq 'HASH') {
                   8900:21):                 %menu = %{$menuref};
                   8901:21):             }
                   8902:21):             if ($menu{'top'} eq 'n') {
                   8903:21):                 $args->{'no_primary_menu'} = 1;
                   8904:21):             }
                   8905:21):             if ($menu{'inline'} eq 'n') {
                   8906:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   8907:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8908:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8909:21):                     my $crstype = &course_type();
                   8910:21):                     my $now = time;
                   8911:21):                     my $ccrole;
                   8912:21):                     if ($crstype eq 'Community') {
                   8913:21):                         $ccrole = 'co';
                   8914:21):                     } else {
                   8915:21):                         $ccrole = 'cc';
                   8916:21):                     }
                   8917:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   8918:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   8919:21):                         if ((($start) && ($start<0)) ||
                   8920:21):                             (($end) && ($end<$now))  ||
                   8921:21):                             (($start) && ($now<$start))) {
                   8922:21):                             $args->{'no_inline_menu'} = 1;
                   8923:21):                         }
                   8924:21):                     } else {
                   8925:21):                         $args->{'no_inline_menu'} = 1;
                   8926:21):                     }
                   8927:21):                 }
                   8928:21):             }
                   8929:21):         }
                   8930:21):     }
          .4(raebu 8931:22): 
          .8(raebu 8932:22):     my $showncrumbs;
1.338     albertel 8933:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8934: 	if ($args->{'frameset'}) {
                   8935: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8936: 						$args->{'add_entries'});
                   8937: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8938:         } else {
                   8939:             $result .=
                   8940:                 &bodytag($title, 
                   8941:                          $args->{'function'},       $args->{'add_entries'},
                   8942:                          $args->{'only_body'},      $args->{'domain'},
                   8943:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8944:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 8945:21):                          $args,                     \@advtools,
          .8(raebu 8946:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   8947:         }
1.330     albertel 8948:     }
1.338     albertel 8949: 
1.315     albertel 8950:     if ($args->{'js_ready'}) {
1.713     kaisler  8951: 		$result = &js_ready($result);
1.315     albertel 8952:     }
1.320     albertel 8953:     if ($args->{'html_encode'}) {
1.713     kaisler  8954: 		$result = &html_encode($result);
                   8955:     }
                   8956: 
1.813     bisitz   8957:     # Preparation for new and consistent functionlist at top of screen
                   8958:     # if ($args->{'functionlist'}) {
                   8959:     #            $result .= &build_functionlist();
                   8960:     #}
                   8961: 
1.964     droeschl 8962:     # Don't add anything more if only_body wanted or in const space
                   8963:     return $result if    $args->{'only_body'} 
                   8964:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8965: 
                   8966:     #Breadcrumbs
1.758     kaisler  8967:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 8968:22):         unless ($showncrumbs) {
1.758     kaisler  8969: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8970: 		#if any br links exists, add them to the breadcrumbs
                   8971: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8972: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8973: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8974: 			}
                   8975: 		}
1.1075.2.19  raeburn  8976:                 # if @advtools array contains items add then to the breadcrumbs
                   8977:                 if (@advtools > 0) {
                   8978:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8979:                 }
1.1075.2.123  raeburn  8980:                 my $menulink;
                   8981:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 8982:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8983:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  8984:                     $menulink = 0;
                   8985:                 } else {
                   8986:                     undef($menulink);
                   8987:                 }
1.1075.2.161.  .8(raebu 8988:22):                 my $linkprotout;
                   8989:22):                 if ($env{'request.deeplink.login'}) {
                   8990:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   8991:22):                     if ($linkprotout) {
                   8992:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   8993:22):                     }
                   8994:22):                 }
1.758     kaisler  8995: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8996: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8997: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 8998:21): 		} else {
1.1075.2.123  raeburn  8999: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9000: 		}
1.1075.2.161.  .8(raebu 9001:22):         }
1.1075.2.24  raeburn  9002:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9003:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9004:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9005:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9006:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9007:     }
1.315     albertel 9008:     return $result;
1.306     albertel 9009: }
                   9010: 
                   9011: sub end_page {
1.315     albertel 9012:     my ($args) = @_;
                   9013:     $env{'internal.end_page'}++;
1.330     albertel 9014:     my $result;
1.335     albertel 9015:     if ($args->{'discussion'}) {
                   9016: 	my ($target,$parser);
                   9017: 	if (ref($args->{'discussion'})) {
                   9018: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9019: 				$args->{'discussion'}{'parser'});
                   9020: 	}
                   9021: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9022:     }
1.330     albertel 9023:     if ($args->{'frameset'}) {
                   9024: 	$result .= '</frameset>';
                   9025:     } else {
1.635     raeburn  9026: 	$result .= &endbodytag($args);
1.330     albertel 9027:     }
1.1075.2.6  raeburn  9028:     unless ($args->{'notbody'}) {
                   9029:         $result .= "\n</html>";
                   9030:     }
1.330     albertel 9031: 
1.315     albertel 9032:     if ($args->{'js_ready'}) {
1.317     albertel 9033: 	$result = &js_ready($result);
1.315     albertel 9034:     }
1.335     albertel 9035: 
1.320     albertel 9036:     if ($args->{'html_encode'}) {
                   9037: 	$result = &html_encode($result);
                   9038:     }
1.335     albertel 9039: 
1.315     albertel 9040:     return $result;
                   9041: }
                   9042: 
1.1075.2.161.  .1(raebu 9043:21): sub menucoll_in_effect {
                   9044:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9045:21):     if ($env{'request.course.id'}) {
                   9046:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9047:21):         if ($env{'request.deeplink.login'}) {
                   9048:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9049:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9050:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9051:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9052:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9053:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9054:21):                     if (ref($navmap)) {
                   9055:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9056:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9057:21):                                                           '0.deeplink');
                   9058:21):                     } else {
                   9059:21):                         $check_login_symb = 1;
                   9060:21):                     }
                   9061:21):                 } else {
                   9062:21):                     my $symb=&Apache::lonnet::symbread();
                   9063:21):                     if ($symb) {
                   9064:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9065:21):                     } else {
                   9066:21):                         $check_login_symb = 1;
                   9067:21):                     }
                   9068:21):                 }
                   9069:21):             } else {
                   9070:21):                 $check_login_symb = 1;
                   9071:21):             }
                   9072:21):             if ($check_login_symb) {
                   9073:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9074:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9075:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9076:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9077:21):                     if (ref($navmap)) {
                   9078:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9079:21):                     }
                   9080:21):                 } else {
                   9081:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9082:21):                 }
                   9083:21):             }
                   9084:21):             if ($deeplink ne '') {
          .6(raebu 9085:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9086:21):                 if ($display =~ /^\d+$/) {
                   9087:21):                     $deeplinkmenu = 1;
                   9088:21):                     $menucoll = $display;
                   9089:21):                 }
                   9090:21):             }
                   9091:21):         }
                   9092:21):         if ($menucoll) {
                   9093:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9094:21):         }
                   9095:21):     }
                   9096:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9097:21): }
                   9098:21): 
                   9099:21): sub deeplink_login_symb {
                   9100:21):     my ($cnum,$cdom) = @_;
                   9101:21):     my $login_symb;
                   9102:21):     if ($env{'request.deeplink.login'}) {
                   9103:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9104:21):     }
                   9105:21):     return $login_symb;
                   9106:21): }
                   9107:21): 
                   9108:21): sub symb_from_tinyurl {
                   9109:21):     my ($url,$cnum,$cdom) = @_;
                   9110:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9111:21):         my $key = $1;
                   9112:21):         my ($tinyurl,$login);
                   9113:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9114:21):         if (defined($cached)) {
                   9115:21):             $tinyurl = $result;
                   9116:21):         } else {
                   9117:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9118:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9119:21):             if ($currtiny{$key} ne '') {
                   9120:21):                 $tinyurl = $currtiny{$key};
                   9121:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9122:21):             }
                   9123:21):         }
                   9124:21):         if ($tinyurl ne '') {
                   9125:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9126:21):             if (wantarray) {
                   9127:21):                 return ($cnumreq,$symb);
                   9128:21):             } elsif ($cnumreq eq $cnum) {
                   9129:21):                 return $symb;
                   9130:21):             }
                   9131:21):         }
                   9132:21):     }
                   9133:21):     if (wantarray) {
                   9134:21):         return ();
                   9135:21):     } else {
                   9136:21):         return;
                   9137:21):     }
                   9138:21): }
                   9139:21): 
1.1034    www      9140: sub wishlist_window {
                   9141:     return(<<'ENDWISHLIST');
1.1046    raeburn  9142: <script type="text/javascript">
1.1034    www      9143: // <![CDATA[
                   9144: // <!-- BEGIN LON-CAPA Internal
                   9145: function set_wishlistlink(title, path) {
                   9146:     if (!title) {
                   9147:         title = document.title;
                   9148:         title = title.replace(/^LON-CAPA /,'');
                   9149:     }
1.1075.2.65  raeburn  9150:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9151:     title = title.replace("'","\\\'");
1.1034    www      9152:     if (!path) {
                   9153:         path = location.pathname;
                   9154:     }
1.1075.2.65  raeburn  9155:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9156:     path = path.replace("'","\\\'");
1.1034    www      9157:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9158:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9159: }
                   9160: // END LON-CAPA Internal -->
                   9161: // ]]>
                   9162: </script>
                   9163: ENDWISHLIST
                   9164: }
                   9165: 
1.1030    www      9166: sub modal_window {
                   9167:     return(<<'ENDMODAL');
1.1046    raeburn  9168: <script type="text/javascript">
1.1030    www      9169: // <![CDATA[
                   9170: // <!-- BEGIN LON-CAPA Internal
                   9171: var modalWindow = {
                   9172: 	parent:"body",
                   9173: 	windowId:null,
                   9174: 	content:null,
                   9175: 	width:null,
                   9176: 	height:null,
                   9177: 	close:function()
                   9178: 	{
                   9179: 	        $(".LCmodal-window").remove();
                   9180: 	        $(".LCmodal-overlay").remove();
                   9181: 	},
                   9182: 	open:function()
                   9183: 	{
                   9184: 		var modal = "";
                   9185: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9186: 		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;\">";
                   9187: 		modal += this.content;
                   9188: 		modal += "</div>";	
                   9189: 
                   9190: 		$(this.parent).append(modal);
                   9191: 
                   9192: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9193: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9194: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9195: 	}
                   9196: };
1.1075.2.42  raeburn  9197: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9198: 	{
1.1075.2.119  raeburn  9199:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9200: 		modalWindow.windowId = "myModal";
                   9201: 		modalWindow.width = width;
                   9202: 		modalWindow.height = height;
1.1075.2.80  raeburn  9203: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9204: 		modalWindow.open();
1.1075.2.87  raeburn  9205: 	};
1.1030    www      9206: // END LON-CAPA Internal -->
                   9207: // ]]>
                   9208: </script>
                   9209: ENDMODAL
                   9210: }
                   9211: 
                   9212: sub modal_link {
1.1075.2.42  raeburn  9213:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9214:     unless ($width) { $width=480; }
                   9215:     unless ($height) { $height=400; }
1.1031    www      9216:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9217:     unless ($transparency) { $transparency='true'; }
                   9218: 
1.1074    raeburn  9219:     my $target_attr;
                   9220:     if (defined($target)) {
                   9221:         $target_attr = 'target="'.$target.'"';
                   9222:     }
                   9223:     return <<"ENDLINK";
1.1075.2.143  raeburn  9224: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9225: ENDLINK
1.1030    www      9226: }
                   9227: 
1.1032    www      9228: sub modal_adhoc_script {
1.1075.2.155  raeburn  9229:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9230:     my $mathjax;
                   9231:     if ($possmathjax) {
                   9232:         $mathjax = <<'ENDJAX';
                   9233:                if (typeof MathJax == 'object') {
                   9234:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9235:                }
                   9236: ENDJAX
                   9237:     }
1.1032    www      9238:     return (<<ENDADHOC);
1.1046    raeburn  9239: <script type="text/javascript">
1.1032    www      9240: // <![CDATA[
                   9241:         var $funcname = function()
                   9242:         {
                   9243:                 modalWindow.windowId = "myModal";
                   9244:                 modalWindow.width = $width;
                   9245:                 modalWindow.height = $height;
                   9246:                 modalWindow.content = '$content';
                   9247:                 modalWindow.open();
1.1075.2.155  raeburn  9248:                 $mathjax
1.1032    www      9249:         };  
                   9250: // ]]>
                   9251: </script>
                   9252: ENDADHOC
                   9253: }
                   9254: 
1.1041    www      9255: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9256:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9257:     my $innerwidth=$width-20;
                   9258:     $content=&js_ready(
1.1042    www      9259:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9260:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9261:                  $content.
1.1041    www      9262:                  &end_scrollbox().
1.1075.2.42  raeburn  9263:                  &end_page()
1.1041    www      9264:              );
1.1075.2.155  raeburn  9265:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9266: }
                   9267: 
                   9268: sub modal_adhoc_window {
1.1075.2.155  raeburn  9269:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9270:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9271:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9272: }
                   9273: 
                   9274: sub modal_adhoc_launch {
                   9275:     my ($funcname,$width,$height,$content)=@_;
                   9276:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9277: <script type="text/javascript">
                   9278: // <![CDATA[
                   9279: $funcname();
                   9280: // ]]>
                   9281: </script>
                   9282: ENDLAUNCH
                   9283: }
                   9284: 
                   9285: sub modal_adhoc_close {
                   9286:     return (<<ENDCLOSE);
                   9287: <script type="text/javascript">
                   9288: // <![CDATA[
                   9289: modalWindow.close();
                   9290: // ]]>
                   9291: </script>
                   9292: ENDCLOSE
                   9293: }
                   9294: 
1.1038    www      9295: sub togglebox_script {
                   9296:    return(<<ENDTOGGLE);
                   9297: <script type="text/javascript"> 
                   9298: // <![CDATA[
                   9299: function LCtoggleDisplay(id,hidetext,showtext) {
                   9300:    link = document.getElementById(id + "link").childNodes[0];
                   9301:    with (document.getElementById(id).style) {
                   9302:       if (display == "none" ) {
                   9303:           display = "inline";
                   9304:           link.nodeValue = hidetext;
                   9305:         } else {
                   9306:           display = "none";
                   9307:           link.nodeValue = showtext;
                   9308:        }
                   9309:    }
                   9310: }
                   9311: // ]]>
                   9312: </script>
                   9313: ENDTOGGLE
                   9314: }
                   9315: 
1.1039    www      9316: sub start_togglebox {
                   9317:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9318:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9319:     unless ($showtext) { $showtext=&mt('show'); }
                   9320:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9321:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9322:     return &start_data_table().
                   9323:            &start_data_table_header_row().
                   9324:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9325:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9326:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9327:            &end_data_table_header_row().
                   9328:            '<tr id="'.$id.'" style="display:none""><td>';
                   9329: }
                   9330: 
                   9331: sub end_togglebox {
                   9332:     return '</td></tr>'.&end_data_table();
                   9333: }
                   9334: 
1.1041    www      9335: sub LCprogressbar_script {
1.1075.2.130  raeburn  9336:    my ($id,$number_to_do)=@_;
                   9337:    if ($number_to_do) {
                   9338:        return(<<ENDPROGRESS);
1.1041    www      9339: <script type="text/javascript">
                   9340: // <![CDATA[
1.1045    www      9341: \$('#progressbar$id').progressbar({
1.1041    www      9342:   value: 0,
                   9343:   change: function(event, ui) {
                   9344:     var newVal = \$(this).progressbar('option', 'value');
                   9345:     \$('.pblabel', this).text(LCprogressTxt);
                   9346:   }
                   9347: });
                   9348: // ]]>
                   9349: </script>
                   9350: ENDPROGRESS
1.1075.2.130  raeburn  9351:    } else {
                   9352:        return(<<ENDPROGRESS);
                   9353: <script type="text/javascript">
                   9354: // <![CDATA[
                   9355: \$('#progressbar$id').progressbar({
                   9356:   value: false,
                   9357:   create: function(event, ui) {
                   9358:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9359:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9360:   }
                   9361: });
                   9362: // ]]>
                   9363: </script>
                   9364: ENDPROGRESS
                   9365:    }
1.1041    www      9366: }
                   9367: 
                   9368: sub LCprogressbarUpdate_script {
                   9369:    return(<<ENDPROGRESSUPDATE);
                   9370: <style type="text/css">
                   9371: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9372: .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      9373: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9374: </style>
                   9375: <script type="text/javascript">
                   9376: // <![CDATA[
1.1045    www      9377: var LCprogressTxt='---';
                   9378: 
1.1075.2.130  raeburn  9379: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9380:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9381:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9382:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9383:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9384:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9385:    } else {
                   9386:        \$('#progressbar'+id).progressbar('value',percent);
                   9387:    }
1.1041    www      9388: }
                   9389: // ]]>
                   9390: </script>
                   9391: ENDPROGRESSUPDATE
                   9392: }
                   9393: 
1.1042    www      9394: my $LClastpercent;
1.1045    www      9395: my $LCidcnt;
                   9396: my $LCcurrentid;
1.1042    www      9397: 
1.1041    www      9398: sub LCprogressbar {
1.1075.2.130  raeburn  9399:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9400:     $LClastpercent=0;
1.1045    www      9401:     $LCidcnt++;
                   9402:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9403:     my ($starting,$content);
                   9404:     if ($number_to_do) {
                   9405:         $starting=&mt('Starting');
                   9406:         $content=(<<ENDPROGBAR);
                   9407: $preamble
1.1045    www      9408:   <div id="progressbar$LCcurrentid">
1.1041    www      9409:     <span class="pblabel">$starting</span>
                   9410:   </div>
                   9411: ENDPROGBAR
1.1075.2.130  raeburn  9412:     } else {
                   9413:         $starting=&mt('Loading...');
                   9414:         $LClastpercent='false';
                   9415:         $content=(<<ENDPROGBAR);
                   9416: $preamble
                   9417:   <div id="progressbar$LCcurrentid">
                   9418:       <div class="progress-label">$starting</div>
                   9419:   </div>
                   9420: ENDPROGBAR
                   9421:     }
                   9422:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9423: }
                   9424: 
                   9425: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9426:     my ($r,$val,$text,$number_to_do)=@_;
                   9427:     if ($number_to_do) {
                   9428:         unless ($val) { 
                   9429:             if ($LClastpercent) {
                   9430:                 $val=$LClastpercent;
                   9431:             } else {
                   9432:                 $val=0;
                   9433:             }
                   9434:         }
                   9435:         if ($val<0) { $val=0; }
                   9436:         if ($val>100) { $val=0; }
                   9437:         $LClastpercent=$val;
                   9438:         unless ($text) { $text=$val.'%'; }
                   9439:     } else {
                   9440:         $val = 'false';
1.1042    www      9441:     }
1.1041    www      9442:     $text=&js_ready($text);
1.1044    www      9443:     &r_print($r,<<ENDUPDATE);
1.1041    www      9444: <script type="text/javascript">
                   9445: // <![CDATA[
1.1075.2.130  raeburn  9446: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9447: // ]]>
                   9448: </script>
                   9449: ENDUPDATE
1.1035    www      9450: }
                   9451: 
1.1042    www      9452: sub LCprogressbarClose {
                   9453:     my ($r)=@_;
                   9454:     $LClastpercent=0;
1.1044    www      9455:     &r_print($r,<<ENDCLOSE);
1.1042    www      9456: <script type="text/javascript">
                   9457: // <![CDATA[
1.1045    www      9458: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9459: // ]]>
                   9460: </script>
                   9461: ENDCLOSE
1.1044    www      9462: }
                   9463: 
                   9464: sub r_print {
                   9465:     my ($r,$to_print)=@_;
                   9466:     if ($r) {
                   9467:       $r->print($to_print);
                   9468:       $r->rflush();
                   9469:     } else {
                   9470:       print($to_print);
                   9471:     }
1.1042    www      9472: }
                   9473: 
1.320     albertel 9474: sub html_encode {
                   9475:     my ($result) = @_;
                   9476: 
1.322     albertel 9477:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9478:     
                   9479:     return $result;
                   9480: }
1.1044    www      9481: 
1.317     albertel 9482: sub js_ready {
                   9483:     my ($result) = @_;
                   9484: 
1.323     albertel 9485:     $result =~ s/[\n\r]/ /xmsg;
                   9486:     $result =~ s/\\/\\\\/xmsg;
                   9487:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9488:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9489:     
                   9490:     return $result;
                   9491: }
                   9492: 
1.315     albertel 9493: sub validate_page {
                   9494:     if (  exists($env{'internal.start_page'})
1.316     albertel 9495: 	  &&     $env{'internal.start_page'} > 1) {
                   9496: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9497: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9498: 				 $ENV{'request.filename'});
1.315     albertel 9499:     }
                   9500:     if (  exists($env{'internal.end_page'})
1.316     albertel 9501: 	  &&     $env{'internal.end_page'} > 1) {
                   9502: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9503: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9504: 				 $env{'request.filename'});
1.315     albertel 9505:     }
                   9506:     if (     exists($env{'internal.start_page'})
                   9507: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9508: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9509: 				 $env{'request.filename'});
1.315     albertel 9510:     }
                   9511:     if (   ! exists($env{'internal.start_page'})
                   9512: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9513: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9514: 				 $env{'request.filename'});
1.315     albertel 9515:     }
1.306     albertel 9516: }
1.315     albertel 9517: 
1.996     www      9518: 
                   9519: sub start_scrollbox {
1.1075.2.56  raeburn  9520:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9521:     unless ($outerwidth) { $outerwidth='520px'; }
                   9522:     unless ($width) { $width='500px'; }
                   9523:     unless ($height) { $height='200px'; }
1.1075    raeburn  9524:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9525:     if ($id ne '') {
1.1075.2.42  raeburn  9526:         $table_id = ' id="table_'.$id.'"';
                   9527:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9528:     }
1.1075    raeburn  9529:     if ($bgcolor ne '') {
                   9530:         $tdcol = "background-color: $bgcolor;";
                   9531:     }
1.1075.2.42  raeburn  9532:     my $nicescroll_js;
                   9533:     if ($env{'browser.mobile'}) {
                   9534:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9535:     }
1.1075    raeburn  9536:     return <<"END";
1.1075.2.42  raeburn  9537: $nicescroll_js
                   9538: 
                   9539: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  9540: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  9541: END
1.996     www      9542: }
                   9543: 
                   9544: sub end_scrollbox {
1.1036    www      9545:     return '</div></td></tr></table>';
1.996     www      9546: }
                   9547: 
1.1075.2.42  raeburn  9548: sub nicescroll_javascript {
                   9549:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9550:     my %options;
                   9551:     if (ref($cursor) eq 'HASH') {
                   9552:         %options = %{$cursor};
                   9553:     }
                   9554:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9555:         $options{'railalign'} = 'left';
                   9556:     }
                   9557:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9558:         my $function  = &get_users_function();
                   9559:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   9560:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9561:             $options{'cursorcolor'} = '#00F';
                   9562:         }
                   9563:     }
                   9564:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9565:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   9566:             $options{'cursoropacity'}='1.0';
                   9567:         }
                   9568:     } else {
                   9569:         $options{'cursoropacity'}='1.0';
                   9570:     }
                   9571:     if ($options{'cursorfixedheight'} eq 'none') {
                   9572:         delete($options{'cursorfixedheight'});
                   9573:     } else {
                   9574:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9575:     }
                   9576:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9577:         delete($options{'railoffset'});
                   9578:     }
                   9579:     my @niceoptions;
                   9580:     while (my($key,$value) = each(%options)) {
                   9581:         if ($value =~ /^\{.+\}$/) {
                   9582:             push(@niceoptions,$key.':'.$value);
                   9583:         } else {
                   9584:             push(@niceoptions,$key.':"'.$value.'"');
                   9585:         }
                   9586:     }
                   9587:     my $nicescroll_js = '
                   9588: $(document).ready(
                   9589:       function() {
                   9590:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9591:       }
                   9592: );
                   9593: ';
                   9594:     if ($framecheck) {
                   9595:         $nicescroll_js .= '
                   9596: function expand_div(caller) {
                   9597:     if (top === self) {
                   9598:         document.getElementById("'.$id.'").style.width = "auto";
                   9599:         document.getElementById("'.$id.'").style.height = "auto";
                   9600:     } else {
                   9601:         try {
                   9602:             if (parent.frames) {
                   9603:                 if (parent.frames.length > 1) {
                   9604:                     var framesrc = parent.frames[1].location.href;
                   9605:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9606:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9607:                         document.getElementById("'.$id.'").style.width = "auto";
                   9608:                         document.getElementById("'.$id.'").style.height = "auto";
                   9609:                     }
                   9610:                 }
                   9611:             }
                   9612:         } catch (e) {
                   9613:             return;
                   9614:         }
                   9615:     }
                   9616:     return;
                   9617: }
                   9618: ';
                   9619:     }
                   9620:     if ($needjsready) {
                   9621:         $nicescroll_js = '
                   9622: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9623:     } else {
                   9624:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9625:     }
                   9626:     return $nicescroll_js;
                   9627: }
                   9628: 
1.318     albertel 9629: sub simple_error_page {
1.1075.2.49  raeburn  9630:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 9631:22):     my %displayargs;
1.1075.2.49  raeburn  9632:     if (ref($args) eq 'HASH') {
                   9633:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 9634:22):         if ($args->{'only_body'}) {
                   9635:22):             $displayargs{'only_body'} = 1;
                   9636:22):         }
                   9637:22):         if ($args->{'no_nav_bar'}) {
                   9638:22):             $displayargs{'no_nav_bar'} = 1;
                   9639:22):         }
1.1075.2.49  raeburn  9640:     } else {
                   9641:         $msg = &mt($msg);
                   9642:     }
                   9643: 
1.318     albertel 9644:     my $page =
1.1075.2.161.  .4(raebu 9645:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  9646: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9647: 	&Apache::loncommon::end_page();
                   9648:     if (ref($r)) {
                   9649: 	$r->print($page);
1.327     albertel 9650: 	return;
1.318     albertel 9651:     }
                   9652:     return $page;
                   9653: }
1.347     albertel 9654: 
                   9655: {
1.610     albertel 9656:     my @row_count;
1.961     onken    9657: 
                   9658:     sub start_data_table_count {
                   9659:         unshift(@row_count, 0);
                   9660:         return;
                   9661:     }
                   9662: 
                   9663:     sub end_data_table_count {
                   9664:         shift(@row_count);
                   9665:         return;
                   9666:     }
                   9667: 
1.347     albertel 9668:     sub start_data_table {
1.1018    raeburn  9669: 	my ($add_class,$id) = @_;
1.422     albertel 9670: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9671:         my $table_id;
                   9672:         if (defined($id)) {
                   9673:             $table_id = ' id="'.$id.'"';
                   9674:         }
1.961     onken    9675: 	&start_data_table_count();
1.1018    raeburn  9676: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9677:     }
                   9678: 
                   9679:     sub end_data_table {
1.961     onken    9680: 	&end_data_table_count();
1.389     albertel 9681: 	return '</table>'."\n";;
1.347     albertel 9682:     }
                   9683: 
                   9684:     sub start_data_table_row {
1.974     wenzelju 9685: 	my ($add_class, $id) = @_;
1.610     albertel 9686: 	$row_count[0]++;
                   9687: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9688: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9689:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9690:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9691:     }
1.471     banghart 9692:     
                   9693:     sub continue_data_table_row {
1.974     wenzelju 9694: 	my ($add_class, $id) = @_;
1.610     albertel 9695: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9696: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9697:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9698:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9699:     }
1.347     albertel 9700: 
                   9701:     sub end_data_table_row {
1.389     albertel 9702: 	return '</tr>'."\n";;
1.347     albertel 9703:     }
1.367     www      9704: 
1.421     albertel 9705:     sub start_data_table_empty_row {
1.707     bisitz   9706: #	$row_count[0]++;
1.421     albertel 9707: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9708:     }
                   9709: 
                   9710:     sub end_data_table_empty_row {
                   9711: 	return '</tr>'."\n";;
                   9712:     }
                   9713: 
1.367     www      9714:     sub start_data_table_header_row {
1.389     albertel 9715: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9716:     }
                   9717: 
                   9718:     sub end_data_table_header_row {
1.389     albertel 9719: 	return '</tr>'."\n";;
1.367     www      9720:     }
1.890     droeschl 9721: 
                   9722:     sub data_table_caption {
                   9723:         my $caption = shift;
                   9724:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9725:     }
1.347     albertel 9726: }
                   9727: 
1.548     albertel 9728: =pod
                   9729: 
                   9730: =item * &inhibit_menu_check($arg)
                   9731: 
                   9732: Checks for a inhibitmenu state and generates output to preserve it
                   9733: 
                   9734: Inputs:         $arg - can be any of
                   9735:                      - undef - in which case the return value is a string 
                   9736:                                to add  into arguments list of a uri
                   9737:                      - 'input' - in which case the return value is a HTML
                   9738:                                  <form> <input> field of type hidden to
                   9739:                                  preserve the value
                   9740:                      - a url - in which case the return value is the url with
                   9741:                                the neccesary cgi args added to preserve the
                   9742:                                inhibitmenu state
                   9743:                      - a ref to a url - no return value, but the string is
                   9744:                                         updated to include the neccessary cgi
                   9745:                                         args to preserve the inhibitmenu state
                   9746: 
                   9747: =cut
                   9748: 
                   9749: sub inhibit_menu_check {
                   9750:     my ($arg) = @_;
                   9751:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9752:     if ($arg eq 'input') {
                   9753: 	if ($env{'form.inhibitmenu'}) {
                   9754: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9755: 	} else {
                   9756: 	    return
                   9757: 	}
                   9758:     }
                   9759:     if ($env{'form.inhibitmenu'}) {
                   9760: 	if (ref($arg)) {
                   9761: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9762: 	} elsif ($arg eq '') {
                   9763: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9764: 	} else {
                   9765: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9766: 	}
                   9767:     }
                   9768:     if (!ref($arg)) {
                   9769: 	return $arg;
                   9770:     }
                   9771: }
                   9772: 
1.251     albertel 9773: ###############################################
1.182     matthew  9774: 
                   9775: =pod
                   9776: 
1.549     albertel 9777: =back
                   9778: 
                   9779: =head1 User Information Routines
                   9780: 
                   9781: =over 4
                   9782: 
1.405     albertel 9783: =item * &get_users_function()
1.182     matthew  9784: 
                   9785: Used by &bodytag to determine the current users primary role.
                   9786: Returns either 'student','coordinator','admin', or 'author'.
                   9787: 
                   9788: =cut
                   9789: 
                   9790: ###############################################
                   9791: sub get_users_function {
1.815     tempelho 9792:     my $function = 'norole';
1.818     tempelho 9793:     if ($env{'request.role'}=~/^(st)/) {
                   9794:         $function='student';
                   9795:     }
1.907     raeburn  9796:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9797:         $function='coordinator';
                   9798:     }
1.258     albertel 9799:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9800:         $function='admin';
                   9801:     }
1.826     bisitz   9802:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9803:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9804:         $function='author';
                   9805:     }
                   9806:     return $function;
1.54      www      9807: }
1.99      www      9808: 
                   9809: ###############################################
                   9810: 
1.233     raeburn  9811: =pod
                   9812: 
1.821     raeburn  9813: =item * &show_course()
                   9814: 
                   9815: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9816: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9817: 
                   9818: Inputs:
                   9819: None
                   9820: 
                   9821: Outputs:
                   9822: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9823: 
                   9824: =cut
                   9825: 
                   9826: ###############################################
                   9827: sub show_course {
                   9828:     my $course = !$env{'user.adv'};
                   9829:     if (!$env{'user.adv'}) {
                   9830:         foreach my $env (keys(%env)) {
                   9831:             next if ($env !~ m/^user\.priv\./);
                   9832:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9833:                 $course = 0;
                   9834:                 last;
                   9835:             }
                   9836:         }
                   9837:     }
                   9838:     return $course;
                   9839: }
                   9840: 
                   9841: ###############################################
                   9842: 
                   9843: =pod
                   9844: 
1.542     raeburn  9845: =item * &check_user_status()
1.274     raeburn  9846: 
                   9847: Determines current status of supplied role for a
                   9848: specific user. Roles can be active, previous or future.
                   9849: 
                   9850: Inputs: 
                   9851: user's domain, user's username, course's domain,
1.375     raeburn  9852: course's number, optional section ID.
1.274     raeburn  9853: 
                   9854: Outputs:
                   9855: role status: active, previous or future. 
                   9856: 
                   9857: =cut
                   9858: 
                   9859: sub check_user_status {
1.412     raeburn  9860:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9861:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9862:     my @uroles = keys(%userinfo);
1.274     raeburn  9863:     my $srchstr;
                   9864:     my $active_chk = 'none';
1.412     raeburn  9865:     my $now = time;
1.274     raeburn  9866:     if (@uroles > 0) {
1.908     raeburn  9867:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9868:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9869:         } else {
1.412     raeburn  9870:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9871:         }
                   9872:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9873:             my $role_end = 0;
                   9874:             my $role_start = 0;
                   9875:             $active_chk = 'active';
1.412     raeburn  9876:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9877:                 $role_end = $1;
                   9878:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9879:                     $role_start = $1;
1.274     raeburn  9880:                 }
                   9881:             }
                   9882:             if ($role_start > 0) {
1.412     raeburn  9883:                 if ($now < $role_start) {
1.274     raeburn  9884:                     $active_chk = 'future';
                   9885:                 }
                   9886:             }
                   9887:             if ($role_end > 0) {
1.412     raeburn  9888:                 if ($now > $role_end) {
1.274     raeburn  9889:                     $active_chk = 'previous';
                   9890:                 }
                   9891:             }
                   9892:         }
                   9893:     }
                   9894:     return $active_chk;
                   9895: }
                   9896: 
                   9897: ###############################################
                   9898: 
                   9899: =pod
                   9900: 
1.405     albertel 9901: =item * &get_sections()
1.233     raeburn  9902: 
                   9903: Determines all the sections for a course including
                   9904: sections with students and sections containing other roles.
1.419     raeburn  9905: Incoming parameters: 
                   9906: 
                   9907: 1. domain
                   9908: 2. course number 
                   9909: 3. reference to array containing roles for which sections should 
                   9910: be gathered (optional).
                   9911: 4. reference to array containing status types for which sections 
                   9912: should be gathered (optional).
                   9913: 
                   9914: If the third argument is undefined, sections are gathered for any role. 
                   9915: If the fourth argument is undefined, sections are gathered for any status.
                   9916: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9917:  
1.374     raeburn  9918: Returns section hash (keys are section IDs, values are
                   9919: number of users in each section), subject to the
1.419     raeburn  9920: optional roles filter, optional status filter 
1.233     raeburn  9921: 
                   9922: =cut
                   9923: 
                   9924: ###############################################
                   9925: sub get_sections {
1.419     raeburn  9926:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9927:     if (!defined($cdom) || !defined($cnum)) {
                   9928:         my $cid =  $env{'request.course.id'};
                   9929: 
                   9930: 	return if (!defined($cid));
                   9931: 
                   9932:         $cdom = $env{'course.'.$cid.'.domain'};
                   9933:         $cnum = $env{'course.'.$cid.'.num'};
                   9934:     }
                   9935: 
                   9936:     my %sectioncount;
1.419     raeburn  9937:     my $now = time;
1.240     albertel 9938: 
1.1075.2.33  raeburn  9939:     my $check_students = 1;
                   9940:     my $only_students = 0;
                   9941:     if (ref($possible_roles) eq 'ARRAY') {
                   9942:         if (grep(/^st$/,@{$possible_roles})) {
                   9943:             if (@{$possible_roles} == 1) {
                   9944:                 $only_students = 1;
                   9945:             }
                   9946:         } else {
                   9947:             $check_students = 0;
                   9948:         }
                   9949:     }
                   9950: 
                   9951:     if ($check_students) {
1.276     albertel 9952: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9953: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9954: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9955:         my $start_index = &Apache::loncoursedata::CL_START();
                   9956:         my $end_index = &Apache::loncoursedata::CL_END();
                   9957:         my $status;
1.366     albertel 9958: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9959: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9960: 				                     $data->[$status_index],
                   9961:                                                      $data->[$start_index],
                   9962:                                                      $data->[$end_index]);
                   9963:             if ($stu_status eq 'Active') {
                   9964:                 $status = 'active';
                   9965:             } elsif ($end < $now) {
                   9966:                 $status = 'previous';
                   9967:             } elsif ($start > $now) {
                   9968:                 $status = 'future';
                   9969:             } 
                   9970: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9971:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9972:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9973: 		    $sectioncount{$section}++;
                   9974:                 }
1.240     albertel 9975: 	    }
                   9976: 	}
                   9977:     }
1.1075.2.33  raeburn  9978:     if ($only_students) {
                   9979:         return %sectioncount;
                   9980:     }
1.240     albertel 9981:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9982:     foreach my $user (sort(keys(%courseroles))) {
                   9983: 	if ($user !~ /^(\w{2})/) { next; }
                   9984: 	my ($role) = ($user =~ /^(\w{2})/);
                   9985: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9986: 	my ($section,$status);
1.240     albertel 9987: 	if ($role eq 'cr' &&
                   9988: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9989: 	    $section=$1;
                   9990: 	}
                   9991: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9992: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9993:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9994:         if ($end == -1 && $start == -1) {
                   9995:             next; #deleted role
                   9996:         }
                   9997:         if (!defined($possible_status)) { 
                   9998:             $sectioncount{$section}++;
                   9999:         } else {
                   10000:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10001:                 $status = 'active';
                   10002:             } elsif ($end < $now) {
                   10003:                 $status = 'future';
                   10004:             } elsif ($start > $now) {
                   10005:                 $status = 'previous';
                   10006:             }
                   10007:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10008:                 $sectioncount{$section}++;
                   10009:             }
                   10010:         }
1.233     raeburn  10011:     }
1.366     albertel 10012:     return %sectioncount;
1.233     raeburn  10013: }
                   10014: 
1.274     raeburn  10015: ###############################################
1.294     raeburn  10016: 
                   10017: =pod
1.405     albertel 10018: 
                   10019: =item * &get_course_users()
                   10020: 
1.275     raeburn  10021: Retrieves usernames:domains for users in the specified course
                   10022: with specific role(s), and access status. 
                   10023: 
                   10024: Incoming parameters:
1.277     albertel 10025: 1. course domain
                   10026: 2. course number
                   10027: 3. access status: users must have - either active, 
1.275     raeburn  10028: previous, future, or all.
1.277     albertel 10029: 4. reference to array of permissible roles
1.288     raeburn  10030: 5. reference to array of section restrictions (optional)
                   10031: 6. reference to results object (hash of hashes).
                   10032: 7. reference to optional userdata hash
1.609     raeburn  10033: 8. reference to optional statushash
1.630     raeburn  10034: 9. flag if privileged users (except those set to unhide in
                   10035:    course settings) should be excluded    
1.609     raeburn  10036: Keys of top level results hash are roles.
1.275     raeburn  10037: Keys of inner hashes are username:domain, with 
                   10038: values set to access type.
1.288     raeburn  10039: Optional userdata hash returns an array with arguments in the 
                   10040: same order as loncoursedata::get_classlist() for student data.
                   10041: 
1.609     raeburn  10042: Optional statushash returns
                   10043: 
1.288     raeburn  10044: Entries for end, start, section and status are blank because
                   10045: of the possibility of multiple values for non-student roles.
                   10046: 
1.275     raeburn  10047: =cut
1.405     albertel 10048: 
1.275     raeburn  10049: ###############################################
1.405     albertel 10050: 
1.275     raeburn  10051: sub get_course_users {
1.630     raeburn  10052:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10053:     my %idx = ();
1.419     raeburn  10054:     my %seclists;
1.288     raeburn  10055: 
                   10056:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10057:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10058:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10059:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10060:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10061:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10062:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10063:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10064: 
1.290     albertel 10065:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10066:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10067:         my $now = time;
1.277     albertel 10068:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10069:             my $match = 0;
1.412     raeburn  10070:             my $secmatch = 0;
1.419     raeburn  10071:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10072:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10073:             if ($section eq '') {
                   10074:                 $section = 'none';
                   10075:             }
1.291     albertel 10076:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10077:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10078:                     $secmatch = 1;
                   10079:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10080:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10081:                         $secmatch = 1;
                   10082:                     }
                   10083:                 } else {  
1.419     raeburn  10084: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10085: 		        $secmatch = 1;
                   10086:                     }
1.290     albertel 10087: 		}
1.412     raeburn  10088:                 if (!$secmatch) {
                   10089:                     next;
                   10090:                 }
1.419     raeburn  10091:             }
1.275     raeburn  10092:             if (defined($$types{'active'})) {
1.288     raeburn  10093:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10094:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10095:                     $match = 1;
1.275     raeburn  10096:                 }
                   10097:             }
                   10098:             if (defined($$types{'previous'})) {
1.609     raeburn  10099:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10100:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10101:                     $match = 1;
1.275     raeburn  10102:                 }
                   10103:             }
                   10104:             if (defined($$types{'future'})) {
1.609     raeburn  10105:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10106:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10107:                     $match = 1;
1.275     raeburn  10108:                 }
                   10109:             }
1.609     raeburn  10110:             if ($match) {
                   10111:                 push(@{$seclists{$student}},$section);
                   10112:                 if (ref($userdata) eq 'HASH') {
                   10113:                     $$userdata{$student} = $$classlist{$student};
                   10114:                 }
                   10115:                 if (ref($statushash) eq 'HASH') {
                   10116:                     $statushash->{$student}{'st'}{$section} = $status;
                   10117:                 }
1.288     raeburn  10118:             }
1.275     raeburn  10119:         }
                   10120:     }
1.412     raeburn  10121:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10122:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10123:         my $now = time;
1.609     raeburn  10124:         my %displaystatus = ( previous => 'Expired',
                   10125:                               active   => 'Active',
                   10126:                               future   => 'Future',
                   10127:                             );
1.1075.2.36  raeburn  10128:         my (%nothide,@possdoms);
1.630     raeburn  10129:         if ($hidepriv) {
                   10130:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10131:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10132:                 if ($user !~ /:/) {
                   10133:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10134:                 } else {
                   10135:                     $nothide{$user} = 1;
                   10136:                 }
                   10137:             }
1.1075.2.36  raeburn  10138:             my @possdoms = ($cdom);
                   10139:             if ($coursehash{'checkforpriv'}) {
                   10140:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10141:             }
1.630     raeburn  10142:         }
1.439     raeburn  10143:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10144:             my $match = 0;
1.412     raeburn  10145:             my $secmatch = 0;
1.439     raeburn  10146:             my $status;
1.412     raeburn  10147:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10148:             $user =~ s/:$//;
1.439     raeburn  10149:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10150:             if ($end == -1 || $start == -1) {
                   10151:                 next;
                   10152:             }
                   10153:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10154:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10155:                 my ($uname,$udom) = split(/:/,$user);
                   10156:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10157:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10158:                         $secmatch = 1;
                   10159:                     } elsif ($usec eq '') {
1.420     albertel 10160:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10161:                             $secmatch = 1;
                   10162:                         }
                   10163:                     } else {
                   10164:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10165:                             $secmatch = 1;
                   10166:                         }
                   10167:                     }
                   10168:                     if (!$secmatch) {
                   10169:                         next;
                   10170:                     }
1.288     raeburn  10171:                 }
1.419     raeburn  10172:                 if ($usec eq '') {
                   10173:                     $usec = 'none';
                   10174:                 }
1.275     raeburn  10175:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10176:                     if ($hidepriv) {
1.1075.2.36  raeburn  10177:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10178:                             (!$nothide{$uname.':'.$udom})) {
                   10179:                             next;
                   10180:                         }
                   10181:                     }
1.503     raeburn  10182:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10183:                         $status = 'previous';
                   10184:                     } elsif ($start > $now) {
                   10185:                         $status = 'future';
                   10186:                     } else {
                   10187:                         $status = 'active';
                   10188:                     }
1.277     albertel 10189:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10190:                         if ($status eq $type) {
1.420     albertel 10191:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10192:                                 push(@{$$users{$role}{$user}},$type);
                   10193:                             }
1.288     raeburn  10194:                             $match = 1;
                   10195:                         }
                   10196:                     }
1.419     raeburn  10197:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10198:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10199: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10200:                         }
1.420     albertel 10201:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10202:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10203:                         }
1.609     raeburn  10204:                         if (ref($statushash) eq 'HASH') {
                   10205:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10206:                         }
1.275     raeburn  10207:                     }
                   10208:                 }
                   10209:             }
                   10210:         }
1.290     albertel 10211:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10212:             if ((defined($cdom)) && (defined($cnum))) {
                   10213:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10214:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10215:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10216:                     next if ($owner eq '');
                   10217:                     my ($ownername,$ownerdom);
                   10218:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10219:                         $ownername = $1;
                   10220:                         $ownerdom = $2;
                   10221:                     } else {
                   10222:                         $ownername = $owner;
                   10223:                         $ownerdom = $cdom;
                   10224:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10225:                     }
                   10226:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10227:                     if (defined($userdata) && 
1.609     raeburn  10228: 			!exists($$userdata{$owner})) {
                   10229: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10230:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10231:                             push(@{$seclists{$owner}},'none');
                   10232:                         }
                   10233:                         if (ref($statushash) eq 'HASH') {
                   10234:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10235:                         }
1.290     albertel 10236: 		    }
1.279     raeburn  10237:                 }
                   10238:             }
                   10239:         }
1.419     raeburn  10240:         foreach my $user (keys(%seclists)) {
                   10241:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10242:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10243:         }
1.275     raeburn  10244:     }
                   10245:     return;
                   10246: }
                   10247: 
1.288     raeburn  10248: sub get_user_info {
                   10249:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10250:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10251: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10252:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10253:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10254:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10255:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10256:     return;
                   10257: }
1.275     raeburn  10258: 
1.472     raeburn  10259: ###############################################
                   10260: 
                   10261: =pod
                   10262: 
                   10263: =item * &get_user_quota()
                   10264: 
1.1075.2.41  raeburn  10265: Retrieves quota assigned for storage of user files.
                   10266: Default is to report quota for portfolio files.
1.472     raeburn  10267: 
                   10268: Incoming parameters:
                   10269: 1. user's username
                   10270: 2. user's domain
1.1075.2.41  raeburn  10271: 3. quota name - portfolio, author, or course
                   10272:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10273: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10274:    course
1.472     raeburn  10275: 
                   10276: Returns:
1.1075.2.58  raeburn  10277: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10278: 2. (Optional) Type of setting: custom or default
                   10279:    (individually assigned or default for user's 
                   10280:    institutional status).
                   10281: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10282:    or student - types as defined in localenroll::inst_usertypes 
                   10283:    for user's domain, which determines default quota for user.
                   10284: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10285: 
                   10286: If a value has been stored in the user's environment, 
1.536     raeburn  10287: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10288: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10289: 
                   10290: =cut
                   10291: 
                   10292: ###############################################
                   10293: 
                   10294: 
                   10295: sub get_user_quota {
1.1075.2.42  raeburn  10296:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10297:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10298:     if (!defined($udom)) {
                   10299:         $udom = $env{'user.domain'};
                   10300:     }
                   10301:     if (!defined($uname)) {
                   10302:         $uname = $env{'user.name'};
                   10303:     }
                   10304:     if (($udom eq '' || $uname eq '') ||
                   10305:         ($udom eq 'public') && ($uname eq 'public')) {
                   10306:         $quota = 0;
1.536     raeburn  10307:         $quotatype = 'default';
                   10308:         $defquota = 0; 
1.472     raeburn  10309:     } else {
1.536     raeburn  10310:         my $inststatus;
1.1075.2.41  raeburn  10311:         if ($quotaname eq 'course') {
                   10312:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10313:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10314:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10315:             } else {
                   10316:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10317:                 $quota = $cenv{'internal.uploadquota'};
                   10318:             }
1.536     raeburn  10319:         } else {
1.1075.2.41  raeburn  10320:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10321:                 if ($quotaname eq 'author') {
                   10322:                     $quota = $env{'environment.authorquota'};
                   10323:                 } else {
                   10324:                     $quota = $env{'environment.portfolioquota'};
                   10325:                 }
                   10326:                 $inststatus = $env{'environment.inststatus'};
                   10327:             } else {
                   10328:                 my %userenv = 
                   10329:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10330:                                          'authorquota','inststatus'],$udom,$uname);
                   10331:                 my ($tmp) = keys(%userenv);
                   10332:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10333:                     if ($quotaname eq 'author') {
                   10334:                         $quota = $userenv{'authorquota'};
                   10335:                     } else {
                   10336:                         $quota = $userenv{'portfolioquota'};
                   10337:                     }
                   10338:                     $inststatus = $userenv{'inststatus'};
                   10339:                 } else {
                   10340:                     undef(%userenv);
                   10341:                 }
                   10342:             }
                   10343:         }
                   10344:         if ($quota eq '' || wantarray) {
                   10345:             if ($quotaname eq 'course') {
                   10346:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10347:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10348:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10349:                     $defquota = $domdefs{$crstype.'quota'};
                   10350:                 }
                   10351:                 if ($defquota eq '') {
                   10352:                     $defquota = 500;
                   10353:                 }
1.1075.2.41  raeburn  10354:             } else {
                   10355:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10356:             }
                   10357:             if ($quota eq '') {
                   10358:                 $quota = $defquota;
                   10359:                 $quotatype = 'default';
                   10360:             } else {
                   10361:                 $quotatype = 'custom';
                   10362:             }
1.472     raeburn  10363:         }
                   10364:     }
1.536     raeburn  10365:     if (wantarray) {
                   10366:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10367:     } else {
                   10368:         return $quota;
                   10369:     }
1.472     raeburn  10370: }
                   10371: 
                   10372: ###############################################
                   10373: 
                   10374: =pod
                   10375: 
                   10376: =item * &default_quota()
                   10377: 
1.536     raeburn  10378: Retrieves default quota assigned for storage of user portfolio files,
                   10379: given an (optional) user's institutional status.
1.472     raeburn  10380: 
                   10381: Incoming parameters:
1.1075.2.42  raeburn  10382: 
1.472     raeburn  10383: 1. domain
1.536     raeburn  10384: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10385:    status types (e.g., faculty, staff, student etc.)
                   10386:    which apply to the user for whom the default is being retrieved.
                   10387:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10388:    default quota will be returned.
                   10389: 3.  quota name - portfolio, author, or course
                   10390:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10391: 
                   10392: Returns:
1.1075.2.42  raeburn  10393: 
1.1075.2.58  raeburn  10394: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10395: 2. (Optional) institutional type which determined the value of the
                   10396:    default quota.
1.472     raeburn  10397: 
                   10398: If a value has been stored in the domain's configuration db,
                   10399: it will return that, otherwise it returns 20 (for backwards 
                   10400: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10401: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10402: 
1.536     raeburn  10403: If the user's status includes multiple types (e.g., staff and student),
                   10404: the largest default quota which applies to the user determines the
                   10405: default quota returned.
                   10406: 
1.472     raeburn  10407: =cut
                   10408: 
                   10409: ###############################################
                   10410: 
                   10411: 
                   10412: sub default_quota {
1.1075.2.41  raeburn  10413:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10414:     my ($defquota,$settingstatus);
                   10415:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10416:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10417:     my $key = 'defaultquota';
                   10418:     if ($quotaname eq 'author') {
                   10419:         $key = 'authorquota';
                   10420:     }
1.622     raeburn  10421:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10422:         if ($inststatus ne '') {
1.765     raeburn  10423:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10424:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10425:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10426:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10427:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10428:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10429:                             $settingstatus = $item;
1.1075.2.41  raeburn  10430:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10431:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10432:                             $settingstatus = $item;
                   10433:                         }
                   10434:                     }
1.1075.2.41  raeburn  10435:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10436:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10437:                         if ($defquota eq '') {
                   10438:                             $defquota = $quotahash{'quotas'}{$item};
                   10439:                             $settingstatus = $item;
                   10440:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10441:                             $defquota = $quotahash{'quotas'}{$item};
                   10442:                             $settingstatus = $item;
                   10443:                         }
1.536     raeburn  10444:                     }
                   10445:                 }
                   10446:             }
                   10447:         }
                   10448:         if ($defquota eq '') {
1.1075.2.41  raeburn  10449:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10450:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10451:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10452:                 $defquota = $quotahash{'quotas'}{'default'};
                   10453:             }
1.536     raeburn  10454:             $settingstatus = 'default';
1.1075.2.42  raeburn  10455:             if ($defquota eq '') {
                   10456:                 if ($quotaname eq 'author') {
                   10457:                     $defquota = 500;
                   10458:                 }
                   10459:             }
1.536     raeburn  10460:         }
                   10461:     } else {
                   10462:         $settingstatus = 'default';
1.1075.2.41  raeburn  10463:         if ($quotaname eq 'author') {
                   10464:             $defquota = 500;
                   10465:         } else {
                   10466:             $defquota = 20;
                   10467:         }
1.536     raeburn  10468:     }
                   10469:     if (wantarray) {
                   10470:         return ($defquota,$settingstatus);
1.472     raeburn  10471:     } else {
1.536     raeburn  10472:         return $defquota;
1.472     raeburn  10473:     }
                   10474: }
                   10475: 
1.1075.2.41  raeburn  10476: ###############################################
                   10477: 
                   10478: =pod
                   10479: 
1.1075.2.42  raeburn  10480: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  10481: 
                   10482: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  10483: of existing file within authoring space will cause quota for the authoring
                   10484: space to be exceeded.
                   10485: 
                   10486: Same, if upload of a file directly to a course/community via Course Editor
                   10487: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  10488: 
1.1075.2.61  raeburn  10489: Inputs: 7 
1.1075.2.42  raeburn  10490: 1. username or coursenum
1.1075.2.41  raeburn  10491: 2. domain
1.1075.2.42  raeburn  10492: 3. context ('author' or 'course')
1.1075.2.41  raeburn  10493: 4. filename of file for which action is being requested
                   10494: 5. filesize (kB) of file
                   10495: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  10496: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  10497: 
                   10498: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   10499:          otherwise return null.
                   10500: 
1.1075.2.42  raeburn  10501: =back
                   10502: 
1.1075.2.41  raeburn  10503: =cut
                   10504: 
1.1075.2.42  raeburn  10505: sub excess_filesize_warning {
1.1075.2.59  raeburn  10506:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  10507:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  10508:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  10509:     if ($context eq 'author') {
                   10510:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10511:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10512:     } else {
                   10513:         foreach my $subdir ('docs','supplemental') {
                   10514:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10515:         }
                   10516:     }
1.1075.2.41  raeburn  10517:     $disk_quota = int($disk_quota * 1000);
                   10518:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  10519:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  10520:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  10521:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10522:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  10523:                             $disk_quota,$current_disk_usage).
                   10524:                '</p>';
                   10525:     }
                   10526:     return;
                   10527: }
                   10528: 
                   10529: ###############################################
                   10530: 
                   10531: 
1.384     raeburn  10532: sub get_secgrprole_info {
                   10533:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10534:     my %sections_count = &get_sections($cdom,$cnum);
                   10535:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10536:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10537:     my @groups = sort(keys(%curr_groups));
                   10538:     my $allroles = [];
                   10539:     my $rolehash;
                   10540:     my $accesshash = {
                   10541:                      active => 'Currently has access',
                   10542:                      future => 'Will have future access',
                   10543:                      previous => 'Previously had access',
                   10544:                   };
                   10545:     if ($needroles) {
                   10546:         $rolehash = {'all' => 'all'};
1.385     albertel 10547:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10548: 	if (&Apache::lonnet::error(%user_roles)) {
                   10549: 	    undef(%user_roles);
                   10550: 	}
                   10551:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10552:             my ($role)=split(/\:/,$item,2);
                   10553:             if ($role eq 'cr') { next; }
                   10554:             if ($role =~ /^cr/) {
                   10555:                 $$rolehash{$role} = (split('/',$role))[3];
                   10556:             } else {
                   10557:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10558:             }
                   10559:         }
                   10560:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10561:             push(@{$allroles},$key);
                   10562:         }
                   10563:         push (@{$allroles},'st');
                   10564:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10565:     }
                   10566:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10567: }
                   10568: 
1.555     raeburn  10569: sub user_picker {
1.1075.2.127  raeburn  10570:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10571:     my $currdom = $dom;
1.1075.2.114  raeburn  10572:     my @alldoms = &Apache::lonnet::all_domains();
                   10573:     if (@alldoms == 1) {
                   10574:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10575:                                                ['directorysrch'],$alldoms[0]);
                   10576:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10577:         my $showdom = $domdesc;
                   10578:         if ($showdom eq '') {
                   10579:             $showdom = $dom;
                   10580:         }
                   10581:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10582:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10583:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10584:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10585:             }
                   10586:         }
                   10587:     }
1.555     raeburn  10588:     my %curr_selected = (
                   10589:                         srchin => 'dom',
1.580     raeburn  10590:                         srchby => 'lastname',
1.555     raeburn  10591:                       );
                   10592:     my $srchterm;
1.625     raeburn  10593:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10594:         if ($srch->{'srchby'} ne '') {
                   10595:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10596:         }
                   10597:         if ($srch->{'srchin'} ne '') {
                   10598:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10599:         }
                   10600:         if ($srch->{'srchtype'} ne '') {
                   10601:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10602:         }
                   10603:         if ($srch->{'srchdomain'} ne '') {
                   10604:             $currdom = $srch->{'srchdomain'};
                   10605:         }
                   10606:         $srchterm = $srch->{'srchterm'};
                   10607:     }
1.1075.2.98  raeburn  10608:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10609:                     'usr'       => 'Search criteria',
1.563     raeburn  10610:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10611:                     'uname'     => 'username',
                   10612:                     'lastname'  => 'last name',
1.555     raeburn  10613:                     'lastfirst' => 'last name, first name',
1.558     albertel 10614:                     'crs'       => 'in this course',
1.576     raeburn  10615:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10616:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10617:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10618:                     'exact'     => 'is',
                   10619:                     'contains'  => 'contains',
1.569     raeburn  10620:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  10621:                                        );
                   10622:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10623:                     'youm'      => "You must include some text to search for.",
                   10624:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10625:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10626:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10627:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10628:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10629:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10630:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10631:                                        );
1.1075.2.98  raeburn  10632:     &html_escape(\%html_lt);
                   10633:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  10634:     my $domform;
1.1075.2.126  raeburn  10635:     my $allow_blank = 1;
1.1075.2.115  raeburn  10636:     if ($fixeddom) {
1.1075.2.126  raeburn  10637:         $allow_blank = 0;
                   10638:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  10639:     } else {
1.1075.2.126  raeburn  10640:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  10641:     }
1.563     raeburn  10642:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10643: 
                   10644:     my @srchins = ('crs','dom','alc','instd');
                   10645: 
                   10646:     foreach my $option (@srchins) {
                   10647:         # FIXME 'alc' option unavailable until 
                   10648:         #       loncreateuser::print_user_query_page()
                   10649:         #       has been completed.
                   10650:         next if ($option eq 'alc');
1.880     raeburn  10651:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10652:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  10653:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10654:         if ($curr_selected{'srchin'} eq $option) {
                   10655:             $srchinsel .= ' 
1.1075.2.98  raeburn  10656:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10657:         } else {
                   10658:             $srchinsel .= '
1.1075.2.98  raeburn  10659:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10660:         }
1.555     raeburn  10661:     }
1.563     raeburn  10662:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10663: 
                   10664:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10665:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10666:         if ($curr_selected{'srchby'} eq $option) {
                   10667:             $srchbysel .= '
1.1075.2.98  raeburn  10668:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10669:         } else {
                   10670:             $srchbysel .= '
1.1075.2.98  raeburn  10671:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10672:          }
                   10673:     }
                   10674:     $srchbysel .= "\n  </select>\n";
                   10675: 
                   10676:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10677:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10678:         if ($curr_selected{'srchtype'} eq $option) {
                   10679:             $srchtypesel .= '
1.1075.2.98  raeburn  10680:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10681:         } else {
                   10682:             $srchtypesel .= '
1.1075.2.98  raeburn  10683:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10684:         }
                   10685:     }
                   10686:     $srchtypesel .= "\n  </select>\n";
                   10687: 
1.558     albertel 10688:     my ($newuserscript,$new_user_create);
1.994     raeburn  10689:     my $context_dom = $env{'request.role.domain'};
                   10690:     if ($context eq 'requestcrs') {
                   10691:         if ($env{'form.coursedom'} ne '') { 
                   10692:             $context_dom = $env{'form.coursedom'};
                   10693:         }
                   10694:     }
1.556     raeburn  10695:     if ($forcenewuser) {
1.576     raeburn  10696:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10697:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10698:                 if ($cancreate) {
                   10699:                     $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>';
                   10700:                 } else {
1.799     bisitz   10701:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10702:                     my %usertypetext = (
                   10703:                         official   => 'institutional',
                   10704:                         unofficial => 'non-institutional',
                   10705:                     );
1.799     bisitz   10706:                     $new_user_create = '<p class="LC_warning">'
                   10707:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10708:                                       .' '
                   10709:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10710:                                           ,'<a href="'.$helplink.'">','</a>')
                   10711:                                       .'</p><br />';
1.627     raeburn  10712:                 }
1.576     raeburn  10713:             }
                   10714:         }
                   10715: 
1.556     raeburn  10716:         $newuserscript = <<"ENDSCRIPT";
                   10717: 
1.570     raeburn  10718: function setSearch(createnew,callingForm) {
1.556     raeburn  10719:     if (createnew == 1) {
1.570     raeburn  10720:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10721:             if (callingForm.srchby.options[i].value == 'uname') {
                   10722:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10723:             }
                   10724:         }
1.570     raeburn  10725:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10726:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10727: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10728:             }
                   10729:         }
1.570     raeburn  10730:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10731:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10732:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10733:             }
                   10734:         }
1.570     raeburn  10735:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10736:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10737:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10738:             }
                   10739:         }
                   10740:     }
                   10741: }
                   10742: ENDSCRIPT
1.558     albertel 10743: 
1.556     raeburn  10744:     }
                   10745: 
1.555     raeburn  10746:     my $output = <<"END_BLOCK";
1.556     raeburn  10747: <script type="text/javascript">
1.824     bisitz   10748: // <![CDATA[
1.570     raeburn  10749: function validateEntry(callingForm) {
1.558     albertel 10750: 
1.556     raeburn  10751:     var checkok = 1;
1.558     albertel 10752:     var srchin;
1.570     raeburn  10753:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10754: 	if ( callingForm.srchin[i].checked ) {
                   10755: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10756: 	}
                   10757:     }
                   10758: 
1.570     raeburn  10759:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10760:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10761:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10762:     var srchterm =  callingForm.srchterm.value;
                   10763:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10764:     var msg = "";
                   10765: 
                   10766:     if (srchterm == "") {
                   10767:         checkok = 0;
1.1075.2.98  raeburn  10768:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10769:     }
                   10770: 
1.569     raeburn  10771:     if (srchtype== 'begins') {
                   10772:         if (srchterm.length < 2) {
                   10773:             checkok = 0;
1.1075.2.98  raeburn  10774:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10775:         }
                   10776:     }
                   10777: 
1.556     raeburn  10778:     if (srchtype== 'contains') {
                   10779:         if (srchterm.length < 3) {
                   10780:             checkok = 0;
1.1075.2.98  raeburn  10781:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10782:         }
                   10783:     }
                   10784:     if (srchin == 'instd') {
                   10785:         if (srchdomain == '') {
                   10786:             checkok = 0;
1.1075.2.98  raeburn  10787:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10788:         }
                   10789:     }
                   10790:     if (srchin == 'dom') {
                   10791:         if (srchdomain == '') {
                   10792:             checkok = 0;
1.1075.2.98  raeburn  10793:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10794:         }
                   10795:     }
                   10796:     if (srchby == 'lastfirst') {
                   10797:         if (srchterm.indexOf(",") == -1) {
                   10798:             checkok = 0;
1.1075.2.98  raeburn  10799:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10800:         }
                   10801:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10802:             checkok = 0;
1.1075.2.98  raeburn  10803:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10804:         }
                   10805:     }
                   10806:     if (checkok == 0) {
1.1075.2.98  raeburn  10807:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10808:         return;
                   10809:     }
                   10810:     if (checkok == 1) {
1.570     raeburn  10811:         callingForm.submit();
1.556     raeburn  10812:     }
                   10813: }
                   10814: 
                   10815: $newuserscript
                   10816: 
1.824     bisitz   10817: // ]]>
1.556     raeburn  10818: </script>
1.558     albertel 10819: 
                   10820: $new_user_create
                   10821: 
1.555     raeburn  10822: END_BLOCK
1.558     albertel 10823: 
1.876     raeburn  10824:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10825:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10826:                $domform.
                   10827:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10828:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10829:                $srchbysel.
                   10830:                $srchtypesel. 
                   10831:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10832:                $srchinsel.
                   10833:                &Apache::lonhtmlcommon::row_closure(1). 
                   10834:                &Apache::lonhtmlcommon::end_pick_box().
                   10835:                '<br />';
1.1075.2.114  raeburn  10836:     return ($output,1);
1.555     raeburn  10837: }
                   10838: 
1.612     raeburn  10839: sub user_rule_check {
1.615     raeburn  10840:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10841:     my ($response,%inst_response);
1.612     raeburn  10842:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10843:         if (keys(%{$usershash}) > 1) {
                   10844:             my (%by_username,%by_id,%userdoms);
                   10845:             my $checkid;
1.612     raeburn  10846:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10847:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10848:                     $checkid = 1;
                   10849:                 }
                   10850:             }
                   10851:             foreach my $user (keys(%{$usershash})) {
                   10852:                 my ($uname,$udom) = split(/:/,$user);
                   10853:                 if ($checkid) {
                   10854:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10855:                         if ($usershash->{$user}->{'id'} ne '') {
                   10856:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10857:                             $userdoms{$udom} = 1;
                   10858:                             if (ref($inst_results) eq 'HASH') {
                   10859:                                 $inst_results->{$uname.':'.$udom} = {};
                   10860:                             }
                   10861:                         }
                   10862:                     }
                   10863:                 } else {
                   10864:                     $by_username{$udom}{$uname} = 1;
                   10865:                     $userdoms{$udom} = 1;
                   10866:                     if (ref($inst_results) eq 'HASH') {
                   10867:                         $inst_results->{$uname.':'.$udom} = {};
                   10868:                     }
                   10869:                 }
                   10870:             }
                   10871:             foreach my $udom (keys(%userdoms)) {
                   10872:                 if (!$got_rules->{$udom}) {
                   10873:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10874:                                                              ['usercreation'],$udom);
                   10875:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10876:                         foreach my $item ('username','id') {
                   10877:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10878:                                 $$curr_rules{$udom}{$item} =
                   10879:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10880:                             }
                   10881:                         }
                   10882:                     }
                   10883:                     $got_rules->{$udom} = 1;
                   10884:                 }
                   10885:             }
                   10886:             if ($checkid) {
                   10887:                 foreach my $udom (keys(%by_id)) {
                   10888:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10889:                     if ($outcome eq 'ok') {
                   10890:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10891:                             my $uname = $by_id{$udom}{$id};
                   10892:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10893:                         }
                   10894:                         if (ref($results) eq 'HASH') {
                   10895:                             foreach my $uname (keys(%{$results})) {
                   10896:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10897:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10898:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10899:                                 }
                   10900:                             }
                   10901:                         }
                   10902:                     }
1.612     raeburn  10903:                 }
1.615     raeburn  10904:             } else {
1.1075.2.99  raeburn  10905:                 foreach my $udom (keys(%by_username)) {
                   10906:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10907:                     if ($outcome eq 'ok') {
                   10908:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10909:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10910:                         }
                   10911:                         if (ref($results) eq 'HASH') {
                   10912:                             foreach my $uname (keys(%{$results})) {
                   10913:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10914:                             }
                   10915:                         }
                   10916:                     }
                   10917:                 }
1.612     raeburn  10918:             }
1.1075.2.99  raeburn  10919:         } elsif (keys(%{$usershash}) == 1) {
                   10920:             my $user = (keys(%{$usershash}))[0];
                   10921:             my ($uname,$udom) = split(/:/,$user);
                   10922:             if (($udom ne '') && ($uname ne '')) {
                   10923:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10924:                     if (ref($checks) eq 'HASH') {
                   10925:                         if (defined($checks->{'username'})) {
                   10926:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10927:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10928:                         } elsif (defined($checks->{'id'})) {
                   10929:                             if ($usershash->{$user}->{'id'} ne '') {
                   10930:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10931:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10932:                                                                   $usershash->{$user}->{'id'});
                   10933:                             } else {
                   10934:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10935:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10936:                             }
                   10937:                         }
                   10938:                     } else {
                   10939:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10940:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10941:                        return;
                   10942:                     }
                   10943:                     if (!$got_rules->{$udom}) {
                   10944:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10945:                                                                  ['usercreation'],$udom);
                   10946:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10947:                             foreach my $item ('username','id') {
                   10948:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10949:                                    $$curr_rules{$udom}{$item} =
                   10950:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10951:                                 }
                   10952:                             }
1.585     raeburn  10953:                         }
1.1075.2.99  raeburn  10954:                         $got_rules->{$udom} = 1;
1.585     raeburn  10955:                     }
                   10956:                 }
1.1075.2.99  raeburn  10957:             } else {
                   10958:                 return;
                   10959:             }
                   10960:         } else {
                   10961:             return;
                   10962:         }
                   10963:         foreach my $user (keys(%{$usershash})) {
                   10964:             my ($uname,$udom) = split(/:/,$user);
                   10965:             next if (($udom eq '') || ($uname eq ''));
                   10966:             my $id;
                   10967:             if (ref($inst_results) eq 'HASH') {
                   10968:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10969:                     $id = $inst_results->{$user}->{'id'};
                   10970:                 }
                   10971:             }
                   10972:             if ($id eq '') {
                   10973:                 if (ref($usershash->{$user})) {
                   10974:                     $id = $usershash->{$user}->{'id'};
                   10975:                 }
1.585     raeburn  10976:             }
1.612     raeburn  10977:             foreach my $item (keys(%{$checks})) {
                   10978:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10979:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10980:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10981:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10982:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10983:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10984:                                 if ($rule_check{$rule}) {
                   10985:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10986:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10987:                                         if (ref($inst_results) eq 'HASH') {
                   10988:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10989:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10990:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10991:                                                 } elsif ($item eq 'id') {
                   10992:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10993:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10994:                                                     }
1.615     raeburn  10995:                                                 }
1.612     raeburn  10996:                                             }
                   10997:                                         }
1.615     raeburn  10998:                                     }
                   10999:                                     last;
1.585     raeburn  11000:                                 }
                   11001:                             }
                   11002:                         }
                   11003:                     }
                   11004:                 }
                   11005:             }
                   11006:         }
                   11007:     }
1.612     raeburn  11008:     return;
                   11009: }
                   11010: 
                   11011: sub user_rule_formats {
                   11012:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11013:     my %text = ( 
                   11014:                  'username' => 'Usernames',
                   11015:                  'id'       => 'IDs',
                   11016:                );
                   11017:     my $output;
                   11018:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11019:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11020:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11021:             $output = '<br />'.
                   11022:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11023:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11024:                       ' <ul>';
1.612     raeburn  11025:             foreach my $rule (@{$ruleorder}) {
                   11026:                 if (ref($curr_rules) eq 'ARRAY') {
                   11027:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11028:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11029:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11030:                                         $rules->{$rule}{'desc'}.'</li>';
                   11031:                         }
                   11032:                     }
                   11033:                 }
                   11034:             }
                   11035:             $output .= '</ul>';
                   11036:         }
                   11037:     }
                   11038:     return $output;
                   11039: }
                   11040: 
                   11041: sub instrule_disallow_msg {
1.615     raeburn  11042:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11043:     my $response;
                   11044:     my %text = (
                   11045:                   item   => 'username',
                   11046:                   items  => 'usernames',
                   11047:                   match  => 'matches',
                   11048:                   do     => 'does',
                   11049:                   action => 'a username',
                   11050:                   one    => 'one',
                   11051:                );
                   11052:     if ($count > 1) {
                   11053:         $text{'item'} = 'usernames';
                   11054:         $text{'match'} ='match';
                   11055:         $text{'do'} = 'do';
                   11056:         $text{'action'} = 'usernames',
                   11057:         $text{'one'} = 'ones';
                   11058:     }
                   11059:     if ($checkitem eq 'id') {
                   11060:         $text{'items'} = 'IDs';
                   11061:         $text{'item'} = 'ID';
                   11062:         $text{'action'} = 'an ID';
1.615     raeburn  11063:         if ($count > 1) {
                   11064:             $text{'item'} = 'IDs';
                   11065:             $text{'action'} = 'IDs';
                   11066:         }
1.612     raeburn  11067:     }
1.674     bisitz   11068:     $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  11069:     if ($mode eq 'upload') {
                   11070:         if ($checkitem eq 'username') {
                   11071:             $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'}.");
                   11072:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11073:             $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  11074:         }
1.669     raeburn  11075:     } elsif ($mode eq 'selfcreate') {
                   11076:         if ($checkitem eq 'id') {
                   11077:             $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.");
                   11078:         }
1.615     raeburn  11079:     } else {
                   11080:         if ($checkitem eq 'username') {
                   11081:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11082:         } elsif ($checkitem eq 'id') {
                   11083:             $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.");
                   11084:         }
1.612     raeburn  11085:     }
                   11086:     return $response;
1.585     raeburn  11087: }
                   11088: 
1.624     raeburn  11089: sub personal_data_fieldtitles {
                   11090:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11091:                         id => 'Student/Employee ID',
                   11092:                         permanentemail => 'E-mail address',
                   11093:                         lastname => 'Last Name',
                   11094:                         firstname => 'First Name',
                   11095:                         middlename => 'Middle Name',
                   11096:                         generation => 'Generation',
                   11097:                         gen => 'Generation',
1.765     raeburn  11098:                         inststatus => 'Affiliation',
1.624     raeburn  11099:                    );
                   11100:     return %fieldtitles;
                   11101: }
                   11102: 
1.642     raeburn  11103: sub sorted_inst_types {
                   11104:     my ($dom) = @_;
1.1075.2.70  raeburn  11105:     my ($usertypes,$order);
                   11106:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11107:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11108:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11109:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11110:     } else {
                   11111:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11112:     }
1.642     raeburn  11113:     my $othertitle = &mt('All users');
                   11114:     if ($env{'request.course.id'}) {
1.668     raeburn  11115:         $othertitle  = &mt('Any users');
1.642     raeburn  11116:     }
                   11117:     my @types;
                   11118:     if (ref($order) eq 'ARRAY') {
                   11119:         @types = @{$order};
                   11120:     }
                   11121:     if (@types == 0) {
                   11122:         if (ref($usertypes) eq 'HASH') {
                   11123:             @types = sort(keys(%{$usertypes}));
                   11124:         }
                   11125:     }
                   11126:     if (keys(%{$usertypes}) > 0) {
                   11127:         $othertitle = &mt('Other users');
                   11128:     }
                   11129:     return ($othertitle,$usertypes,\@types);
                   11130: }
                   11131: 
1.645     raeburn  11132: sub get_institutional_codes {
1.1075.2.157  raeburn  11133:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11134: # Get complete list of course sections to update
                   11135:     my @currsections = ();
                   11136:     my @currxlists = ();
1.1075.2.157  raeburn  11137:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11138:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11139:     my $crskey = $crs.':'.$coursecode;
                   11140:     @{$unclutteredsec{$crskey}} = ();
                   11141:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11142: 
                   11143:     if ($$settings{'internal.sectionnums'} ne '') {
                   11144:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11145:     }
                   11146: 
                   11147:     if ($$settings{'internal.crosslistings'} ne '') {
                   11148:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11149:     }
                   11150: 
                   11151:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11152:         foreach my $xl (@currxlists) {
                   11153:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11154:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11155:                     push(@{$allcourses},$1);
1.645     raeburn  11156:                     $$LC_code{$1} = $2;
                   11157:                 }
                   11158:             }
                   11159:         }
                   11160:     }
1.1075.2.157  raeburn  11161: 
1.645     raeburn  11162:     if (@currsections > 0) {
1.1075.2.157  raeburn  11163:         foreach my $sec (@currsections) {
                   11164:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11165:                 my $instsec = $1;
1.645     raeburn  11166:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11167:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11168:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11169:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11170:                 }
                   11171:             }
                   11172:         }
                   11173:     }
                   11174: 
                   11175:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11176:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11177:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11178:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11179:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11180:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11181:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11182:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11183:                 }
                   11184:             }
                   11185:         }
                   11186:     }
                   11187:     return;
                   11188: }
                   11189: 
1.971     raeburn  11190: sub get_standard_codeitems {
                   11191:     return ('Year','Semester','Department','Number','Section');
                   11192: }
                   11193: 
1.112     bowersj2 11194: =pod
                   11195: 
1.780     raeburn  11196: =head1 Slot Helpers
                   11197: 
                   11198: =over 4
                   11199: 
                   11200: =item * sorted_slots()
                   11201: 
1.1040    raeburn  11202: Sorts an array of slot names in order of an optional sort key,
                   11203: default sort is by slot start time (earliest first). 
1.780     raeburn  11204: 
                   11205: Inputs:
                   11206: 
                   11207: =over 4
                   11208: 
                   11209: slotsarr  - Reference to array of unsorted slot names.
                   11210: 
                   11211: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11212: 
1.1040    raeburn  11213: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11214: 
1.549     albertel 11215: =back
                   11216: 
1.780     raeburn  11217: Returns:
                   11218: 
                   11219: =over 4
                   11220: 
1.1040    raeburn  11221: sorted   - An array of slot names sorted by a specified sort key 
                   11222:            (default sort key is start time of the slot).
1.780     raeburn  11223: 
                   11224: =back
                   11225: 
                   11226: =cut
                   11227: 
                   11228: 
                   11229: sub sorted_slots {
1.1040    raeburn  11230:     my ($slotsarr,$slots,$sortkey) = @_;
                   11231:     if ($sortkey eq '') {
                   11232:         $sortkey = 'starttime';
                   11233:     }
1.780     raeburn  11234:     my @sorted;
                   11235:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11236:         @sorted =
                   11237:             sort {
                   11238:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11239:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11240:                      }
                   11241:                      if (ref($slots->{$a})) { return -1;}
                   11242:                      if (ref($slots->{$b})) { return 1;}
                   11243:                      return 0;
                   11244:                  } @{$slotsarr};
                   11245:     }
                   11246:     return @sorted;
                   11247: }
                   11248: 
1.1040    raeburn  11249: =pod
                   11250: 
                   11251: =item * get_future_slots()
                   11252: 
                   11253: Inputs:
                   11254: 
                   11255: =over 4
                   11256: 
                   11257: cnum - course number
                   11258: 
                   11259: cdom - course domain
                   11260: 
                   11261: now - current UNIX time
                   11262: 
                   11263: symb - optional symb
                   11264: 
                   11265: =back
                   11266: 
                   11267: Returns:
                   11268: 
                   11269: =over 4
                   11270: 
                   11271: sorted_reservable - ref to array of student_schedulable slots currently 
                   11272:                     reservable, ordered by end date of reservation period.
                   11273: 
                   11274: reservable_now - ref to hash of student_schedulable slots currently
                   11275:                  reservable.
                   11276: 
                   11277:     Keys in inner hash are:
                   11278:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11279:     (b) endreserve: end date of reservation period.
                   11280:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11281:         selected.
1.1040    raeburn  11282: 
                   11283: sorted_future - ref to array of student_schedulable slots reservable in
                   11284:                 the future, ordered by start date of reservation period.
                   11285: 
                   11286: future_reservable - ref to hash of student_schedulable slots reservable
                   11287:                     in the future.
                   11288: 
                   11289:     Keys in inner hash are:
                   11290:     (a) symb: either blank or symb to which slot use is restricted.
                   11291:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11292:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11293:         selected.
1.1040    raeburn  11294: 
                   11295: =back
                   11296: 
                   11297: =cut
                   11298: 
                   11299: sub get_future_slots {
                   11300:     my ($cnum,$cdom,$now,$symb) = @_;
                   11301:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11302:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11303:     foreach my $slot (keys(%slots)) {
                   11304:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11305:         if ($symb) {
                   11306:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11307:                      ($slots{$slot}->{'symb'} ne $symb));
                   11308:         }
                   11309:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11310:             ($slots{$slot}->{'endtime'} > $now)) {
                   11311:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11312:                 my $userallowed = 0;
                   11313:                 if ($slots{$slot}->{'allowedsections'}) {
                   11314:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11315:                     if (!defined($env{'request.role.sec'})
                   11316:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11317:                         $userallowed=1;
                   11318:                     } else {
                   11319:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11320:                             $userallowed=1;
                   11321:                         }
                   11322:                     }
                   11323:                     unless ($userallowed) {
                   11324:                         if (defined($env{'request.course.groups'})) {
                   11325:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11326:                             foreach my $group (@groups) {
                   11327:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11328:                                     $userallowed=1;
                   11329:                                     last;
                   11330:                                 }
                   11331:                             }
                   11332:                         }
                   11333:                     }
                   11334:                 }
                   11335:                 if ($slots{$slot}->{'allowedusers'}) {
                   11336:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11337:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11338:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11339:                         $userallowed = 1;
                   11340:                     }
                   11341:                 }
                   11342:                 next unless($userallowed);
                   11343:             }
                   11344:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11345:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11346:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11347:             my $uniqueperiod;
                   11348:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11349:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11350:             }
1.1040    raeburn  11351:             if (($startreserve < $now) &&
                   11352:                 (!$endreserve || $endreserve > $now)) {
                   11353:                 my $lastres = $endreserve;
                   11354:                 if (!$lastres) {
                   11355:                     $lastres = $slots{$slot}->{'starttime'};
                   11356:                 }
                   11357:                 $reservable_now{$slot} = {
                   11358:                                            symb       => $symb,
1.1075.2.104  raeburn  11359:                                            endreserve => $lastres,
                   11360:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11361:                                          };
                   11362:             } elsif (($startreserve > $now) &&
                   11363:                      (!$endreserve || $endreserve > $startreserve)) {
                   11364:                 $future_reservable{$slot} = {
                   11365:                                               symb         => $symb,
1.1075.2.104  raeburn  11366:                                               startreserve => $startreserve,
                   11367:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11368:                                             };
                   11369:             }
                   11370:         }
                   11371:     }
                   11372:     my @unsorted_reservable = keys(%reservable_now);
                   11373:     if (@unsorted_reservable > 0) {
                   11374:         @sorted_reservable = 
                   11375:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11376:     }
                   11377:     my @unsorted_future = keys(%future_reservable);
                   11378:     if (@unsorted_future > 0) {
                   11379:         @sorted_future =
                   11380:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11381:     }
                   11382:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11383: }
1.780     raeburn  11384: 
                   11385: =pod
                   11386: 
1.1057    foxr     11387: =back
                   11388: 
1.549     albertel 11389: =head1 HTTP Helpers
                   11390: 
                   11391: =over 4
                   11392: 
1.648     raeburn  11393: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11394: 
1.258     albertel 11395: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11396: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11397: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11398: 
                   11399: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11400: $possible_names is an ref to an array of form element names.  As an example:
                   11401: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11402: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11403: 
                   11404: =cut
1.1       albertel 11405: 
1.6       albertel 11406: sub get_unprocessed_cgi {
1.25      albertel 11407:   my ($query,$possible_names)= @_;
1.26      matthew  11408:   # $Apache::lonxml::debug=1;
1.356     albertel 11409:   foreach my $pair (split(/&/,$query)) {
                   11410:     my ($name, $value) = split(/=/,$pair);
1.369     www      11411:     $name = &unescape($name);
1.25      albertel 11412:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11413:       $value =~ tr/+/ /;
                   11414:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11415:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11416:     }
1.16      harris41 11417:   }
1.6       albertel 11418: }
                   11419: 
1.112     bowersj2 11420: =pod
                   11421: 
1.648     raeburn  11422: =item * &cacheheader() 
1.112     bowersj2 11423: 
                   11424: returns cache-controlling header code
                   11425: 
                   11426: =cut
                   11427: 
1.7       albertel 11428: sub cacheheader {
1.258     albertel 11429:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11430:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11431:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11432:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11433:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11434:     return $output;
1.7       albertel 11435: }
                   11436: 
1.112     bowersj2 11437: =pod
                   11438: 
1.648     raeburn  11439: =item * &no_cache($r) 
1.112     bowersj2 11440: 
                   11441: specifies header code to not have cache
                   11442: 
                   11443: =cut
                   11444: 
1.9       albertel 11445: sub no_cache {
1.216     albertel 11446:     my ($r) = @_;
                   11447:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11448: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11449:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11450:     $r->no_cache(1);
                   11451:     $r->header_out("Expires" => $date);
                   11452:     $r->header_out("Pragma" => "no-cache");
1.123     www      11453: }
                   11454: 
                   11455: sub content_type {
1.181     albertel 11456:     my ($r,$type,$charset) = @_;
1.299     foxr     11457:     if ($r) {
                   11458: 	#  Note that printout.pl calls this with undef for $r.
                   11459: 	&no_cache($r);
                   11460:     }
1.258     albertel 11461:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11462:     unless ($charset) {
                   11463: 	$charset=&Apache::lonlocal::current_encoding;
                   11464:     }
                   11465:     if ($charset) { $type.='; charset='.$charset; }
                   11466:     if ($r) {
                   11467: 	$r->content_type($type);
                   11468:     } else {
                   11469: 	print("Content-type: $type\n\n");
                   11470:     }
1.9       albertel 11471: }
1.25      albertel 11472: 
1.112     bowersj2 11473: =pod
                   11474: 
1.648     raeburn  11475: =item * &add_to_env($name,$value) 
1.112     bowersj2 11476: 
1.258     albertel 11477: adds $name to the %env hash with value
1.112     bowersj2 11478: $value, if $name already exists, the entry is converted to an array
                   11479: reference and $value is added to the array.
                   11480: 
                   11481: =cut
                   11482: 
1.25      albertel 11483: sub add_to_env {
                   11484:   my ($name,$value)=@_;
1.258     albertel 11485:   if (defined($env{$name})) {
                   11486:     if (ref($env{$name})) {
1.25      albertel 11487:       #already have multiple values
1.258     albertel 11488:       push(@{ $env{$name} },$value);
1.25      albertel 11489:     } else {
                   11490:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11491:       my $first=$env{$name};
                   11492:       undef($env{$name});
                   11493:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11494:     }
                   11495:   } else {
1.258     albertel 11496:     $env{$name}=$value;
1.25      albertel 11497:   }
1.31      albertel 11498: }
1.149     albertel 11499: 
                   11500: =pod
                   11501: 
1.648     raeburn  11502: =item * &get_env_multiple($name) 
1.149     albertel 11503: 
1.258     albertel 11504: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11505: values may be defined and end up as an array ref.
                   11506: 
                   11507: returns an array of values
                   11508: 
                   11509: =cut
                   11510: 
                   11511: sub get_env_multiple {
                   11512:     my ($name) = @_;
                   11513:     my @values;
1.258     albertel 11514:     if (defined($env{$name})) {
1.149     albertel 11515:         # exists is it an array
1.258     albertel 11516:         if (ref($env{$name})) {
                   11517:             @values=@{ $env{$name} };
1.149     albertel 11518:         } else {
1.258     albertel 11519:             $values[0]=$env{$name};
1.149     albertel 11520:         }
                   11521:     }
                   11522:     return(@values);
                   11523: }
                   11524: 
1.660     raeburn  11525: sub ask_for_embedded_content {
                   11526:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11527:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  11528:         %currsubfile,%unused,$rem);
1.1071    raeburn  11529:     my $counter = 0;
                   11530:     my $numnew = 0;
1.987     raeburn  11531:     my $numremref = 0;
                   11532:     my $numinvalid = 0;
                   11533:     my $numpathchg = 0;
                   11534:     my $numexisting = 0;
1.1071    raeburn  11535:     my $numunused = 0;
                   11536:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  11537:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11538:     my $heading = &mt('Upload embedded files');
                   11539:     my $buttontext = &mt('Upload');
                   11540: 
1.1075.2.11  raeburn  11541:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  11542:         if ($actionurl eq '/adm/dependencies') {
                   11543:             $navmap = Apache::lonnavmaps::navmap->new();
                   11544:         }
                   11545:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11546:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  11547:     }
1.1075.2.35  raeburn  11548:     if (($actionurl eq '/adm/portfolio') ||
                   11549:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11550:         my $current_path='/';
                   11551:         if ($env{'form.currentpath'}) {
                   11552:             $current_path = $env{'form.currentpath'};
                   11553:         }
                   11554:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  11555:             $udom = $cdom;
                   11556:             $uname = $cnum;
1.984     raeburn  11557:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11558:         } else {
                   11559:             $udom = $env{'user.domain'};
                   11560:             $uname = $env{'user.name'};
                   11561:             $url = '/userfiles/portfolio';
                   11562:         }
1.987     raeburn  11563:         $toplevel = $url.'/';
1.984     raeburn  11564:         $url .= $current_path;
                   11565:         $getpropath = 1;
1.987     raeburn  11566:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11567:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11568:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11569:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11570:         $toplevel = $url;
1.984     raeburn  11571:         if ($rest ne '') {
1.987     raeburn  11572:             $url .= $rest;
                   11573:         }
                   11574:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11575:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11576:             $url = $args->{'docs_url'};
                   11577:             $toplevel = $url;
1.1075.2.11  raeburn  11578:             if ($args->{'context'} eq 'paste') {
                   11579:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11580:                 ($path) =
                   11581:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11582:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11583:                 $fileloc =~ s{^/}{};
                   11584:             }
1.1071    raeburn  11585:         }
                   11586:     } elsif ($actionurl eq '/adm/dependencies') {
                   11587:         if ($env{'request.course.id'} ne '') {
                   11588:             if (ref($args) eq 'HASH') {
                   11589:                 $url = $args->{'docs_url'};
                   11590:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  11591:                 $toplevel = $url;
                   11592:                 unless ($toplevel =~ m{^/}) {
                   11593:                     $toplevel = "/$url";
                   11594:                 }
1.1075.2.11  raeburn  11595:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  11596:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11597:                     $path = $1;
                   11598:                 } else {
                   11599:                     ($path) =
                   11600:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11601:                 }
1.1075.2.79  raeburn  11602:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11603:                     $fileloc = $toplevel;
                   11604:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11605:                     my ($udom,$uname,$fname) =
                   11606:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11607:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11608:                 } else {
                   11609:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11610:                 }
1.1071    raeburn  11611:                 $fileloc =~ s{^/}{};
                   11612:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11613:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11614:             }
1.987     raeburn  11615:         }
1.1075.2.35  raeburn  11616:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11617:         $udom = $cdom;
                   11618:         $uname = $cnum;
                   11619:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11620:         $toplevel = $url;
                   11621:         $path = $url;
                   11622:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11623:         $fileloc =~ s{^/}{};
                   11624:     }
                   11625:     foreach my $file (keys(%{$allfiles})) {
                   11626:         my $embed_file;
                   11627:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11628:             $embed_file = $1;
                   11629:         } else {
                   11630:             $embed_file = $file;
                   11631:         }
1.1075.2.55  raeburn  11632:         my ($absolutepath,$cleaned_file);
                   11633:         if ($embed_file =~ m{^\w+://}) {
                   11634:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  11635:             $newfiles{$cleaned_file} = 1;
                   11636:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11637:         } else {
1.1075.2.55  raeburn  11638:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11639:             if ($embed_file =~ m{^/}) {
                   11640:                 $absolutepath = $embed_file;
                   11641:             }
1.1075.2.47  raeburn  11642:             if ($cleaned_file =~ m{/}) {
                   11643:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11644:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11645:                 my $item = $fname;
                   11646:                 if ($path ne '') {
                   11647:                     $item = $path.'/'.$fname;
                   11648:                     $subdependencies{$path}{$fname} = 1;
                   11649:                 } else {
                   11650:                     $dependencies{$item} = 1;
                   11651:                 }
                   11652:                 if ($absolutepath) {
                   11653:                     $mapping{$item} = $absolutepath;
                   11654:                 } else {
                   11655:                     $mapping{$item} = $embed_file;
                   11656:                 }
                   11657:             } else {
                   11658:                 $dependencies{$embed_file} = 1;
                   11659:                 if ($absolutepath) {
1.1075.2.47  raeburn  11660:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11661:                 } else {
1.1075.2.47  raeburn  11662:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11663:                 }
                   11664:             }
1.984     raeburn  11665:         }
                   11666:     }
1.1071    raeburn  11667:     my $dirptr = 16384;
1.984     raeburn  11668:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11669:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  11670:         if (($actionurl eq '/adm/portfolio') ||
                   11671:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  11672:             my ($sublistref,$listerror) =
                   11673:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11674:             if (ref($sublistref) eq 'ARRAY') {
                   11675:                 foreach my $line (@{$sublistref}) {
                   11676:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11677:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11678:                 }
1.984     raeburn  11679:             }
1.987     raeburn  11680:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11681:             if (opendir(my $dir,$url.'/'.$path)) {
                   11682:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11683:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11684:             }
1.1075.2.11  raeburn  11685:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11686:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11687:                   ($args->{'context'} eq 'paste')) ||
                   11688:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11689:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  11690:                 my $dir;
                   11691:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11692:                     $dir = $fileloc;
                   11693:                 } else {
                   11694:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11695:                 }
1.1071    raeburn  11696:                 if ($dir ne '') {
                   11697:                     my ($sublistref,$listerror) =
                   11698:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11699:                     if (ref($sublistref) eq 'ARRAY') {
                   11700:                         foreach my $line (@{$sublistref}) {
                   11701:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11702:                                 undef,$mtime)=split(/\&/,$line,12);
                   11703:                             unless (($testdir&$dirptr) ||
                   11704:                                     ($file_name =~ /^\.\.?$/)) {
                   11705:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11706:                             }
                   11707:                         }
                   11708:                     }
                   11709:                 }
1.984     raeburn  11710:             }
                   11711:         }
                   11712:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11713:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11714:                 my $item = $path.'/'.$file;
                   11715:                 unless ($mapping{$item} eq $item) {
                   11716:                     $pathchanges{$item} = 1;
                   11717:                 }
                   11718:                 $existing{$item} = 1;
                   11719:                 $numexisting ++;
                   11720:             } else {
                   11721:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11722:             }
                   11723:         }
1.1071    raeburn  11724:         if ($actionurl eq '/adm/dependencies') {
                   11725:             foreach my $path (keys(%currsubfile)) {
                   11726:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11727:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11728:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11729:                              next if (($rem ne '') &&
                   11730:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11731:                                        (ref($navmap) &&
                   11732:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11733:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11734:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11735:                              $unused{$path.'/'.$file} = 1; 
                   11736:                          }
                   11737:                     }
                   11738:                 }
                   11739:             }
                   11740:         }
1.984     raeburn  11741:     }
1.987     raeburn  11742:     my %currfile;
1.1075.2.35  raeburn  11743:     if (($actionurl eq '/adm/portfolio') ||
                   11744:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11745:         my ($dirlistref,$listerror) =
                   11746:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11747:         if (ref($dirlistref) eq 'ARRAY') {
                   11748:             foreach my $line (@{$dirlistref}) {
                   11749:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11750:                 $currfile{$file_name} = 1;
                   11751:             }
1.984     raeburn  11752:         }
1.987     raeburn  11753:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11754:         if (opendir(my $dir,$url)) {
1.987     raeburn  11755:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11756:             map {$currfile{$_} = 1;} @dir_list;
                   11757:         }
1.1075.2.11  raeburn  11758:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11759:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11760:               ($args->{'context'} eq 'paste')) ||
                   11761:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11762:         if ($env{'request.course.id'} ne '') {
                   11763:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11764:             if ($dir ne '') {
                   11765:                 my ($dirlistref,$listerror) =
                   11766:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11767:                 if (ref($dirlistref) eq 'ARRAY') {
                   11768:                     foreach my $line (@{$dirlistref}) {
                   11769:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11770:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11771:                         unless (($testdir&$dirptr) ||
                   11772:                                 ($file_name =~ /^\.\.?$/)) {
                   11773:                             $currfile{$file_name} = [$size,$mtime];
                   11774:                         }
                   11775:                     }
                   11776:                 }
                   11777:             }
                   11778:         }
1.984     raeburn  11779:     }
                   11780:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11781:         if (exists($currfile{$file})) {
1.987     raeburn  11782:             unless ($mapping{$file} eq $file) {
                   11783:                 $pathchanges{$file} = 1;
                   11784:             }
                   11785:             $existing{$file} = 1;
                   11786:             $numexisting ++;
                   11787:         } else {
1.984     raeburn  11788:             $newfiles{$file} = 1;
                   11789:         }
                   11790:     }
1.1071    raeburn  11791:     foreach my $file (keys(%currfile)) {
                   11792:         unless (($file eq $filename) ||
                   11793:                 ($file eq $filename.'.bak') ||
                   11794:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11795:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11796:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11797:                     next if (($rem ne '') &&
                   11798:                              (($env{"httpref.$rem".$file} ne '') ||
                   11799:                               (ref($navmap) &&
                   11800:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11801:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11802:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11803:                 }
1.1075.2.11  raeburn  11804:             }
1.1071    raeburn  11805:             $unused{$file} = 1;
                   11806:         }
                   11807:     }
1.1075.2.11  raeburn  11808:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11809:         ($args->{'context'} eq 'paste')) {
                   11810:         $counter = scalar(keys(%existing));
                   11811:         $numpathchg = scalar(keys(%pathchanges));
                   11812:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11813:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11814:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11815:         $counter = scalar(keys(%existing));
                   11816:         $numpathchg = scalar(keys(%pathchanges));
                   11817:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11818:     }
1.984     raeburn  11819:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11820:         if ($actionurl eq '/adm/dependencies') {
                   11821:             next if ($embed_file =~ m{^\w+://});
                   11822:         }
1.660     raeburn  11823:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11824:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11825:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11826:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11827:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11828:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11829:         }
1.1075.2.35  raeburn  11830:         $upload_output .= '</td>';
1.1071    raeburn  11831:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11832:             $upload_output.='<td align="right">'.
                   11833:                             '<span class="LC_info LC_fontsize_medium">'.
                   11834:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11835:             $numremref++;
1.660     raeburn  11836:         } elsif ($args->{'error_on_invalid_names'}
                   11837:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11838:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11839:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11840:             $numinvalid++;
1.660     raeburn  11841:         } else {
1.1075.2.35  raeburn  11842:             $upload_output .= '<td>'.
                   11843:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11844:                                                      $embed_file,\%mapping,
1.1071    raeburn  11845:                                                      $allfiles,$codebase,'upload');
                   11846:             $counter ++;
                   11847:             $numnew ++;
1.987     raeburn  11848:         }
                   11849:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11850:     }
                   11851:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11852:         if ($actionurl eq '/adm/dependencies') {
                   11853:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11854:             $modify_output .= &start_data_table_row().
                   11855:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11856:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11857:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11858:                               '<td>'.$size.'</td>'.
                   11859:                               '<td>'.$mtime.'</td>'.
                   11860:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11861:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11862:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11863:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11864:                               &embedded_file_element('upload_embedded',$counter,
                   11865:                                                      $embed_file,\%mapping,
                   11866:                                                      $allfiles,$codebase,'modify').
                   11867:                               '</div></td>'.
                   11868:                               &end_data_table_row()."\n";
                   11869:             $counter ++;
                   11870:         } else {
                   11871:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11872:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11873:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11874:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11875:                               &Apache::loncommon::end_data_table_row()."\n";
                   11876:         }
                   11877:     }
                   11878:     my $delidx = $counter;
                   11879:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11880:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11881:         $delete_output .= &start_data_table_row().
                   11882:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11883:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11884:                           '<td>'.$size.'</td>'.
                   11885:                           '<td>'.$mtime.'</td>'.
                   11886:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11887:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11888:                           &embedded_file_element('upload_embedded',$delidx,
                   11889:                                                  $oldfile,\%mapping,$allfiles,
                   11890:                                                  $codebase,'delete').'</td>'.
                   11891:                           &end_data_table_row()."\n"; 
                   11892:         $numunused ++;
                   11893:         $delidx ++;
1.987     raeburn  11894:     }
                   11895:     if ($upload_output) {
                   11896:         $upload_output = &start_data_table().
                   11897:                          $upload_output.
                   11898:                          &end_data_table()."\n";
                   11899:     }
1.1071    raeburn  11900:     if ($modify_output) {
                   11901:         $modify_output = &start_data_table().
                   11902:                          &start_data_table_header_row().
                   11903:                          '<th>'.&mt('File').'</th>'.
                   11904:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11905:                          '<th>'.&mt('Modified').'</th>'.
                   11906:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11907:                          &end_data_table_header_row().
                   11908:                          $modify_output.
                   11909:                          &end_data_table()."\n";
                   11910:     }
                   11911:     if ($delete_output) {
                   11912:         $delete_output = &start_data_table().
                   11913:                          &start_data_table_header_row().
                   11914:                          '<th>'.&mt('File').'</th>'.
                   11915:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11916:                          '<th>'.&mt('Modified').'</th>'.
                   11917:                          '<th>'.&mt('Delete?').'</th>'.
                   11918:                          &end_data_table_header_row().
                   11919:                          $delete_output.
                   11920:                          &end_data_table()."\n";
                   11921:     }
1.987     raeburn  11922:     my $applies = 0;
                   11923:     if ($numremref) {
                   11924:         $applies ++;
                   11925:     }
                   11926:     if ($numinvalid) {
                   11927:         $applies ++;
                   11928:     }
                   11929:     if ($numexisting) {
                   11930:         $applies ++;
                   11931:     }
1.1071    raeburn  11932:     if ($counter || $numunused) {
1.987     raeburn  11933:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11934:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11935:                   $state.'<h3>'.$heading.'</h3>'; 
                   11936:         if ($actionurl eq '/adm/dependencies') {
                   11937:             if ($numnew) {
                   11938:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11939:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11940:                            $upload_output.'<br />'."\n";
                   11941:             }
                   11942:             if ($numexisting) {
                   11943:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11944:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11945:                            $modify_output.'<br />'."\n";
                   11946:                            $buttontext = &mt('Save changes');
                   11947:             }
                   11948:             if ($numunused) {
                   11949:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11950:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11951:                            $delete_output.'<br />'."\n";
                   11952:                            $buttontext = &mt('Save changes');
                   11953:             }
                   11954:         } else {
                   11955:             $output .= $upload_output.'<br />'."\n";
                   11956:         }
                   11957:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11958:                    $counter.'" />'."\n";
                   11959:         if ($actionurl eq '/adm/dependencies') { 
                   11960:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11961:                        $numnew.'" />'."\n";
                   11962:         } elsif ($actionurl eq '') {
1.987     raeburn  11963:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11964:         }
                   11965:     } elsif ($applies) {
                   11966:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11967:         if ($applies > 1) {
                   11968:             $output .=  
1.1075.2.35  raeburn  11969:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11970:             if ($numremref) {
                   11971:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11972:             }
                   11973:             if ($numinvalid) {
                   11974:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11975:             }
                   11976:             if ($numexisting) {
                   11977:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11978:             }
                   11979:             $output .= '</ul><br />';
                   11980:         } elsif ($numremref) {
                   11981:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11982:         } elsif ($numinvalid) {
                   11983:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11984:         } elsif ($numexisting) {
                   11985:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11986:         }
                   11987:         $output .= $upload_output.'<br />';
                   11988:     }
                   11989:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11990:     $chgcount = $counter;
1.987     raeburn  11991:     if (keys(%pathchanges) > 0) {
                   11992:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11993:             if ($counter) {
1.987     raeburn  11994:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11995:                                                   $embed_file,\%mapping,
1.1071    raeburn  11996:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11997:             } else {
                   11998:                 $pathchange_output .= 
                   11999:                     &start_data_table_row().
                   12000:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12001:                     $chgcount.'" checked="checked" /></td>'.
                   12002:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12003:                     '<td>'.$embed_file.
                   12004:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12005:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12006:                     '</td>'.&end_data_table_row();
1.660     raeburn  12007:             }
1.987     raeburn  12008:             $numpathchg ++;
                   12009:             $chgcount ++;
1.660     raeburn  12010:         }
                   12011:     }
1.1075.2.35  raeburn  12012:     if (($counter) || ($numunused)) {
1.987     raeburn  12013:         if ($numpathchg) {
                   12014:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12015:                        $numpathchg.'" />'."\n";
                   12016:         }
                   12017:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12018:             ($actionurl eq '/adm/imsimport')) {
                   12019:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12020:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12021:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12022:         } elsif ($actionurl eq '/adm/dependencies') {
                   12023:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12024:         }
1.1075.2.35  raeburn  12025:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12026:     } elsif ($numpathchg) {
                   12027:         my %pathchange = ();
                   12028:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12029:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12030:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12031:         }
1.987     raeburn  12032:     }
1.1071    raeburn  12033:     return ($output,$counter,$numpathchg);
1.987     raeburn  12034: }
                   12035: 
1.1075.2.47  raeburn  12036: =pod
                   12037: 
                   12038: =item * clean_path($name)
                   12039: 
                   12040: Performs clean-up of directories, subdirectories and filename in an
                   12041: embedded object, referenced in an HTML file which is being uploaded
                   12042: to a course or portfolio, where
                   12043: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12044: checked.
                   12045: 
                   12046: Clean-up is similar to replacements in lonnet::clean_filename()
                   12047: except each / between sub-directory and next level is preserved.
                   12048: 
                   12049: =cut
                   12050: 
                   12051: sub clean_path {
                   12052:     my ($embed_file) = @_;
                   12053:     $embed_file =~s{^/+}{};
                   12054:     my @contents;
                   12055:     if ($embed_file =~ m{/}) {
                   12056:         @contents = split(/\//,$embed_file);
                   12057:     } else {
                   12058:         @contents = ($embed_file);
                   12059:     }
                   12060:     my $lastidx = scalar(@contents)-1;
                   12061:     for (my $i=0; $i<=$lastidx; $i++) {
                   12062:         $contents[$i]=~s{\\}{/}g;
                   12063:         $contents[$i]=~s/\s+/\_/g;
                   12064:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12065:         if ($i == $lastidx) {
                   12066:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12067:         }
                   12068:     }
                   12069:     if ($lastidx > 0) {
                   12070:         return join('/',@contents);
                   12071:     } else {
                   12072:         return $contents[0];
                   12073:     }
                   12074: }
                   12075: 
1.987     raeburn  12076: sub embedded_file_element {
1.1071    raeburn  12077:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12078:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12079:                    (ref($codebase) eq 'HASH'));
                   12080:     my $output;
1.1071    raeburn  12081:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12082:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12083:     }
                   12084:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12085:                &escape($embed_file).'" />';
                   12086:     unless (($context eq 'upload_embedded') && 
                   12087:             ($mapping->{$embed_file} eq $embed_file)) {
                   12088:         $output .='
                   12089:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12090:     }
                   12091:     my $attrib;
                   12092:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12093:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12094:     }
                   12095:     $output .=
                   12096:         "\n\t\t".
                   12097:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12098:         $attrib.'" />';
                   12099:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12100:         $output .=
                   12101:             "\n\t\t".
                   12102:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12103:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12104:     }
1.987     raeburn  12105:     return $output;
1.660     raeburn  12106: }
                   12107: 
1.1071    raeburn  12108: sub get_dependency_details {
                   12109:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12110:     my ($size,$mtime,$showsize,$showmtime);
                   12111:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12112:         if ($embed_file =~ m{/}) {
                   12113:             my ($path,$fname) = split(/\//,$embed_file);
                   12114:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12115:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12116:             }
                   12117:         } else {
                   12118:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12119:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12120:             }
                   12121:         }
                   12122:         $showsize = $size/1024.0;
                   12123:         $showsize = sprintf("%.1f",$showsize);
                   12124:         if ($mtime > 0) {
                   12125:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12126:         }
                   12127:     }
                   12128:     return ($showsize,$showmtime);
                   12129: }
                   12130: 
                   12131: sub ask_embedded_js {
                   12132:     return <<"END";
                   12133: <script type="text/javascript"">
                   12134: // <![CDATA[
                   12135: function toggleBrowse(counter) {
                   12136:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12137:     var fileid = document.getElementById('embedded_item_'+counter);
                   12138:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12139:     if (chkboxid.checked == true) {
                   12140:         uploaddivid.style.display='block';
                   12141:     } else {
                   12142:         uploaddivid.style.display='none';
                   12143:         fileid.value = '';
                   12144:     }
                   12145: }
                   12146: // ]]>
                   12147: </script>
                   12148: 
                   12149: END
                   12150: }
                   12151: 
1.661     raeburn  12152: sub upload_embedded {
                   12153:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12154:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12155:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12156:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12157:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12158:         my $orig_uploaded_filename =
                   12159:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12160:         foreach my $type ('orig','ref','attrib','codebase') {
                   12161:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12162:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12163:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12164:             }
                   12165:         }
1.661     raeburn  12166:         my ($path,$fname) =
                   12167:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12168:         # no path, whole string is fname
                   12169:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12170:         $fname = &Apache::lonnet::clean_filename($fname);
                   12171:         # See if there is anything left
                   12172:         next if ($fname eq '');
                   12173: 
                   12174:         # Check if file already exists as a file or directory.
                   12175:         my ($state,$msg);
                   12176:         if ($context eq 'portfolio') {
                   12177:             my $port_path = $dirpath;
                   12178:             if ($group ne '') {
                   12179:                 $port_path = "groups/$group/$port_path";
                   12180:             }
1.987     raeburn  12181:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12182:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12183:                                               $dir_root,$port_path,$disk_quota,
                   12184:                                               $current_disk_usage,$uname,$udom);
                   12185:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12186:                 || $state eq 'file_locked') {
1.661     raeburn  12187:                 $output .= $msg;
                   12188:                 next;
                   12189:             }
                   12190:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12191:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12192:             if ($state eq 'exists') {
                   12193:                 $output .= $msg;
                   12194:                 next;
                   12195:             }
                   12196:         }
                   12197:         # Check if extension is valid
                   12198:         if (($fname =~ /\.(\w+)$/) &&
                   12199:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12200:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12201:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12202:             next;
                   12203:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12204:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12205:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12206:             next;
                   12207:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12208:             $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  12209:             next;
                   12210:         }
                   12211:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12212:         my $subdir = $path;
                   12213:         $subdir =~ s{/+$}{};
1.661     raeburn  12214:         if ($context eq 'portfolio') {
1.984     raeburn  12215:             my $result;
                   12216:             if ($state eq 'existingfile') {
                   12217:                 $result=
                   12218:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12219:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12220:             } else {
1.984     raeburn  12221:                 $result=
                   12222:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12223:                                                     $dirpath.
1.1075.2.35  raeburn  12224:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12225:                 if ($result !~ m|^/uploaded/|) {
                   12226:                     $output .= '<span class="LC_error">'
                   12227:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12228:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12229:                                .'</span><br />';
                   12230:                     next;
                   12231:                 } else {
1.987     raeburn  12232:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12233:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12234:                 }
1.661     raeburn  12235:             }
1.1075.2.35  raeburn  12236:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12237:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12238:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12239:             my $result =
1.1075.2.35  raeburn  12240:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12241:             if ($result !~ m|^/uploaded/|) {
                   12242:                 $output .= '<span class="LC_error">'
                   12243:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12244:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12245:                            .'</span><br />';
                   12246:                     next;
                   12247:             } else {
                   12248:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12249:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12250:                 if ($context eq 'syllabus') {
                   12251:                     &Apache::lonnet::make_public_indefinitely($result);
                   12252:                 }
1.987     raeburn  12253:             }
1.661     raeburn  12254:         } else {
                   12255: # Save the file
                   12256:             my $target = $env{'form.embedded_item_'.$i};
                   12257:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12258:             my $dest = $fullpath.$fname;
                   12259:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12260:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12261:             my $count;
                   12262:             my $filepath = $dir_root;
1.1027    raeburn  12263:             foreach my $subdir (@parts) {
                   12264:                 $filepath .= "/$subdir";
                   12265:                 if (!-e $filepath) {
1.661     raeburn  12266:                     mkdir($filepath,0770);
                   12267:                 }
                   12268:             }
                   12269:             my $fh;
                   12270:             if (!open($fh,'>'.$dest)) {
                   12271:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12272:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12273:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12274:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12275:                            '</span><br />';
                   12276:             } else {
                   12277:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12278:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12279:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12280:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12281:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12282:                               '</span><br />';
                   12283:                 } else {
1.987     raeburn  12284:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12285:                                $url.'</span>').'<br />';
                   12286:                     unless ($context eq 'testbank') {
                   12287:                         $footer .= &mt('View embedded file: [_1]',
                   12288:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12289:                     }
                   12290:                 }
                   12291:                 close($fh);
                   12292:             }
                   12293:         }
                   12294:         if ($env{'form.embedded_ref_'.$i}) {
                   12295:             $pathchange{$i} = 1;
                   12296:         }
                   12297:     }
                   12298:     if ($output) {
                   12299:         $output = '<p>'.$output.'</p>';
                   12300:     }
                   12301:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12302:     $returnflag = 'ok';
1.1071    raeburn  12303:     my $numpathchgs = scalar(keys(%pathchange));
                   12304:     if ($numpathchgs > 0) {
1.987     raeburn  12305:         if ($context eq 'portfolio') {
                   12306:             $output .= '<p>'.&mt('or').'</p>';
                   12307:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12308:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12309:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12310:             $returnflag = 'modify_orightml';
                   12311:         }
                   12312:     }
1.1071    raeburn  12313:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12314: }
                   12315: 
                   12316: sub modify_html_form {
                   12317:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12318:     my $end = 0;
                   12319:     my $modifyform;
                   12320:     if ($context eq 'upload_embedded') {
                   12321:         return unless (ref($pathchange) eq 'HASH');
                   12322:         if ($env{'form.number_embedded_items'}) {
                   12323:             $end += $env{'form.number_embedded_items'};
                   12324:         }
                   12325:         if ($env{'form.number_pathchange_items'}) {
                   12326:             $end += $env{'form.number_pathchange_items'};
                   12327:         }
                   12328:         if ($end) {
                   12329:             for (my $i=0; $i<$end; $i++) {
                   12330:                 if ($i < $env{'form.number_embedded_items'}) {
                   12331:                     next unless($pathchange->{$i});
                   12332:                 }
                   12333:                 $modifyform .=
                   12334:                     &start_data_table_row().
                   12335:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12336:                     'checked="checked" /></td>'.
                   12337:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12338:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12339:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12340:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12341:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12342:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12343:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12344:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12345:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12346:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12347:                     &end_data_table_row();
1.1071    raeburn  12348:             }
1.987     raeburn  12349:         }
                   12350:     } else {
                   12351:         $modifyform = $pathchgtable;
                   12352:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12353:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12354:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12355:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12356:         }
                   12357:     }
                   12358:     if ($modifyform) {
1.1071    raeburn  12359:         if ($actionurl eq '/adm/dependencies') {
                   12360:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12361:         }
1.987     raeburn  12362:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12363:                '<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".
                   12364:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12365:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12366:                '</ol></p>'."\n".'<p>'.
                   12367:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12368:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12369:                &start_data_table()."\n".
                   12370:                &start_data_table_header_row().
                   12371:                '<th>'.&mt('Change?').'</th>'.
                   12372:                '<th>'.&mt('Current reference').'</th>'.
                   12373:                '<th>'.&mt('Required reference').'</th>'.
                   12374:                &end_data_table_header_row()."\n".
                   12375:                $modifyform.
                   12376:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12377:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12378:                '</form>'."\n";
                   12379:     }
                   12380:     return;
                   12381: }
                   12382: 
                   12383: sub modify_html_refs {
1.1075.2.35  raeburn  12384:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12385:     my $container;
                   12386:     if ($context eq 'portfolio') {
                   12387:         $container = $env{'form.container'};
                   12388:     } elsif ($context eq 'coursedoc') {
                   12389:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12390:     } elsif ($context eq 'manage_dependencies') {
                   12391:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12392:         $container = "/$container";
1.1075.2.35  raeburn  12393:     } elsif ($context eq 'syllabus') {
                   12394:         $container = $url;
1.987     raeburn  12395:     } else {
1.1027    raeburn  12396:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12397:     }
                   12398:     my (%allfiles,%codebase,$output,$content);
                   12399:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12400:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12401:         if (wantarray) {
                   12402:             return ('',0,0); 
                   12403:         } else {
                   12404:             return;
                   12405:         }
                   12406:     }
                   12407:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12408:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12409:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12410:             if (wantarray) {
                   12411:                 return ('',0,0);
                   12412:             } else {
                   12413:                 return;
                   12414:             }
                   12415:         } 
1.987     raeburn  12416:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12417:         if ($content eq '-1') {
                   12418:             if (wantarray) {
                   12419:                 return ('',0,0);
                   12420:             } else {
                   12421:                 return;
                   12422:             }
                   12423:         }
1.987     raeburn  12424:     } else {
1.1071    raeburn  12425:         unless ($container =~ /^\Q$dir_root\E/) {
                   12426:             if (wantarray) {
                   12427:                 return ('',0,0);
                   12428:             } else {
                   12429:                 return;
                   12430:             }
                   12431:         } 
1.1075.2.128  raeburn  12432:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12433:             $content = join('', <$fh>);
                   12434:             close($fh);
                   12435:         } else {
1.1071    raeburn  12436:             if (wantarray) {
                   12437:                 return ('',0,0);
                   12438:             } else {
                   12439:                 return;
                   12440:             }
1.987     raeburn  12441:         }
                   12442:     }
                   12443:     my ($count,$codebasecount) = (0,0);
                   12444:     my $mm = new File::MMagic;
                   12445:     my $mime_type = $mm->checktype_contents($content);
                   12446:     if ($mime_type eq 'text/html') {
                   12447:         my $parse_result = 
                   12448:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12449:                                                     \%codebase,\$content);
                   12450:         if ($parse_result eq 'ok') {
                   12451:             foreach my $i (@changes) {
                   12452:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12453:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12454:                 if ($allfiles{$ref}) {
                   12455:                     my $newname =  $orig;
                   12456:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12457:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12458:                     if ($attrib_regexp =~ /:/) {
                   12459:                         $attrib_regexp =~ s/\:/|/g;
                   12460:                     }
                   12461:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12462:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12463:                         $count += $numchg;
1.1075.2.35  raeburn  12464:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12465:                         delete($allfiles{$ref});
1.987     raeburn  12466:                     }
                   12467:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12468:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12469:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12470:                         $codebasecount ++;
                   12471:                     }
                   12472:                 }
                   12473:             }
1.1075.2.35  raeburn  12474:             my $skiprewrites;
1.987     raeburn  12475:             if ($count || $codebasecount) {
                   12476:                 my $saveresult;
1.1071    raeburn  12477:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12478:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12479:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12480:                     if ($url eq $container) {
                   12481:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12482:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12483:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12484:                                             $fname.'</span>').'</p>';
1.987     raeburn  12485:                     } else {
                   12486:                          $output = '<p class="LC_error">'.
                   12487:                                    &mt('Error: update failed for: [_1].',
                   12488:                                    '<span class="LC_filename">'.
                   12489:                                    $container.'</span>').'</p>';
                   12490:                     }
1.1075.2.35  raeburn  12491:                     if ($context eq 'syllabus') {
                   12492:                         unless ($saveresult eq 'ok') {
                   12493:                             $skiprewrites = 1;
                   12494:                         }
                   12495:                     }
1.987     raeburn  12496:                 } else {
1.1075.2.128  raeburn  12497:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12498:                         print $fh $content;
                   12499:                         close($fh);
                   12500:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12501:                                   $count,'<span class="LC_filename">'.
                   12502:                                   $container.'</span>').'</p>';
1.661     raeburn  12503:                     } else {
1.987     raeburn  12504:                          $output = '<p class="LC_error">'.
                   12505:                                    &mt('Error: could not update [_1].',
                   12506:                                    '<span class="LC_filename">'.
                   12507:                                    $container.'</span>').'</p>';
1.661     raeburn  12508:                     }
                   12509:                 }
                   12510:             }
1.1075.2.35  raeburn  12511:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12512:                 my ($actionurl,$state);
                   12513:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12514:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12515:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12516:                                               \%codebase,
                   12517:                                               {'context' => 'rewrites',
                   12518:                                                'ignore_remote_references' => 1,});
                   12519:                 if (ref($mapping) eq 'HASH') {
                   12520:                     my $rewrites = 0;
                   12521:                     foreach my $key (keys(%{$mapping})) {
                   12522:                         next if ($key =~ m{^https?://});
                   12523:                         my $ref = $mapping->{$key};
                   12524:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12525:                         my $attrib;
                   12526:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12527:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12528:                         }
                   12529:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12530:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12531:                             $rewrites += $numchg;
                   12532:                         }
                   12533:                     }
                   12534:                     if ($rewrites) {
                   12535:                         my $saveresult;
                   12536:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12537:                         if ($url eq $container) {
                   12538:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12539:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12540:                                             $count,'<span class="LC_filename">'.
                   12541:                                             $fname.'</span>').'</p>';
                   12542:                         } else {
                   12543:                             $output .= '<p class="LC_error">'.
                   12544:                                        &mt('Error: could not update links in [_1].',
                   12545:                                        '<span class="LC_filename">'.
                   12546:                                        $container.'</span>').'</p>';
                   12547: 
                   12548:                         }
                   12549:                     }
                   12550:                 }
                   12551:             }
1.987     raeburn  12552:         } else {
                   12553:             &logthis('Failed to parse '.$container.
                   12554:                      ' to modify references: '.$parse_result);
1.661     raeburn  12555:         }
                   12556:     }
1.1071    raeburn  12557:     if (wantarray) {
                   12558:         return ($output,$count,$codebasecount);
                   12559:     } else {
                   12560:         return $output;
                   12561:     }
1.661     raeburn  12562: }
                   12563: 
                   12564: sub check_for_existing {
                   12565:     my ($path,$fname,$element) = @_;
                   12566:     my ($state,$msg);
                   12567:     if (-d $path.'/'.$fname) {
                   12568:         $state = 'exists';
                   12569:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12570:     } elsif (-e $path.'/'.$fname) {
                   12571:         $state = 'exists';
                   12572:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12573:     }
                   12574:     if ($state eq 'exists') {
                   12575:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12576:     }
                   12577:     return ($state,$msg);
                   12578: }
                   12579: 
                   12580: sub check_for_upload {
                   12581:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12582:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12583:     my $filesize = length($env{'form.'.$element});
                   12584:     if (!$filesize) {
                   12585:         my $msg = '<span class="LC_error">'.
                   12586:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12587:                       '<span class="LC_filename">'.$fname.'</span>',
                   12588:                       $filesize).'<br />'.
1.1007    raeburn  12589:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12590:                   '</span>';
                   12591:         return ('zero_bytes',$msg);
                   12592:     }
                   12593:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12594:     my $getpropath = 1;
1.1021    raeburn  12595:     my ($dirlistref,$listerror) =
                   12596:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12597:     my $found_file = 0;
                   12598:     my $locked_file = 0;
1.991     raeburn  12599:     my @lockers;
                   12600:     my $navmap;
                   12601:     if ($env{'request.course.id'}) {
                   12602:         $navmap = Apache::lonnavmaps::navmap->new();
                   12603:     }
1.1021    raeburn  12604:     if (ref($dirlistref) eq 'ARRAY') {
                   12605:         foreach my $line (@{$dirlistref}) {
                   12606:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12607:             if ($file_name eq $fname){
                   12608:                 $file_name = $path.$file_name;
                   12609:                 if ($group ne '') {
                   12610:                     $file_name = $group.$file_name;
                   12611:                 }
                   12612:                 $found_file = 1;
                   12613:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12614:                     foreach my $lock (@lockers) {
                   12615:                         if (ref($lock) eq 'ARRAY') {
                   12616:                             my ($symb,$crsid) = @{$lock};
                   12617:                             if ($crsid eq $env{'request.course.id'}) {
                   12618:                                 if (ref($navmap)) {
                   12619:                                     my $res = $navmap->getBySymb($symb);
                   12620:                                     foreach my $part (@{$res->parts()}) { 
                   12621:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12622:                                         unless (($slot_status == $res->RESERVED) ||
                   12623:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12624:                                             $locked_file = 1;
                   12625:                                         }
1.991     raeburn  12626:                                     }
1.1021    raeburn  12627:                                 } else {
                   12628:                                     $locked_file = 1;
1.991     raeburn  12629:                                 }
                   12630:                             } else {
                   12631:                                 $locked_file = 1;
                   12632:                             }
                   12633:                         }
1.1021    raeburn  12634:                    }
                   12635:                 } else {
                   12636:                     my @info = split(/\&/,$rest);
                   12637:                     my $currsize = $info[6]/1000;
                   12638:                     if ($currsize < $filesize) {
                   12639:                         my $extra = $filesize - $currsize;
                   12640:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  12641:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12642:                                       &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  12643:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12644:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12645:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12646:                             return ('will_exceed_quota',$msg);
                   12647:                         }
1.984     raeburn  12648:                     }
                   12649:                 }
1.661     raeburn  12650:             }
                   12651:         }
                   12652:     }
                   12653:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  12654:         my $msg = '<p class="LC_warning">'.
                   12655:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   12656:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12657:         return ('will_exceed_quota',$msg);
                   12658:     } elsif ($found_file) {
                   12659:         if ($locked_file) {
1.1075.2.69  raeburn  12660:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12661:             $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  12662:             $msg .= '</p>';
1.661     raeburn  12663:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12664:             return ('file_locked',$msg);
                   12665:         } else {
1.1075.2.69  raeburn  12666:             my $msg = '<p class="LC_error">';
1.984     raeburn  12667:             $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  12668:             $msg .= '</p>';
1.984     raeburn  12669:             return ('existingfile',$msg);
1.661     raeburn  12670:         }
                   12671:     }
                   12672: }
                   12673: 
1.987     raeburn  12674: sub check_for_traversal {
                   12675:     my ($path,$url,$toplevel) = @_;
                   12676:     my @parts=split(/\//,$path);
                   12677:     my $cleanpath;
                   12678:     my $fullpath = $url;
                   12679:     for (my $i=0;$i<@parts;$i++) {
                   12680:         next if ($parts[$i] eq '.');
                   12681:         if ($parts[$i] eq '..') {
                   12682:             $fullpath =~ s{([^/]+/)$}{};
                   12683:         } else {
                   12684:             $fullpath .= $parts[$i].'/';
                   12685:         }
                   12686:     }
                   12687:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12688:         $cleanpath = $1;
                   12689:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12690:         my $curr_toprel = $1;
                   12691:         my @parts = split(/\//,$curr_toprel);
                   12692:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12693:         my @urlparts = split(/\//,$url_toprel);
                   12694:         my $doubledots;
                   12695:         my $startdiff = -1;
                   12696:         for (my $i=0; $i<@urlparts; $i++) {
                   12697:             if ($startdiff == -1) {
                   12698:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12699:                     $startdiff = $i;
                   12700:                     $doubledots .= '../';
                   12701:                 }
                   12702:             } else {
                   12703:                 $doubledots .= '../';
                   12704:             }
                   12705:         }
                   12706:         if ($startdiff > -1) {
                   12707:             $cleanpath = $doubledots;
                   12708:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12709:                 $cleanpath .= $parts[$i].'/';
                   12710:             }
                   12711:         }
                   12712:     }
                   12713:     $cleanpath =~ s{(/)$}{};
                   12714:     return $cleanpath;
                   12715: }
1.31      albertel 12716: 
1.1053    raeburn  12717: sub is_archive_file {
                   12718:     my ($mimetype) = @_;
                   12719:     if (($mimetype eq 'application/octet-stream') ||
                   12720:         ($mimetype eq 'application/x-stuffit') ||
                   12721:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12722:         return 1;
                   12723:     }
                   12724:     return;
                   12725: }
                   12726: 
                   12727: sub decompress_form {
1.1065    raeburn  12728:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12729:     my %lt = &Apache::lonlocal::texthash (
                   12730:         this => 'This file is an archive file.',
1.1067    raeburn  12731:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12732:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12733:         youm => 'You may wish to extract its contents.',
                   12734:         extr => 'Extract contents',
1.1067    raeburn  12735:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12736:         proa => 'Process automatically?',
1.1053    raeburn  12737:         yes  => 'Yes',
                   12738:         no   => 'No',
1.1067    raeburn  12739:         fold => 'Title for folder containing movie',
                   12740:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12741:     );
1.1065    raeburn  12742:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12743:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12744:     my $info = &list_archive_contents($fileloc,\@paths);
                   12745:     if (@paths) {
                   12746:         foreach my $path (@paths) {
                   12747:             $path =~ s{^/}{};
1.1067    raeburn  12748:             if ($path =~ m{^([^/]+)/$}) {
                   12749:                 $topdir = $1;
                   12750:             }
1.1065    raeburn  12751:             if ($path =~ m{^([^/]+)/}) {
                   12752:                 $toplevel{$1} = $path;
                   12753:             } else {
                   12754:                 $toplevel{$path} = $path;
                   12755:             }
                   12756:         }
                   12757:     }
1.1067    raeburn  12758:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12759:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12760:                         "$topdir/media/",
                   12761:                         "$topdir/media/$topdir.mp4",
                   12762:                         "$topdir/media/FirstFrame.png",
                   12763:                         "$topdir/media/player.swf",
                   12764:                         "$topdir/media/swfobject.js",
                   12765:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12766:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12767:                          "$topdir/$topdir.mp4",
                   12768:                          "$topdir/$topdir\_config.xml",
                   12769:                          "$topdir/$topdir\_controller.swf",
                   12770:                          "$topdir/$topdir\_embed.css",
                   12771:                          "$topdir/$topdir\_First_Frame.png",
                   12772:                          "$topdir/$topdir\_player.html",
                   12773:                          "$topdir/$topdir\_Thumbnails.png",
                   12774:                          "$topdir/playerProductInstall.swf",
                   12775:                          "$topdir/scripts/",
                   12776:                          "$topdir/scripts/config_xml.js",
                   12777:                          "$topdir/scripts/handlebars.js",
                   12778:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12779:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12780:                          "$topdir/scripts/modernizr.js",
                   12781:                          "$topdir/scripts/player-min.js",
                   12782:                          "$topdir/scripts/swfobject.js",
                   12783:                          "$topdir/skins/",
                   12784:                          "$topdir/skins/configuration_express.xml",
                   12785:                          "$topdir/skins/express_show/",
                   12786:                          "$topdir/skins/express_show/player-min.css",
                   12787:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12788:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12789:                          "$topdir/$topdir.mp4",
                   12790:                          "$topdir/$topdir\_config.xml",
                   12791:                          "$topdir/$topdir\_controller.swf",
                   12792:                          "$topdir/$topdir\_embed.css",
                   12793:                          "$topdir/$topdir\_First_Frame.png",
                   12794:                          "$topdir/$topdir\_player.html",
                   12795:                          "$topdir/$topdir\_Thumbnails.png",
                   12796:                          "$topdir/playerProductInstall.swf",
                   12797:                          "$topdir/scripts/",
                   12798:                          "$topdir/scripts/config_xml.js",
                   12799:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12800:                          "$topdir/skins/",
                   12801:                          "$topdir/skins/configuration_express.xml",
                   12802:                          "$topdir/skins/express_show/",
                   12803:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12804:                          "$topdir/skins/express_show/spritesheet.png",
                   12805:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12806:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12807:         if (@diffs == 0) {
1.1075.2.59  raeburn  12808:             $is_camtasia = 6;
                   12809:         } else {
1.1075.2.81  raeburn  12810:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12811:             if (@diffs == 0) {
                   12812:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12813:             } else {
                   12814:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12815:                 if (@diffs == 0) {
                   12816:                     $is_camtasia = 8;
                   12817:                 }
1.1075.2.59  raeburn  12818:             }
1.1067    raeburn  12819:         }
                   12820:     }
                   12821:     my $output;
                   12822:     if ($is_camtasia) {
                   12823:         $output = <<"ENDCAM";
                   12824: <script type="text/javascript" language="Javascript">
                   12825: // <![CDATA[
                   12826: 
                   12827: function camtasiaToggle() {
                   12828:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12829:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12830:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12831:                 document.getElementById('camtasia_titles').style.display='block';
                   12832:             } else {
                   12833:                 document.getElementById('camtasia_titles').style.display='none';
                   12834:             }
                   12835:         }
                   12836:     }
                   12837:     return;
                   12838: }
                   12839: 
                   12840: // ]]>
                   12841: </script>
                   12842: <p>$lt{'camt'}</p>
                   12843: ENDCAM
1.1065    raeburn  12844:     } else {
1.1067    raeburn  12845:         $output = '<p>'.$lt{'this'};
                   12846:         if ($info eq '') {
                   12847:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12848:         } else {
                   12849:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12850:                        '<div><pre>'.$info.'</pre></div>';
                   12851:         }
1.1065    raeburn  12852:     }
1.1067    raeburn  12853:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12854:     my $duplicates;
                   12855:     my $num = 0;
                   12856:     if (ref($dirlist) eq 'ARRAY') {
                   12857:         foreach my $item (@{$dirlist}) {
                   12858:             if (ref($item) eq 'ARRAY') {
                   12859:                 if (exists($toplevel{$item->[0]})) {
                   12860:                     $duplicates .= 
                   12861:                         &start_data_table_row().
                   12862:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12863:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12864:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12865:                         'value="1" />'.&mt('Yes').'</label>'.
                   12866:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12867:                         '<td>'.$item->[0].'</td>';
                   12868:                     if ($item->[2]) {
                   12869:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12870:                     } else {
                   12871:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12872:                     }
                   12873:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12874:                                    '<td>'.
                   12875:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12876:                                    '</td>'.
                   12877:                                    &end_data_table_row();
                   12878:                     $num ++;
                   12879:                 }
                   12880:             }
                   12881:         }
                   12882:     }
                   12883:     my $itemcount;
                   12884:     if (@paths > 0) {
                   12885:         $itemcount = scalar(@paths);
                   12886:     } else {
                   12887:         $itemcount = 1;
                   12888:     }
1.1067    raeburn  12889:     if ($is_camtasia) {
                   12890:         $output .= $lt{'auto'}.'<br />'.
                   12891:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12892:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12893:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12894:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12895:                    $lt{'no'}.'</label></span><br />'.
                   12896:                    '<div id="camtasia_titles" style="display:block">'.
                   12897:                    &Apache::lonhtmlcommon::start_pick_box().
                   12898:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12899:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12900:                    &Apache::lonhtmlcommon::row_closure().
                   12901:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12902:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12903:                    &Apache::lonhtmlcommon::row_closure(1).
                   12904:                    &Apache::lonhtmlcommon::end_pick_box().
                   12905:                    '</div>';
                   12906:     }
1.1065    raeburn  12907:     $output .= 
                   12908:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12909:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12910:         "\n";
1.1065    raeburn  12911:     if ($duplicates ne '') {
                   12912:         $output .= '<p><span class="LC_warning">'.
                   12913:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12914:                    &start_data_table().
                   12915:                    &start_data_table_header_row().
                   12916:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12917:                    '<th>'.&mt('Name').'</th>'.
                   12918:                    '<th>'.&mt('Type').'</th>'.
                   12919:                    '<th>'.&mt('Size').'</th>'.
                   12920:                    '<th>'.&mt('Last modified').'</th>'.
                   12921:                    &end_data_table_header_row().
                   12922:                    $duplicates.
                   12923:                    &end_data_table().
                   12924:                    '</p>';
                   12925:     }
1.1067    raeburn  12926:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12927:     if (ref($hiddenelements) eq 'HASH') {
                   12928:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12929:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12930:         }
                   12931:     }
                   12932:     $output .= <<"END";
1.1067    raeburn  12933: <br />
1.1053    raeburn  12934: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12935: </form>
                   12936: $noextract
                   12937: END
                   12938:     return $output;
                   12939: }
                   12940: 
1.1065    raeburn  12941: sub decompression_utility {
                   12942:     my ($program) = @_;
                   12943:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12944:     my $location;
                   12945:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12946:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12947:                          '/usr/sbin/') {
                   12948:             if (-x $dir.$program) {
                   12949:                 $location = $dir.$program;
                   12950:                 last;
                   12951:             }
                   12952:         }
                   12953:     }
                   12954:     return $location;
                   12955: }
                   12956: 
                   12957: sub list_archive_contents {
                   12958:     my ($file,$pathsref) = @_;
                   12959:     my (@cmd,$output);
                   12960:     my $needsregexp;
                   12961:     if ($file =~ /\.zip$/) {
                   12962:         @cmd = (&decompression_utility('unzip'),"-l");
                   12963:         $needsregexp = 1;
                   12964:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12965:              ($file =~ /\.tgz$/)) {
                   12966:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12967:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12968:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12969:     } elsif ($file =~ m|\.tar$|) {
                   12970:         @cmd = (&decompression_utility('tar'),"-tf");
                   12971:     }
                   12972:     if (@cmd) {
                   12973:         undef($!);
                   12974:         undef($@);
                   12975:         if (open(my $fh,"-|", @cmd, $file)) {
                   12976:             while (my $line = <$fh>) {
                   12977:                 $output .= $line;
                   12978:                 chomp($line);
                   12979:                 my $item;
                   12980:                 if ($needsregexp) {
                   12981:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12982:                 } else {
                   12983:                     $item = $line;
                   12984:                 }
                   12985:                 if ($item ne '') {
                   12986:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12987:                         push(@{$pathsref},$item);
                   12988:                     } 
                   12989:                 }
                   12990:             }
                   12991:             close($fh);
                   12992:         }
                   12993:     }
                   12994:     return $output;
                   12995: }
                   12996: 
1.1053    raeburn  12997: sub decompress_uploaded_file {
                   12998:     my ($file,$dir) = @_;
                   12999:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13000:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13001:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13002:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13003:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13004:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13005:     my $decompressed = $env{'cgi.decompressed'};
                   13006:     &Apache::lonnet::delenv('cgi.file');
                   13007:     &Apache::lonnet::delenv('cgi.dir');
                   13008:     &Apache::lonnet::delenv('cgi.decompressed');
                   13009:     return ($decompressed,$result);
                   13010: }
                   13011: 
1.1055    raeburn  13012: sub process_decompression {
                   13013:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13014:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13015:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13016:                &mt('Unexpected file path.').'</p>'."\n";
                   13017:     }
                   13018:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13019:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13020:                &mt('Unexpected course context.').'</p>'."\n";
                   13021:     }
                   13022:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13023:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13024:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13025:     }
1.1055    raeburn  13026:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13027:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13028:         $error = &mt('Filename not a supported archive file type.').
                   13029:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13030:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13031:     } else {
                   13032:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13033:         if ($docuhome eq 'no_host') {
                   13034:             $error = &mt('Could not determine home server for course.');
                   13035:         } else {
                   13036:             my @ids=&Apache::lonnet::current_machine_ids();
                   13037:             my $currdir = "$dir_root/$destination";
                   13038:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13039:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13040:                        "$dir_root/$destination";
                   13041:             } else {
                   13042:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13043:                        "$dir_root/$docudom/$docuname/$destination";
                   13044:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13045:                     $error = &mt('Archive file not found.');
                   13046:                 }
                   13047:             }
1.1065    raeburn  13048:             my (@to_overwrite,@to_skip);
                   13049:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13050:                 my $total = $env{'form.archive_overwrite_total'};
                   13051:                 for (my $i=0; $i<$total; $i++) {
                   13052:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13053:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13054:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13055:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13056:                     }
                   13057:                 }
                   13058:             }
                   13059:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13060:             my $numoverwrite = scalar(@to_overwrite);
                   13061:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13062:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13063:             } elsif ($dir eq '') {
1.1055    raeburn  13064:                 $error = &mt('Directory containing archive file unavailable.');
                   13065:             } elsif (!$error) {
1.1065    raeburn  13066:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13067:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13068:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13069:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13070:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13071:                         ($decompressed,$display) =
                   13072:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13073:                         foreach my $item (@to_skip) {
                   13074:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13075:                                 if (-f "$dir/$tempdir/$item") {
                   13076:                                     unlink("$dir/$tempdir/$item");
                   13077:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13078:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13079:                                 }
                   13080:                             }
                   13081:                         }
                   13082:                         foreach my $item (@to_overwrite) {
                   13083:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13084:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13085:                                     if (-f "$dir/$item") {
                   13086:                                         unlink("$dir/$item");
                   13087:                                     } elsif (-d "$dir/$item") {
                   13088:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13089:                                     }
                   13090:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13091:                                 }
1.1065    raeburn  13092:                             }
                   13093:                         }
1.1075.2.128  raeburn  13094:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13095:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13096:                         }
1.1065    raeburn  13097:                     }
                   13098:                 } else {
                   13099:                     ($decompressed,$display) = 
                   13100:                         &decompress_uploaded_file($file,$dir);
                   13101:                 }
1.1055    raeburn  13102:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13103:                     $output = '<p class="LC_info">'.
                   13104:                               &mt('Files extracted successfully from archive.').
                   13105:                               '</p>'."\n";
1.1055    raeburn  13106:                     my ($warning,$result,@contents);
                   13107:                     my ($newdirlistref,$newlisterror) =
                   13108:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13109:                                                  $docuname,1);
                   13110:                     my (%is_dir,%changes,@newitems);
                   13111:                     my $dirptr = 16384;
1.1065    raeburn  13112:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13113:                         foreach my $dir_line (@{$newdirlistref}) {
                   13114:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13115:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13116:                                 push(@newitems,$item);
                   13117:                                 if ($dirptr&$testdir) {
                   13118:                                     $is_dir{$item} = 1;
                   13119:                                 }
                   13120:                                 $changes{$item} = 1;
                   13121:                             }
                   13122:                         }
                   13123:                     }
                   13124:                     if (keys(%changes) > 0) {
                   13125:                         foreach my $item (sort(@newitems)) {
                   13126:                             if ($changes{$item}) {
                   13127:                                 push(@contents,$item);
                   13128:                             }
                   13129:                         }
                   13130:                     }
                   13131:                     if (@contents > 0) {
1.1067    raeburn  13132:                         my $wantform;
                   13133:                         unless ($env{'form.autoextract_camtasia'}) {
                   13134:                             $wantform = 1;
                   13135:                         }
1.1056    raeburn  13136:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13137:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13138:                                                                 $currdir,\%is_dir,
                   13139:                                                                 \%children,\%parent,
1.1056    raeburn  13140:                                                                 \@contents,\%dirorder,
                   13141:                                                                 \%titles,$wantform);
1.1055    raeburn  13142:                         if ($datatable ne '') {
                   13143:                             $output .= &archive_options_form('decompressed',$datatable,
                   13144:                                                              $count,$hiddenelem);
1.1065    raeburn  13145:                             my $startcount = 6;
1.1055    raeburn  13146:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13147:                                                            \%titles,\%children);
1.1055    raeburn  13148:                         }
1.1067    raeburn  13149:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13150:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13151:                             my %displayed;
                   13152:                             my $total = 1;
                   13153:                             $env{'form.archive_directory'} = [];
                   13154:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13155:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13156:                                 $path =~ s{/$}{};
                   13157:                                 my $item;
                   13158:                                 if ($path ne '') {
                   13159:                                     $item = "$path/$titles{$i}";
                   13160:                                 } else {
                   13161:                                     $item = $titles{$i};
                   13162:                                 }
                   13163:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13164:                                 if ($item eq $contents[0]) {
                   13165:                                     push(@{$env{'form.archive_directory'}},$i);
                   13166:                                     $env{'form.archive_'.$i} = 'display';
                   13167:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13168:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13169:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13170:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13171:                                     $env{'form.archive_'.$i} = 'display';
                   13172:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13173:                                     $displayed{'web'} = $i;
                   13174:                                 } else {
1.1075.2.59  raeburn  13175:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13176:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13177:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13178:                                         push(@{$env{'form.archive_directory'}},$i);
                   13179:                                     }
                   13180:                                     $env{'form.archive_'.$i} = 'dependency';
                   13181:                                 }
                   13182:                                 $total ++;
                   13183:                             }
                   13184:                             for (my $i=1; $i<$total; $i++) {
                   13185:                                 next if ($i == $displayed{'web'});
                   13186:                                 next if ($i == $displayed{'folder'});
                   13187:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13188:                             }
                   13189:                             $env{'form.phase'} = 'decompress_cleanup';
                   13190:                             $env{'form.archivedelete'} = 1;
                   13191:                             $env{'form.archive_count'} = $total-1;
                   13192:                             $output .=
                   13193:                                 &process_extracted_files('coursedocs',$docudom,
                   13194:                                                          $docuname,$destination,
                   13195:                                                          $dir_root,$hiddenelem);
                   13196:                         }
1.1055    raeburn  13197:                     } else {
                   13198:                         $warning = &mt('No new items extracted from archive file.');
                   13199:                     }
                   13200:                 } else {
                   13201:                     $output = $display;
                   13202:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13203:                 }
                   13204:             }
                   13205:         }
                   13206:     }
                   13207:     if ($error) {
                   13208:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13209:                    $error.'</p>'."\n";
                   13210:     }
                   13211:     if ($warning) {
                   13212:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13213:     }
                   13214:     return $output;
                   13215: }
                   13216: 
                   13217: sub get_extracted {
1.1056    raeburn  13218:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13219:         $titles,$wantform) = @_;
1.1055    raeburn  13220:     my $count = 0;
                   13221:     my $depth = 0;
                   13222:     my $datatable;
1.1056    raeburn  13223:     my @hierarchy;
1.1055    raeburn  13224:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13225:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13226:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13227:     foreach my $item (@{$contents}) {
                   13228:         $count ++;
1.1056    raeburn  13229:         @{$dirorder->{$count}} = @hierarchy;
                   13230:         $titles->{$count} = $item;
1.1055    raeburn  13231:         &archive_hierarchy($depth,$count,$parent,$children);
                   13232:         if ($wantform) {
                   13233:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13234:                                        $currdir,$depth,$count);
                   13235:         }
                   13236:         if ($is_dir->{$item}) {
                   13237:             $depth ++;
1.1056    raeburn  13238:             push(@hierarchy,$count);
                   13239:             $parent->{$depth} = $count;
1.1055    raeburn  13240:             $datatable .=
                   13241:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13242:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13243:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13244:             $depth --;
1.1056    raeburn  13245:             pop(@hierarchy);
1.1055    raeburn  13246:         }
                   13247:     }
                   13248:     return ($count,$datatable);
                   13249: }
                   13250: 
                   13251: sub recurse_extracted_archive {
1.1056    raeburn  13252:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13253:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13254:     my $result='';
1.1056    raeburn  13255:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13256:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13257:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13258:         return $result;
                   13259:     }
                   13260:     my $dirptr = 16384;
                   13261:     my ($newdirlistref,$newlisterror) =
                   13262:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13263:     if (ref($newdirlistref) eq 'ARRAY') {
                   13264:         foreach my $dir_line (@{$newdirlistref}) {
                   13265:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13266:             unless ($item =~ /^\.+$/) {
                   13267:                 $$count ++;
1.1056    raeburn  13268:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13269:                 $titles->{$$count} = $item;
1.1055    raeburn  13270:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13271: 
1.1055    raeburn  13272:                 my $is_dir;
                   13273:                 if ($dirptr&$testdir) {
                   13274:                     $is_dir = 1;
                   13275:                 }
                   13276:                 if ($wantform) {
                   13277:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13278:                 }
                   13279:                 if ($is_dir) {
                   13280:                     $$depth ++;
1.1056    raeburn  13281:                     push(@{$hierarchy},$$count);
                   13282:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13283:                     $result .=
                   13284:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13285:                                                    $docuname,$depth,$count,
1.1056    raeburn  13286:                                                    $hierarchy,$dirorder,$children,
                   13287:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13288:                     $$depth --;
1.1056    raeburn  13289:                     pop(@{$hierarchy});
1.1055    raeburn  13290:                 }
                   13291:             }
                   13292:         }
                   13293:     }
                   13294:     return $result;
                   13295: }
                   13296: 
                   13297: sub archive_hierarchy {
                   13298:     my ($depth,$count,$parent,$children) =@_;
                   13299:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13300:         if (exists($parent->{$depth})) {
                   13301:              $children->{$parent->{$depth}} .= $count.':';
                   13302:         }
                   13303:     }
                   13304:     return;
                   13305: }
                   13306: 
                   13307: sub archive_row {
                   13308:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13309:     my ($name) = ($item =~ m{([^/]+)$});
                   13310:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13311:                                        'display'    => 'Add as file',
1.1055    raeburn  13312:                                        'dependency' => 'Include as dependency',
                   13313:                                        'discard'    => 'Discard',
                   13314:                                       );
                   13315:     if ($is_dir) {
1.1059    raeburn  13316:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13317:     }
1.1056    raeburn  13318:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13319:     my $offset = 0;
1.1055    raeburn  13320:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13321:         $offset ++;
1.1065    raeburn  13322:         if ($action ne 'display') {
                   13323:             $offset ++;
                   13324:         }  
1.1055    raeburn  13325:         $output .= '<td><span class="LC_nobreak">'.
                   13326:                    '<label><input type="radio" name="archive_'.$count.
                   13327:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13328:         my $text = $choices{$action};
                   13329:         if ($is_dir) {
                   13330:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13331:             if ($action eq 'display') {
1.1059    raeburn  13332:                 $text = &mt('Add as folder');
1.1055    raeburn  13333:             }
1.1056    raeburn  13334:         } else {
                   13335:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13336: 
                   13337:         }
                   13338:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13339:         if ($action eq 'dependency') {
                   13340:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13341:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13342:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13343:                        '<option value=""></option>'."\n".
                   13344:                        '</select>'."\n".
                   13345:                        '</div>';
1.1059    raeburn  13346:         } elsif ($action eq 'display') {
                   13347:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13348:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13349:                        '</div>';
1.1055    raeburn  13350:         }
1.1056    raeburn  13351:         $output .= '</td>';
1.1055    raeburn  13352:     }
                   13353:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13354:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13355:     for (my $i=0; $i<$depth; $i++) {
                   13356:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13357:     }
                   13358:     if ($is_dir) {
                   13359:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13360:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13361:     } else {
                   13362:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13363:     }
                   13364:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13365:                &end_data_table_row();
                   13366:     return $output;
                   13367: }
                   13368: 
                   13369: sub archive_options_form {
1.1065    raeburn  13370:     my ($form,$display,$count,$hiddenelem) = @_;
                   13371:     my %lt = &Apache::lonlocal::texthash(
                   13372:                perm => 'Permanently remove archive file?',
                   13373:                hows => 'How should each extracted item be incorporated in the course?',
                   13374:                cont => 'Content actions for all',
                   13375:                addf => 'Add as folder/file',
                   13376:                incd => 'Include as dependency for a displayed file',
                   13377:                disc => 'Discard',
                   13378:                no   => 'No',
                   13379:                yes  => 'Yes',
                   13380:                save => 'Save',
                   13381:     );
                   13382:     my $output = <<"END";
                   13383: <form name="$form" method="post" action="">
                   13384: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13385: <label>
                   13386:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13387: </label>
                   13388: &nbsp;
                   13389: <label>
                   13390:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13391: </span>
                   13392: </p>
                   13393: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13394: <br />$lt{'hows'}
                   13395: <div class="LC_columnSection">
                   13396:   <fieldset>
                   13397:     <legend>$lt{'cont'}</legend>
                   13398:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13399:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13400:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13401:   </fieldset>
                   13402: </div>
                   13403: END
                   13404:     return $output.
1.1055    raeburn  13405:            &start_data_table()."\n".
1.1065    raeburn  13406:            $display."\n".
1.1055    raeburn  13407:            &end_data_table()."\n".
                   13408:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13409:            $hiddenelem.
1.1065    raeburn  13410:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13411:            '</form>';
                   13412: }
                   13413: 
                   13414: sub archive_javascript {
1.1056    raeburn  13415:     my ($startcount,$numitems,$titles,$children) = @_;
                   13416:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13417:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13418:     my $scripttag = <<START;
                   13419: <script type="text/javascript">
                   13420: // <![CDATA[
                   13421: 
                   13422: function checkAll(form,prefix) {
                   13423:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13424:     for (var i=0; i < form.elements.length; i++) {
                   13425:         var id = form.elements[i].id;
                   13426:         if ((id != '') && (id != undefined)) {
                   13427:             if (idstr.test(id)) {
                   13428:                 if (form.elements[i].type == 'radio') {
                   13429:                     form.elements[i].checked = true;
1.1056    raeburn  13430:                     var nostart = i-$startcount;
1.1059    raeburn  13431:                     var offset = nostart%7;
                   13432:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13433:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13434:                 }
                   13435:             }
                   13436:         }
                   13437:     }
                   13438: }
                   13439: 
                   13440: function propagateCheck(form,count) {
                   13441:     if (count > 0) {
1.1059    raeburn  13442:         var startelement = $startcount + ((count-1) * 7);
                   13443:         for (var j=1; j<6; j++) {
                   13444:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13445:                 var item = startelement + j; 
                   13446:                 if (form.elements[item].type == 'radio') {
                   13447:                     if (form.elements[item].checked) {
                   13448:                         containerCheck(form,count,j);
                   13449:                         break;
                   13450:                     }
1.1055    raeburn  13451:                 }
                   13452:             }
                   13453:         }
                   13454:     }
                   13455: }
                   13456: 
                   13457: numitems = $numitems
1.1056    raeburn  13458: var titles = new Array(numitems);
                   13459: var parents = new Array(numitems);
1.1055    raeburn  13460: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13461:     parents[i] = new Array;
1.1055    raeburn  13462: }
1.1059    raeburn  13463: var maintitle = '$maintitle';
1.1055    raeburn  13464: 
                   13465: START
                   13466: 
1.1056    raeburn  13467:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13468:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13469:         for (my $i=0; $i<@contents; $i ++) {
                   13470:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13471:         }
                   13472:     }
                   13473: 
1.1056    raeburn  13474:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13475:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13476:     }
                   13477: 
1.1055    raeburn  13478:     $scripttag .= <<END;
                   13479: 
                   13480: function containerCheck(form,count,offset) {
                   13481:     if (count > 0) {
1.1056    raeburn  13482:         dependencyCheck(form,count,offset);
1.1059    raeburn  13483:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13484:         form.elements[item].checked = true;
                   13485:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13486:             if (parents[count].length > 0) {
                   13487:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13488:                     containerCheck(form,parents[count][j],offset);
                   13489:                 }
                   13490:             }
                   13491:         }
                   13492:     }
                   13493: }
                   13494: 
                   13495: function dependencyCheck(form,count,offset) {
                   13496:     if (count > 0) {
1.1059    raeburn  13497:         var chosen = (offset+$startcount)+7*(count-1);
                   13498:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13499:         var currtype = form.elements[depitem].type;
                   13500:         if (form.elements[chosen].value == 'dependency') {
                   13501:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13502:             form.elements[depitem].options.length = 0;
                   13503:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  13504:             for (var i=1; i<=numitems; i++) {
                   13505:                 if (i == count) {
                   13506:                     continue;
                   13507:                 }
1.1059    raeburn  13508:                 var startelement = $startcount + (i-1) * 7;
                   13509:                 for (var j=1; j<6; j++) {
                   13510:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13511:                         var item = startelement + j;
                   13512:                         if (form.elements[item].type == 'radio') {
                   13513:                             if (form.elements[item].checked) {
                   13514:                                 if (form.elements[item].value == 'display') {
                   13515:                                     var n = form.elements[depitem].options.length;
                   13516:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13517:                                 }
                   13518:                             }
                   13519:                         }
                   13520:                     }
                   13521:                 }
                   13522:             }
                   13523:         } else {
                   13524:             document.getElementById('arc_depon_'+count).style.display='none';
                   13525:             form.elements[depitem].options.length = 0;
                   13526:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13527:         }
1.1059    raeburn  13528:         titleCheck(form,count,offset);
1.1056    raeburn  13529:     }
                   13530: }
                   13531: 
                   13532: function propagateSelect(form,count,offset) {
                   13533:     if (count > 0) {
1.1065    raeburn  13534:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13535:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13536:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13537:             if (parents[count].length > 0) {
                   13538:                 for (var j=0; j<parents[count].length; j++) {
                   13539:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13540:                 }
                   13541:             }
                   13542:         }
                   13543:     }
                   13544: }
1.1056    raeburn  13545: 
                   13546: function containerSelect(form,count,offset,picked) {
                   13547:     if (count > 0) {
1.1065    raeburn  13548:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13549:         if (form.elements[item].type == 'radio') {
                   13550:             if (form.elements[item].value == 'dependency') {
                   13551:                 if (form.elements[item+1].type == 'select-one') {
                   13552:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13553:                         if (form.elements[item+1].options[i].value == picked) {
                   13554:                             form.elements[item+1].selectedIndex = i;
                   13555:                             break;
                   13556:                         }
                   13557:                     }
                   13558:                 }
                   13559:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13560:                     if (parents[count].length > 0) {
                   13561:                         for (var j=0; j<parents[count].length; j++) {
                   13562:                             containerSelect(form,parents[count][j],offset,picked);
                   13563:                         }
                   13564:                     }
                   13565:                 }
                   13566:             }
                   13567:         }
                   13568:     }
                   13569: }
                   13570: 
1.1059    raeburn  13571: function titleCheck(form,count,offset) {
                   13572:     if (count > 0) {
                   13573:         var chosen = (offset+$startcount)+7*(count-1);
                   13574:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13575:         var currtype = form.elements[depitem].type;
                   13576:         if (form.elements[chosen].value == 'display') {
                   13577:             document.getElementById('arc_title_'+count).style.display='block';
                   13578:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13579:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13580:             }
                   13581:         } else {
                   13582:             document.getElementById('arc_title_'+count).style.display='none';
                   13583:             if (currtype == 'text') { 
                   13584:                 document.getElementById('archive_title_'+count).value='';
                   13585:             }
                   13586:         }
                   13587:     }
                   13588:     return;
                   13589: }
                   13590: 
1.1055    raeburn  13591: // ]]>
                   13592: </script>
                   13593: END
                   13594:     return $scripttag;
                   13595: }
                   13596: 
                   13597: sub process_extracted_files {
1.1067    raeburn  13598:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13599:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  13600:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13601:     my @ids=&Apache::lonnet::current_machine_ids();
                   13602:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13603:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13604:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13605:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13606:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13607:         $pathtocheck = "$dir_root/$destination";
                   13608:         $dir = $dir_root;
                   13609:         $ishome = 1;
                   13610:     } else {
                   13611:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13612:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  13613:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13614:     }
                   13615:     my $currdir = "$dir_root/$destination";
                   13616:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13617:     if ($env{'form.folderpath'}) {
                   13618:         my @items = split('&',$env{'form.folderpath'});
                   13619:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  13620:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13621:             $containers{'0'}='page';
                   13622:         } else {
                   13623:             $containers{'0'}='sequence';
                   13624:         }
1.1055    raeburn  13625:     }
                   13626:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13627:     if ($numitems) {
                   13628:         for (my $i=1; $i<=$numitems; $i++) {
                   13629:             my $path = $env{'form.archive_content_'.$i};
                   13630:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13631:                 my $item = $1;
                   13632:                 $toplevelitems{$item} = $i;
                   13633:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13634:                     $is_dir{$item} = 1;
                   13635:                 }
                   13636:             }
                   13637:         }
                   13638:     }
1.1067    raeburn  13639:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13640:     if (keys(%toplevelitems) > 0) {
                   13641:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13642:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13643:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13644:     }
1.1066    raeburn  13645:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13646:     if ($numitems) {
                   13647:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  13648:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13649:             my $path = $env{'form.archive_content_'.$i};
                   13650:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13651:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13652:                     if ($prefix ne '' && $path ne '') {
                   13653:                         if (-e $prefix.$path) {
1.1066    raeburn  13654:                             if ((@archdirs > 0) && 
                   13655:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13656:                                 $todeletedir{$prefix.$path} = 1;
                   13657:                             } else {
                   13658:                                 $todelete{$prefix.$path} = 1;
                   13659:                             }
1.1055    raeburn  13660:                         }
                   13661:                     }
                   13662:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13663:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13664:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13665:                     $docstitle = $env{'form.archive_title_'.$i};
                   13666:                     if ($docstitle eq '') {
                   13667:                         $docstitle = $title;
                   13668:                     }
1.1055    raeburn  13669:                     $outer = 0;
1.1056    raeburn  13670:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13671:                         if (@{$dirorder{$i}} > 0) {
                   13672:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13673:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13674:                                     $outer = $item;
                   13675:                                     last;
                   13676:                                 }
                   13677:                             }
                   13678:                         }
                   13679:                     }
                   13680:                     my ($errtext,$fatal) = 
                   13681:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13682:                                                '/'.$folders{$outer}.'.'.
                   13683:                                                $containers{$outer});
                   13684:                     next if ($fatal);
                   13685:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13686:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13687:                             $mapinner{$i} = time;
1.1055    raeburn  13688:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13689:                             $containers{$i} = 'sequence';
                   13690:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13691:                                       $folders{$i}.'.'.$containers{$i};
                   13692:                             my $newidx = &LONCAPA::map::getresidx();
                   13693:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13694:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13695:                             push(@LONCAPA::map::order,$newidx);
                   13696:                             my ($outtext,$errtext) =
                   13697:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13698:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  13699:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13700:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13701:                             unless ($errtext) {
1.1075.2.128  raeburn  13702:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13703:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13704:                                             '</li>'."\n";
1.1067    raeburn  13705:                             }
1.1055    raeburn  13706:                         }
                   13707:                     } else {
                   13708:                         if ($context eq 'coursedocs') {
                   13709:                             my $newidx=&LONCAPA::map::getresidx();
                   13710:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13711:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13712:                                       $title;
1.1075.2.128  raeburn  13713:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13714:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13715:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13716:                                 }
1.1075.2.128  raeburn  13717:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13718:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13719:                                 }
                   13720:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13721:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13722:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13723:                                         unless ($ishome) {
                   13724:                                             my $fetch = "$newdest{$i}/$title";
                   13725:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13726:                                             $prompttofetch{$fetch} = 1;
                   13727:                                         }
                   13728:                                    }
                   13729:                                 }
                   13730:                                 $LONCAPA::map::resources[$newidx]=
                   13731:                                     $docstitle.':'.$url.':false:normal:res';
                   13732:                                 push(@LONCAPA::map::order, $newidx);
                   13733:                                 my ($outtext,$errtext)=
                   13734:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13735:                                                             $docuname.'/'.$folders{$outer}.
                   13736:                                                             '.'.$containers{$outer},1,1);
                   13737:                                 unless ($errtext) {
                   13738:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13739:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13740:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13741:                                                    '</li>'."\n";
                   13742:                                     }
1.1067    raeburn  13743:                                 }
1.1075.2.128  raeburn  13744:                             } else {
                   13745:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13746:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13747:                             }
1.1055    raeburn  13748:                         }
                   13749:                     }
1.1075.2.11  raeburn  13750:                 }
                   13751:             } else {
1.1075.2.128  raeburn  13752:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13753:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13754:             }
                   13755:         }
                   13756:         for (my $i=1; $i<=$numitems; $i++) {
                   13757:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13758:             my $path = $env{'form.archive_content_'.$i};
                   13759:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13760:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13761:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13762:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13763:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13764:                         my ($itemidx,$fullpath,$relpath);
                   13765:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13766:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13767:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13768:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13769:                                     $itemidx = $j;
1.1056    raeburn  13770:                                 }
                   13771:                             }
1.1075.2.11  raeburn  13772:                         }
                   13773:                         if ($itemidx eq '') {
                   13774:                             $itemidx =  0;
                   13775:                         }
                   13776:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13777:                             if ($mapinner{$referrer{$i}}) {
                   13778:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13779:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13780:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13781:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13782:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13783:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13784:                                             if (!-e $fullpath) {
                   13785:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13786:                                             }
                   13787:                                         }
1.1075.2.11  raeburn  13788:                                     } else {
                   13789:                                         last;
1.1056    raeburn  13790:                                     }
1.1075.2.11  raeburn  13791:                                 }
                   13792:                             }
                   13793:                         } elsif ($newdest{$referrer{$i}}) {
                   13794:                             $fullpath = $newdest{$referrer{$i}};
                   13795:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13796:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13797:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13798:                                     last;
                   13799:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13800:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13801:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13802:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13803:                                         if (!-e $fullpath) {
                   13804:                                             mkdir($fullpath,0755);
1.1056    raeburn  13805:                                         }
                   13806:                                     }
1.1075.2.11  raeburn  13807:                                 } else {
                   13808:                                     last;
1.1056    raeburn  13809:                                 }
1.1075.2.11  raeburn  13810:                             }
                   13811:                         }
                   13812:                         if ($fullpath ne '') {
                   13813:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13814:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13815:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13816:                                 }
1.1075.2.11  raeburn  13817:                             }
                   13818:                             if (-e "$fullpath/$title") {
                   13819:                                 my $showpath;
                   13820:                                 if ($relpath ne '') {
                   13821:                                     $showpath = "$relpath/$title";
                   13822:                                 } else {
                   13823:                                     $showpath = "/$title";
1.1056    raeburn  13824:                                 }
1.1075.2.128  raeburn  13825:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13826:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13827:                                            '</li>'."\n";
                   13828:                                 unless ($ishome) {
                   13829:                                     my $fetch = "$fullpath/$title";
                   13830:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13831:                                     $prompttofetch{$fetch} = 1;
                   13832:                                 }
1.1055    raeburn  13833:                             }
                   13834:                         }
                   13835:                     }
1.1075.2.11  raeburn  13836:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13837:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13838:                                     &HTML::Entities::encode($path,'<>&"'),
                   13839:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13840:                                 '<br />';
1.1055    raeburn  13841:                 }
                   13842:             } else {
1.1075.2.128  raeburn  13843:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13844:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13845:             }
                   13846:         }
                   13847:         if (keys(%todelete)) {
                   13848:             foreach my $key (keys(%todelete)) {
                   13849:                 unlink($key);
1.1066    raeburn  13850:             }
                   13851:         }
                   13852:         if (keys(%todeletedir)) {
                   13853:             foreach my $key (keys(%todeletedir)) {
                   13854:                 rmdir($key);
                   13855:             }
                   13856:         }
                   13857:         foreach my $dir (sort(keys(%is_dir))) {
                   13858:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13859:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13860:             }
                   13861:         }
1.1067    raeburn  13862:         if ($result ne '') {
                   13863:             $output .= '<ul>'."\n".
                   13864:                        $result."\n".
                   13865:                        '</ul>';
                   13866:         }
                   13867:         unless ($ishome) {
                   13868:             my $replicationfail;
                   13869:             foreach my $item (keys(%prompttofetch)) {
                   13870:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13871:                 unless ($fetchresult eq 'ok') {
                   13872:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13873:                 }
                   13874:             }
                   13875:             if ($replicationfail) {
                   13876:                 $output .= '<p class="LC_error">'.
                   13877:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13878:                            $replicationfail.
                   13879:                            '</ul></p>';
                   13880:             }
                   13881:         }
1.1055    raeburn  13882:     } else {
                   13883:         $warning = &mt('No items found in archive.');
                   13884:     }
                   13885:     if ($error) {
                   13886:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13887:                    $error.'</p>'."\n";
                   13888:     }
                   13889:     if ($warning) {
                   13890:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13891:     }
                   13892:     return $output;
                   13893: }
                   13894: 
1.1066    raeburn  13895: sub cleanup_empty_dirs {
                   13896:     my ($path) = @_;
                   13897:     if (($path ne '') && (-d $path)) {
                   13898:         if (opendir(my $dirh,$path)) {
                   13899:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13900:             my $numitems = 0;
                   13901:             foreach my $item (@dircontents) {
                   13902:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13903:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13904:                     if (-e "$path/$item") {
                   13905:                         $numitems ++;
                   13906:                     }
                   13907:                 } else {
                   13908:                     $numitems ++;
                   13909:                 }
                   13910:             }
                   13911:             if ($numitems == 0) {
                   13912:                 rmdir($path);
                   13913:             }
                   13914:             closedir($dirh);
                   13915:         }
                   13916:     }
                   13917:     return;
                   13918: }
                   13919: 
1.41      ng       13920: =pod
1.45      matthew  13921: 
1.1075.2.56  raeburn  13922: =item * &get_folder_hierarchy()
1.1068    raeburn  13923: 
                   13924: Provides hierarchy of names of folders/sub-folders containing the current
                   13925: item,
                   13926: 
                   13927: Inputs: 3
                   13928:      - $navmap - navmaps object
                   13929: 
                   13930:      - $map - url for map (either the trigger itself, or map containing
                   13931:                            the resource, which is the trigger).
                   13932: 
                   13933:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13934: 
                   13935: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13936: 
                   13937: =cut
                   13938: 
                   13939: sub get_folder_hierarchy {
                   13940:     my ($navmap,$map,$showitem) = @_;
                   13941:     my @pathitems;
                   13942:     if (ref($navmap)) {
                   13943:         my $mapres = $navmap->getResourceByUrl($map);
                   13944:         if (ref($mapres)) {
                   13945:             my $pcslist = $mapres->map_hierarchy();
                   13946:             if ($pcslist ne '') {
                   13947:                 my @pcs = split(/,/,$pcslist);
                   13948:                 foreach my $pc (@pcs) {
                   13949:                     if ($pc == 1) {
1.1075.2.38  raeburn  13950:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13951:                     } else {
                   13952:                         my $res = $navmap->getByMapPc($pc);
                   13953:                         if (ref($res)) {
                   13954:                             my $title = $res->compTitle();
                   13955:                             $title =~ s/\W+/_/g;
                   13956:                             if ($title ne '') {
                   13957:                                 push(@pathitems,$title);
                   13958:                             }
                   13959:                         }
                   13960:                     }
                   13961:                 }
                   13962:             }
1.1071    raeburn  13963:             if ($showitem) {
                   13964:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13965:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13966:                 } else {
                   13967:                     my $maptitle = $mapres->compTitle();
                   13968:                     $maptitle =~ s/\W+/_/g;
                   13969:                     if ($maptitle ne '') {
                   13970:                         push(@pathitems,$maptitle);
                   13971:                     }
1.1068    raeburn  13972:                 }
                   13973:             }
                   13974:         }
                   13975:     }
                   13976:     return @pathitems;
                   13977: }
                   13978: 
                   13979: =pod
                   13980: 
1.1015    raeburn  13981: =item * &get_turnedin_filepath()
                   13982: 
                   13983: Determines path in a user's portfolio file for storage of files uploaded
                   13984: to a specific essayresponse or dropbox item.
                   13985: 
                   13986: Inputs: 3 required + 1 optional.
                   13987: $symb is symb for resource, $uname and $udom are for current user (required).
                   13988: $caller is optional (can be "submission", if routine is called when storing
                   13989: an upoaded file when "Submit Answer" button was pressed).
                   13990: 
                   13991: Returns array containing $path and $multiresp. 
                   13992: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13993: than one file upload item.  Callers of routine should append partid as a 
                   13994: subdirectory to $path in cases where $multiresp is 1.
                   13995: 
                   13996: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13997: 
                   13998: =cut
                   13999: 
                   14000: sub get_turnedin_filepath {
                   14001:     my ($symb,$uname,$udom,$caller) = @_;
                   14002:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14003:     my $turnindir;
                   14004:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14005:     $turnindir = $userhash{'turnindir'};
                   14006:     my ($path,$multiresp);
                   14007:     if ($turnindir eq '') {
                   14008:         if ($caller eq 'submission') {
                   14009:             $turnindir = &mt('turned in');
                   14010:             $turnindir =~ s/\W+/_/g;
                   14011:             my %newhash = (
                   14012:                             'turnindir' => $turnindir,
                   14013:                           );
                   14014:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14015:         }
                   14016:     }
                   14017:     if ($turnindir ne '') {
                   14018:         $path = '/'.$turnindir.'/';
                   14019:         my ($multipart,$turnin,@pathitems);
                   14020:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14021:         if (defined($navmap)) {
                   14022:             my $mapres = $navmap->getResourceByUrl($map);
                   14023:             if (ref($mapres)) {
                   14024:                 my $pcslist = $mapres->map_hierarchy();
                   14025:                 if ($pcslist ne '') {
                   14026:                     foreach my $pc (split(/,/,$pcslist)) {
                   14027:                         my $res = $navmap->getByMapPc($pc);
                   14028:                         if (ref($res)) {
                   14029:                             my $title = $res->compTitle();
                   14030:                             $title =~ s/\W+/_/g;
                   14031:                             if ($title ne '') {
1.1075.2.48  raeburn  14032:                                 if (($pc > 1) && (length($title) > 12)) {
                   14033:                                     $title = substr($title,0,12);
                   14034:                                 }
1.1015    raeburn  14035:                                 push(@pathitems,$title);
                   14036:                             }
                   14037:                         }
                   14038:                     }
                   14039:                 }
                   14040:                 my $maptitle = $mapres->compTitle();
                   14041:                 $maptitle =~ s/\W+/_/g;
                   14042:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14043:                     if (length($maptitle) > 12) {
                   14044:                         $maptitle = substr($maptitle,0,12);
                   14045:                     }
1.1015    raeburn  14046:                     push(@pathitems,$maptitle);
                   14047:                 }
                   14048:                 unless ($env{'request.state'} eq 'construct') {
                   14049:                     my $res = $navmap->getBySymb($symb);
                   14050:                     if (ref($res)) {
                   14051:                         my $partlist = $res->parts();
                   14052:                         my $totaluploads = 0;
                   14053:                         if (ref($partlist) eq 'ARRAY') {
                   14054:                             foreach my $part (@{$partlist}) {
                   14055:                                 my @types = $res->responseType($part);
                   14056:                                 my @ids = $res->responseIds($part);
                   14057:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14058:                                     if ($types[$i] eq 'essay') {
                   14059:                                         my $partid = $part.'_'.$ids[$i];
                   14060:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14061:                                             $totaluploads ++;
                   14062:                                         }
                   14063:                                     }
                   14064:                                 }
                   14065:                             }
                   14066:                             if ($totaluploads > 1) {
                   14067:                                 $multiresp = 1;
                   14068:                             }
                   14069:                         }
                   14070:                     }
                   14071:                 }
                   14072:             } else {
                   14073:                 return;
                   14074:             }
                   14075:         } else {
                   14076:             return;
                   14077:         }
                   14078:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14079:         $restitle =~ s/\W+/_/g;
                   14080:         if ($restitle eq '') {
                   14081:             $restitle = ($resurl =~ m{/[^/]+$});
                   14082:             if ($restitle eq '') {
                   14083:                 $restitle = time;
                   14084:             }
                   14085:         }
1.1075.2.48  raeburn  14086:         if (length($restitle) > 12) {
                   14087:             $restitle = substr($restitle,0,12);
                   14088:         }
1.1015    raeburn  14089:         push(@pathitems,$restitle);
                   14090:         $path .= join('/',@pathitems);
                   14091:     }
                   14092:     return ($path,$multiresp);
                   14093: }
                   14094: 
                   14095: =pod
                   14096: 
1.464     albertel 14097: =back
1.41      ng       14098: 
1.112     bowersj2 14099: =head1 CSV Upload/Handling functions
1.38      albertel 14100: 
1.41      ng       14101: =over 4
                   14102: 
1.648     raeburn  14103: =item * &upfile_store($r)
1.41      ng       14104: 
                   14105: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14106: needs $env{'form.upfile'}
1.41      ng       14107: returns $datatoken to be put into hidden field
                   14108: 
                   14109: =cut
1.31      albertel 14110: 
                   14111: sub upfile_store {
                   14112:     my $r=shift;
1.258     albertel 14113:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14114:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14115:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14116:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14117: 
1.1075.2.128  raeburn  14118:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14119:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14120:                                      time.'_'.$$);
                   14121:     return if ($datatoken eq '');
                   14122: 
1.31      albertel 14123:     {
1.158     raeburn  14124:         my $datafile = $r->dir_config('lonDaemons').
                   14125:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14126:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14127:             print $fh $env{'form.upfile'};
1.158     raeburn  14128:             close($fh);
                   14129:         }
1.31      albertel 14130:     }
                   14131:     return $datatoken;
                   14132: }
                   14133: 
1.56      matthew  14134: =pod
                   14135: 
1.1075.2.128  raeburn  14136: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14137: 
                   14138: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14139: $datatoken is the name to assign to the temporary file.
1.258     albertel 14140: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14141: 
                   14142: =cut
1.31      albertel 14143: 
                   14144: sub load_tmp_file {
1.1075.2.128  raeburn  14145:     my ($r,$datatoken) = @_;
                   14146:     return if ($datatoken eq '');
1.31      albertel 14147:     my @studentdata=();
                   14148:     {
1.158     raeburn  14149:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14150:                               '/tmp/'.$datatoken.'.tmp';
                   14151:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14152:             @studentdata=<$fh>;
                   14153:             close($fh);
                   14154:         }
1.31      albertel 14155:     }
1.258     albertel 14156:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14157: }
                   14158: 
1.1075.2.128  raeburn  14159: sub valid_datatoken {
                   14160:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14161:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14162:         return $datatoken;
                   14163:     }
                   14164:     return;
                   14165: }
                   14166: 
1.56      matthew  14167: =pod
                   14168: 
1.648     raeburn  14169: =item * &upfile_record_sep()
1.41      ng       14170: 
                   14171: Separate uploaded file into records
                   14172: returns array of records,
1.258     albertel 14173: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14174: 
                   14175: =cut
1.31      albertel 14176: 
                   14177: sub upfile_record_sep {
1.258     albertel 14178:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14179:     } else {
1.248     albertel 14180: 	my @records;
1.258     albertel 14181: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14182: 	    if ($line=~/^\s*$/) { next; }
                   14183: 	    push(@records,$line);
                   14184: 	}
                   14185: 	return @records;
1.31      albertel 14186:     }
                   14187: }
                   14188: 
1.56      matthew  14189: =pod
                   14190: 
1.648     raeburn  14191: =item * &record_sep($record)
1.41      ng       14192: 
1.258     albertel 14193: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14194: 
                   14195: =cut
                   14196: 
1.263     www      14197: sub takeleft {
                   14198:     my $index=shift;
                   14199:     return substr('0000'.$index,-4,4);
                   14200: }
                   14201: 
1.31      albertel 14202: sub record_sep {
                   14203:     my $record=shift;
                   14204:     my %components=();
1.258     albertel 14205:     if ($env{'form.upfiletype'} eq 'xml') {
                   14206:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14207:         my $i=0;
1.356     albertel 14208:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14209:             $field=~s/^(\"|\')//;
                   14210:             $field=~s/(\"|\')$//;
1.263     www      14211:             $components{&takeleft($i)}=$field;
1.31      albertel 14212:             $i++;
                   14213:         }
1.258     albertel 14214:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14215:         my $i=0;
1.356     albertel 14216:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14217:             $field=~s/^(\"|\')//;
                   14218:             $field=~s/(\"|\')$//;
1.263     www      14219:             $components{&takeleft($i)}=$field;
1.31      albertel 14220:             $i++;
                   14221:         }
                   14222:     } else {
1.561     www      14223:         my $separator=',';
1.480     banghart 14224:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14225:             $separator=';';
1.480     banghart 14226:         }
1.31      albertel 14227:         my $i=0;
1.561     www      14228: # the character we are looking for to indicate the end of a quote or a record 
                   14229:         my $looking_for=$separator;
                   14230: # do not add the characters to the fields
                   14231:         my $ignore=0;
                   14232: # we just encountered a separator (or the beginning of the record)
                   14233:         my $just_found_separator=1;
                   14234: # store the field we are working on here
                   14235:         my $field='';
                   14236: # work our way through all characters in record
                   14237:         foreach my $character ($record=~/(.)/g) {
                   14238:             if ($character eq $looking_for) {
                   14239:                if ($character ne $separator) {
                   14240: # Found the end of a quote, again looking for separator
                   14241:                   $looking_for=$separator;
                   14242:                   $ignore=1;
                   14243:                } else {
                   14244: # Found a separator, store away what we got
                   14245:                   $components{&takeleft($i)}=$field;
                   14246: 	          $i++;
                   14247:                   $just_found_separator=1;
                   14248:                   $ignore=0;
                   14249:                   $field='';
                   14250:                }
                   14251:                next;
                   14252:             }
                   14253: # single or double quotation marks after a separator indicate beginning of a quote
                   14254: # we are now looking for the end of the quote and need to ignore separators
                   14255:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14256:                $looking_for=$character;
                   14257:                next;
                   14258:             }
                   14259: # ignore would be true after we reached the end of a quote
                   14260:             if ($ignore) { next; }
                   14261:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14262:             $field.=$character;
                   14263:             $just_found_separator=0; 
1.31      albertel 14264:         }
1.561     www      14265: # catch the very last entry, since we never encountered the separator
                   14266:         $components{&takeleft($i)}=$field;
1.31      albertel 14267:     }
                   14268:     return %components;
                   14269: }
                   14270: 
1.144     matthew  14271: ######################################################
                   14272: ######################################################
                   14273: 
1.56      matthew  14274: =pod
                   14275: 
1.648     raeburn  14276: =item * &upfile_select_html()
1.41      ng       14277: 
1.144     matthew  14278: Return HTML code to select a file from the users machine and specify 
                   14279: the file type.
1.41      ng       14280: 
                   14281: =cut
                   14282: 
1.144     matthew  14283: ######################################################
                   14284: ######################################################
1.31      albertel 14285: sub upfile_select_html {
1.144     matthew  14286:     my %Types = (
                   14287:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14288:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14289:                  space => &mt('Space separated'),
                   14290:                  tab   => &mt('Tabulator separated'),
                   14291: #                 xml   => &mt('HTML/XML'),
                   14292:                  );
                   14293:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14294:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14295:     foreach my $type (sort(keys(%Types))) {
                   14296:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14297:     }
                   14298:     $Str .= "</select>\n";
                   14299:     return $Str;
1.31      albertel 14300: }
                   14301: 
1.301     albertel 14302: sub get_samples {
                   14303:     my ($records,$toget) = @_;
                   14304:     my @samples=({});
                   14305:     my $got=0;
                   14306:     foreach my $rec (@$records) {
                   14307: 	my %temp = &record_sep($rec);
                   14308: 	if (! grep(/\S/, values(%temp))) { next; }
                   14309: 	if (%temp) {
                   14310: 	    $samples[$got]=\%temp;
                   14311: 	    $got++;
                   14312: 	    if ($got == $toget) { last; }
                   14313: 	}
                   14314:     }
                   14315:     return \@samples;
                   14316: }
                   14317: 
1.144     matthew  14318: ######################################################
                   14319: ######################################################
                   14320: 
1.56      matthew  14321: =pod
                   14322: 
1.648     raeburn  14323: =item * &csv_print_samples($r,$records)
1.41      ng       14324: 
                   14325: Prints a table of sample values from each column uploaded $r is an
                   14326: Apache Request ref, $records is an arrayref from
                   14327: &Apache::loncommon::upfile_record_sep
                   14328: 
                   14329: =cut
                   14330: 
1.144     matthew  14331: ######################################################
                   14332: ######################################################
1.31      albertel 14333: sub csv_print_samples {
                   14334:     my ($r,$records) = @_;
1.662     bisitz   14335:     my $samples = &get_samples($records,5);
1.301     albertel 14336: 
1.594     raeburn  14337:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14338:               &start_data_table_header_row());
1.356     albertel 14339:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14340:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14341:     $r->print(&end_data_table_header_row());
1.301     albertel 14342:     foreach my $hash (@$samples) {
1.594     raeburn  14343: 	$r->print(&start_data_table_row());
1.356     albertel 14344: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14345: 	    $r->print('<td>');
1.356     albertel 14346: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14347: 	    $r->print('</td>');
                   14348: 	}
1.594     raeburn  14349: 	$r->print(&end_data_table_row());
1.31      albertel 14350:     }
1.594     raeburn  14351:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14352: }
                   14353: 
1.144     matthew  14354: ######################################################
                   14355: ######################################################
                   14356: 
1.56      matthew  14357: =pod
                   14358: 
1.648     raeburn  14359: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14360: 
                   14361: Prints a table to create associations between values and table columns.
1.144     matthew  14362: 
1.41      ng       14363: $r is an Apache Request ref,
                   14364: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14365: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14366: 
                   14367: =cut
                   14368: 
1.144     matthew  14369: ######################################################
                   14370: ######################################################
1.31      albertel 14371: sub csv_print_select_table {
                   14372:     my ($r,$records,$d) = @_;
1.301     albertel 14373:     my $i=0;
                   14374:     my $samples = &get_samples($records,1);
1.144     matthew  14375:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14376: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14377:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14378:               '<th>'.&mt('Column').'</th>'.
                   14379:               &end_data_table_header_row()."\n");
1.356     albertel 14380:     foreach my $array_ref (@$d) {
                   14381: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14382: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14383: 
1.875     bisitz   14384: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14385: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14386: 	$r->print('<option value="none"></option>');
1.356     albertel 14387: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14388: 	    $r->print('<option value="'.$sample.'"'.
                   14389:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14390:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14391: 	}
1.594     raeburn  14392: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14393: 	$i++;
                   14394:     }
1.594     raeburn  14395:     $r->print(&end_data_table());
1.31      albertel 14396:     $i--;
                   14397:     return $i;
                   14398: }
1.56      matthew  14399: 
1.144     matthew  14400: ######################################################
                   14401: ######################################################
                   14402: 
1.56      matthew  14403: =pod
1.31      albertel 14404: 
1.648     raeburn  14405: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14406: 
                   14407: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14408: 
                   14409: $r is an Apache Request ref,
                   14410: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14411: $d is an array of 2 element arrays (internal name, displayed name)
                   14412: 
                   14413: =cut
                   14414: 
1.144     matthew  14415: ######################################################
                   14416: ######################################################
1.31      albertel 14417: sub csv_samples_select_table {
                   14418:     my ($r,$records,$d) = @_;
                   14419:     my $i=0;
1.144     matthew  14420:     #
1.662     bisitz   14421:     my $max_samples = 5;
                   14422:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14423:     $r->print(&start_data_table().
                   14424:               &start_data_table_header_row().'<th>'.
                   14425:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14426:               &end_data_table_header_row());
1.301     albertel 14427: 
                   14428:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14429: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14430: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14431: 	foreach my $option (@$d) {
                   14432: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14433: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14434:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14435:                       $display.'</option>');
1.31      albertel 14436: 	}
                   14437: 	$r->print('</select></td><td>');
1.662     bisitz   14438: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14439: 	    if (defined($samples->[$line]{$key})) { 
                   14440: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14441: 	    }
                   14442: 	}
1.594     raeburn  14443: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14444: 	$i++;
                   14445:     }
1.594     raeburn  14446:     $r->print(&end_data_table());
1.31      albertel 14447:     $i--;
                   14448:     return($i);
1.115     matthew  14449: }
                   14450: 
1.144     matthew  14451: ######################################################
                   14452: ######################################################
                   14453: 
1.115     matthew  14454: =pod
                   14455: 
1.648     raeburn  14456: =item * &clean_excel_name($name)
1.115     matthew  14457: 
                   14458: Returns a replacement for $name which does not contain any illegal characters.
                   14459: 
                   14460: =cut
                   14461: 
1.144     matthew  14462: ######################################################
                   14463: ######################################################
1.115     matthew  14464: sub clean_excel_name {
                   14465:     my ($name) = @_;
                   14466:     $name =~ s/[:\*\?\/\\]//g;
                   14467:     if (length($name) > 31) {
                   14468:         $name = substr($name,0,31);
                   14469:     }
                   14470:     return $name;
1.25      albertel 14471: }
1.84      albertel 14472: 
1.85      albertel 14473: =pod
                   14474: 
1.648     raeburn  14475: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14476: 
                   14477: Returns either 1 or undef
                   14478: 
                   14479: 1 if the part is to be hidden, undef if it is to be shown
                   14480: 
                   14481: Arguments are:
                   14482: 
                   14483: $id the id of the part to be checked
                   14484: $symb, optional the symb of the resource to check
                   14485: $udom, optional the domain of the user to check for
                   14486: $uname, optional the username of the user to check for
                   14487: 
                   14488: =cut
1.84      albertel 14489: 
                   14490: sub check_if_partid_hidden {
                   14491:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14492:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14493: 					 $symb,$udom,$uname);
1.141     albertel 14494:     my $truth=1;
                   14495:     #if the string starts with !, then the list is the list to show not hide
                   14496:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14497:     my @hiddenlist=split(/,/,$hiddenparts);
                   14498:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14499: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14500:     }
1.141     albertel 14501:     return !$truth;
1.84      albertel 14502: }
1.127     matthew  14503: 
1.138     matthew  14504: 
                   14505: ############################################################
                   14506: ############################################################
                   14507: 
                   14508: =pod
                   14509: 
1.157     matthew  14510: =back 
                   14511: 
1.138     matthew  14512: =head1 cgi-bin script and graphing routines
                   14513: 
1.157     matthew  14514: =over 4
                   14515: 
1.648     raeburn  14516: =item * &get_cgi_id()
1.138     matthew  14517: 
                   14518: Inputs: none
                   14519: 
                   14520: Returns an id which can be used to pass environment variables
                   14521: to various cgi-bin scripts.  These environment variables will
                   14522: be removed from the users environment after a given time by
                   14523: the routine &Apache::lonnet::transfer_profile_to_env.
                   14524: 
                   14525: =cut
                   14526: 
                   14527: ############################################################
                   14528: ############################################################
1.152     albertel 14529: my $uniq=0;
1.136     matthew  14530: sub get_cgi_id {
1.154     albertel 14531:     $uniq=($uniq+1)%100000;
1.280     albertel 14532:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14533: }
                   14534: 
1.127     matthew  14535: ############################################################
                   14536: ############################################################
                   14537: 
                   14538: =pod
                   14539: 
1.648     raeburn  14540: =item * &DrawBarGraph()
1.127     matthew  14541: 
1.138     matthew  14542: Facilitates the plotting of data in a (stacked) bar graph.
                   14543: Puts plot definition data into the users environment in order for 
                   14544: graph.png to plot it.  Returns an <img> tag for the plot.
                   14545: The bars on the plot are labeled '1','2',...,'n'.
                   14546: 
                   14547: Inputs:
                   14548: 
                   14549: =over 4
                   14550: 
                   14551: =item $Title: string, the title of the plot
                   14552: 
                   14553: =item $xlabel: string, text describing the X-axis of the plot
                   14554: 
                   14555: =item $ylabel: string, text describing the Y-axis of the plot
                   14556: 
                   14557: =item $Max: scalar, the maximum Y value to use in the plot
                   14558: If $Max is < any data point, the graph will not be rendered.
                   14559: 
1.140     matthew  14560: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14561: they are plotted.  If undefined, default values will be used.
                   14562: 
1.178     matthew  14563: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14564: 
1.138     matthew  14565: =item @Values: An array of array references.  Each array reference holds data
                   14566: to be plotted in a stacked bar chart.
                   14567: 
1.239     matthew  14568: =item If the final element of @Values is a hash reference the key/value
                   14569: pairs will be added to the graph definition.
                   14570: 
1.138     matthew  14571: =back
                   14572: 
                   14573: Returns:
                   14574: 
                   14575: An <img> tag which references graph.png and the appropriate identifying
                   14576: information for the plot.
                   14577: 
1.127     matthew  14578: =cut
                   14579: 
                   14580: ############################################################
                   14581: ############################################################
1.134     matthew  14582: sub DrawBarGraph {
1.178     matthew  14583:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14584:     #
                   14585:     if (! defined($colors)) {
                   14586:         $colors = ['#33ff00', 
                   14587:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14588:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14589:                   ]; 
                   14590:     }
1.228     matthew  14591:     my $extra_settings = {};
                   14592:     if (ref($Values[-1]) eq 'HASH') {
                   14593:         $extra_settings = pop(@Values);
                   14594:     }
1.127     matthew  14595:     #
1.136     matthew  14596:     my $identifier = &get_cgi_id();
                   14597:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14598:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14599:         return '';
                   14600:     }
1.225     matthew  14601:     #
                   14602:     my @Labels;
                   14603:     if (defined($labels)) {
                   14604:         @Labels = @$labels;
                   14605:     } else {
                   14606:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  14607:             push(@Labels,$i+1);
1.225     matthew  14608:         }
                   14609:     }
                   14610:     #
1.129     matthew  14611:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14612:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14613:     my %ValuesHash;
                   14614:     my $NumSets=1;
                   14615:     foreach my $array (@Values) {
                   14616:         next if (! ref($array));
1.136     matthew  14617:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14618:             join(',',@$array);
1.129     matthew  14619:     }
1.127     matthew  14620:     #
1.136     matthew  14621:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14622:     if ($NumBars < 3) {
                   14623:         $width = 120+$NumBars*32;
1.220     matthew  14624:         $xskip = 1;
1.225     matthew  14625:         $bar_width = 30;
                   14626:     } elsif ($NumBars < 5) {
                   14627:         $width = 120+$NumBars*20;
                   14628:         $xskip = 1;
                   14629:         $bar_width = 20;
1.220     matthew  14630:     } elsif ($NumBars < 10) {
1.136     matthew  14631:         $width = 120+$NumBars*15;
                   14632:         $xskip = 1;
                   14633:         $bar_width = 15;
                   14634:     } elsif ($NumBars <= 25) {
                   14635:         $width = 120+$NumBars*11;
                   14636:         $xskip = 5;
                   14637:         $bar_width = 8;
                   14638:     } elsif ($NumBars <= 50) {
                   14639:         $width = 120+$NumBars*8;
                   14640:         $xskip = 5;
                   14641:         $bar_width = 4;
                   14642:     } else {
                   14643:         $width = 120+$NumBars*8;
                   14644:         $xskip = 5;
                   14645:         $bar_width = 4;
                   14646:     }
                   14647:     #
1.137     matthew  14648:     $Max = 1 if ($Max < 1);
                   14649:     if ( int($Max) < $Max ) {
                   14650:         $Max++;
                   14651:         $Max = int($Max);
                   14652:     }
1.127     matthew  14653:     $Title  = '' if (! defined($Title));
                   14654:     $xlabel = '' if (! defined($xlabel));
                   14655:     $ylabel = '' if (! defined($ylabel));
1.369     www      14656:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14657:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14658:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14659:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14660:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14661:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14662:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14663:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14664:     $ValuesHash{$id.'.height'}   = $height;
                   14665:     $ValuesHash{$id.'.width'}    = $width;
                   14666:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14667:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14668:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14669:     #
1.228     matthew  14670:     # Deal with other parameters
                   14671:     while (my ($key,$value) = each(%$extra_settings)) {
                   14672:         $ValuesHash{$id.'.'.$key} = $value;
                   14673:     }
                   14674:     #
1.646     raeburn  14675:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14676:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14677: }
                   14678: 
                   14679: ############################################################
                   14680: ############################################################
                   14681: 
                   14682: =pod
                   14683: 
1.648     raeburn  14684: =item * &DrawXYGraph()
1.137     matthew  14685: 
1.138     matthew  14686: Facilitates the plotting of data in an XY graph.
                   14687: Puts plot definition data into the users environment in order for 
                   14688: graph.png to plot it.  Returns an <img> tag for the plot.
                   14689: 
                   14690: Inputs:
                   14691: 
                   14692: =over 4
                   14693: 
                   14694: =item $Title: string, the title of the plot
                   14695: 
                   14696: =item $xlabel: string, text describing the X-axis of the plot
                   14697: 
                   14698: =item $ylabel: string, text describing the Y-axis of the plot
                   14699: 
                   14700: =item $Max: scalar, the maximum Y value to use in the plot
                   14701: If $Max is < any data point, the graph will not be rendered.
                   14702: 
                   14703: =item $colors: Array ref containing the hex color codes for the data to be 
                   14704: plotted in.  If undefined, default values will be used.
                   14705: 
                   14706: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14707: 
                   14708: =item $Ydata: Array ref containing Array refs.  
1.185     www      14709: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14710: 
                   14711: =item %Values: hash indicating or overriding any default values which are 
                   14712: passed to graph.png.  
                   14713: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14714: 
                   14715: =back
                   14716: 
                   14717: Returns:
                   14718: 
                   14719: An <img> tag which references graph.png and the appropriate identifying
                   14720: information for the plot.
                   14721: 
1.137     matthew  14722: =cut
                   14723: 
                   14724: ############################################################
                   14725: ############################################################
                   14726: sub DrawXYGraph {
                   14727:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14728:     #
                   14729:     # Create the identifier for the graph
                   14730:     my $identifier = &get_cgi_id();
                   14731:     my $id = 'cgi.'.$identifier;
                   14732:     #
                   14733:     $Title  = '' if (! defined($Title));
                   14734:     $xlabel = '' if (! defined($xlabel));
                   14735:     $ylabel = '' if (! defined($ylabel));
                   14736:     my %ValuesHash = 
                   14737:         (
1.369     www      14738:          $id.'.title'  => &escape($Title),
                   14739:          $id.'.xlabel' => &escape($xlabel),
                   14740:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14741:          $id.'.y_max_value'=> $Max,
                   14742:          $id.'.labels'     => join(',',@$Xlabels),
                   14743:          $id.'.PlotType'   => 'XY',
                   14744:          );
                   14745:     #
                   14746:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14747:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14748:     }
                   14749:     #
                   14750:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14751:         return '';
                   14752:     }
                   14753:     my $NumSets=1;
1.138     matthew  14754:     foreach my $array (@{$Ydata}){
1.137     matthew  14755:         next if (! ref($array));
                   14756:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14757:     }
1.138     matthew  14758:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14759:     #
                   14760:     # Deal with other parameters
                   14761:     while (my ($key,$value) = each(%Values)) {
                   14762:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14763:     }
                   14764:     #
1.646     raeburn  14765:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14766:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14767: }
                   14768: 
                   14769: ############################################################
                   14770: ############################################################
                   14771: 
                   14772: =pod
                   14773: 
1.648     raeburn  14774: =item * &DrawXYYGraph()
1.138     matthew  14775: 
                   14776: Facilitates the plotting of data in an XY graph with two Y axes.
                   14777: Puts plot definition data into the users environment in order for 
                   14778: graph.png to plot it.  Returns an <img> tag for the plot.
                   14779: 
                   14780: Inputs:
                   14781: 
                   14782: =over 4
                   14783: 
                   14784: =item $Title: string, the title of the plot
                   14785: 
                   14786: =item $xlabel: string, text describing the X-axis of the plot
                   14787: 
                   14788: =item $ylabel: string, text describing the Y-axis of the plot
                   14789: 
                   14790: =item $colors: Array ref containing the hex color codes for the data to be 
                   14791: plotted in.  If undefined, default values will be used.
                   14792: 
                   14793: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14794: 
                   14795: =item $Ydata1: The first data set
                   14796: 
                   14797: =item $Min1: The minimum value of the left Y-axis
                   14798: 
                   14799: =item $Max1: The maximum value of the left Y-axis
                   14800: 
                   14801: =item $Ydata2: The second data set
                   14802: 
                   14803: =item $Min2: The minimum value of the right Y-axis
                   14804: 
                   14805: =item $Max2: The maximum value of the left Y-axis
                   14806: 
                   14807: =item %Values: hash indicating or overriding any default values which are 
                   14808: passed to graph.png.  
                   14809: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14810: 
                   14811: =back
                   14812: 
                   14813: Returns:
                   14814: 
                   14815: An <img> tag which references graph.png and the appropriate identifying
                   14816: information for the plot.
1.136     matthew  14817: 
                   14818: =cut
                   14819: 
                   14820: ############################################################
                   14821: ############################################################
1.137     matthew  14822: sub DrawXYYGraph {
                   14823:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14824:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14825:     #
                   14826:     # Create the identifier for the graph
                   14827:     my $identifier = &get_cgi_id();
                   14828:     my $id = 'cgi.'.$identifier;
                   14829:     #
                   14830:     $Title  = '' if (! defined($Title));
                   14831:     $xlabel = '' if (! defined($xlabel));
                   14832:     $ylabel = '' if (! defined($ylabel));
                   14833:     my %ValuesHash = 
                   14834:         (
1.369     www      14835:          $id.'.title'  => &escape($Title),
                   14836:          $id.'.xlabel' => &escape($xlabel),
                   14837:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14838:          $id.'.labels' => join(',',@$Xlabels),
                   14839:          $id.'.PlotType' => 'XY',
                   14840:          $id.'.NumSets' => 2,
1.137     matthew  14841:          $id.'.two_axes' => 1,
                   14842:          $id.'.y1_max_value' => $Max1,
                   14843:          $id.'.y1_min_value' => $Min1,
                   14844:          $id.'.y2_max_value' => $Max2,
                   14845:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14846:          );
                   14847:     #
1.137     matthew  14848:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14849:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14850:     }
                   14851:     #
                   14852:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14853:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14854:         return '';
                   14855:     }
                   14856:     my $NumSets=1;
1.137     matthew  14857:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14858:         next if (! ref($array));
                   14859:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14860:     }
                   14861:     #
                   14862:     # Deal with other parameters
                   14863:     while (my ($key,$value) = each(%Values)) {
                   14864:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14865:     }
                   14866:     #
1.646     raeburn  14867:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14868:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14869: }
                   14870: 
                   14871: ############################################################
                   14872: ############################################################
                   14873: 
                   14874: =pod
                   14875: 
1.157     matthew  14876: =back 
                   14877: 
1.139     matthew  14878: =head1 Statistics helper routines?  
                   14879: 
                   14880: Bad place for them but what the hell.
                   14881: 
1.157     matthew  14882: =over 4
                   14883: 
1.648     raeburn  14884: =item * &chartlink()
1.139     matthew  14885: 
                   14886: Returns a link to the chart for a specific student.  
                   14887: 
                   14888: Inputs:
                   14889: 
                   14890: =over 4
                   14891: 
                   14892: =item $linktext: The text of the link
                   14893: 
                   14894: =item $sname: The students username
                   14895: 
                   14896: =item $sdomain: The students domain
                   14897: 
                   14898: =back
                   14899: 
1.157     matthew  14900: =back
                   14901: 
1.139     matthew  14902: =cut
                   14903: 
                   14904: ############################################################
                   14905: ############################################################
                   14906: sub chartlink {
                   14907:     my ($linktext, $sname, $sdomain) = @_;
                   14908:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14909:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14910:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14911:        '">'.$linktext.'</a>';
1.153     matthew  14912: }
                   14913: 
                   14914: #######################################################
                   14915: #######################################################
                   14916: 
                   14917: =pod
                   14918: 
                   14919: =head1 Course Environment Routines
1.157     matthew  14920: 
                   14921: =over 4
1.153     matthew  14922: 
1.648     raeburn  14923: =item * &restore_course_settings()
1.153     matthew  14924: 
1.648     raeburn  14925: =item * &store_course_settings()
1.153     matthew  14926: 
                   14927: Restores/Store indicated form parameters from the course environment.
                   14928: Will not overwrite existing values of the form parameters.
                   14929: 
                   14930: Inputs: 
                   14931: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14932: 
                   14933: a hash ref describing the data to be stored.  For example:
                   14934:    
                   14935: %Save_Parameters = ('Status' => 'scalar',
                   14936:     'chartoutputmode' => 'scalar',
                   14937:     'chartoutputdata' => 'scalar',
                   14938:     'Section' => 'array',
1.373     raeburn  14939:     'Group' => 'array',
1.153     matthew  14940:     'StudentData' => 'array',
                   14941:     'Maps' => 'array');
                   14942: 
                   14943: Returns: both routines return nothing
                   14944: 
1.631     raeburn  14945: =back
                   14946: 
1.153     matthew  14947: =cut
                   14948: 
                   14949: #######################################################
                   14950: #######################################################
                   14951: sub store_course_settings {
1.496     albertel 14952:     return &store_settings($env{'request.course.id'},@_);
                   14953: }
                   14954: 
                   14955: sub store_settings {
1.153     matthew  14956:     # save to the environment
                   14957:     # appenv the same items, just to be safe
1.300     albertel 14958:     my $udom  = $env{'user.domain'};
                   14959:     my $uname = $env{'user.name'};
1.496     albertel 14960:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14961:     my %SaveHash;
                   14962:     my %AppHash;
                   14963:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14964:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14965:         my $envname = 'environment.'.$basename;
1.258     albertel 14966:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14967:             # Save this value away
                   14968:             if ($type eq 'scalar' &&
1.258     albertel 14969:                 (! exists($env{$envname}) || 
                   14970:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14971:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14972:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14973:             } elsif ($type eq 'array') {
                   14974:                 my $stored_form;
1.258     albertel 14975:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14976:                     $stored_form = join(',',
                   14977:                                         map {
1.369     www      14978:                                             &escape($_);
1.258     albertel 14979:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14980:                 } else {
                   14981:                     $stored_form = 
1.369     www      14982:                         &escape($env{'form.'.$setting});
1.153     matthew  14983:                 }
                   14984:                 # Determine if the array contents are the same.
1.258     albertel 14985:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14986:                     $SaveHash{$basename} = $stored_form;
                   14987:                     $AppHash{$envname}   = $stored_form;
                   14988:                 }
                   14989:             }
                   14990:         }
                   14991:     }
                   14992:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14993:                                           $udom,$uname);
1.153     matthew  14994:     if ($put_result !~ /^(ok|delayed)/) {
                   14995:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14996:                                  'got error:'.$put_result);
                   14997:     }
                   14998:     # Make sure these settings stick around in this session, too
1.646     raeburn  14999:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15000:     return;
                   15001: }
                   15002: 
                   15003: sub restore_course_settings {
1.499     albertel 15004:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15005: }
                   15006: 
                   15007: sub restore_settings {
                   15008:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15009:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15010:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15011:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15012:             '.'.$setting;
1.258     albertel 15013:         if (exists($env{$envname})) {
1.153     matthew  15014:             if ($type eq 'scalar') {
1.258     albertel 15015:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15016:             } elsif ($type eq 'array') {
1.258     albertel 15017:                 $env{'form.'.$setting} = [ 
1.153     matthew  15018:                                            map { 
1.369     www      15019:                                                &unescape($_); 
1.258     albertel 15020:                                            } split(',',$env{$envname})
1.153     matthew  15021:                                            ];
                   15022:             }
                   15023:         }
                   15024:     }
1.127     matthew  15025: }
                   15026: 
1.618     raeburn  15027: #######################################################
                   15028: #######################################################
                   15029: 
                   15030: =pod
                   15031: 
                   15032: =head1 Domain E-mail Routines  
                   15033: 
                   15034: =over 4
                   15035: 
1.648     raeburn  15036: =item * &build_recipient_list()
1.618     raeburn  15037: 
1.1075.2.44  raeburn  15038: Build recipient lists for following types of e-mail:
1.766     raeburn  15039: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15040: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15041: module change checking, student/employee ID conflict checks, as
                   15042: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15043: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15044: 
                   15045: Inputs:
1.1075.2.44  raeburn  15046: defmail (scalar - email address of default recipient),
                   15047: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15048: requestsmail, updatesmail, or idconflictsmail).
                   15049: 
1.619     raeburn  15050: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15051: 
                   15052: origmail (scalar - email address of recipient from loncapa.conf,
                   15053: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15054: 
1.1075.2.139  raeburn  15055: $requname username of requester (if mailing type is helpdeskmail)
                   15056: 
                   15057: $requdom domain of requester (if mailing type is helpdeskmail)
                   15058: 
                   15059: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15060: 
1.655     raeburn  15061: Returns: comma separated list of addresses to which to send e-mail.
                   15062: 
                   15063: =back
1.618     raeburn  15064: 
                   15065: =cut
                   15066: 
                   15067: ############################################################
                   15068: ############################################################
                   15069: sub build_recipient_list {
1.1075.2.139  raeburn  15070:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15071:     my @recipients;
1.1075.2.122  raeburn  15072:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15073:     my %domconfig =
1.1075.2.122  raeburn  15074:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15075:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15076:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15077:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15078:                 my @contacts = ('adminemail','supportemail');
                   15079:                 foreach my $item (@contacts) {
                   15080:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15081:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15082:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15083:                             push(@recipients,$addr);
                   15084:                         }
1.619     raeburn  15085:                     }
1.1075.2.122  raeburn  15086:                 }
                   15087:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15088:                 if ($mailing eq 'helpdeskmail') {
                   15089:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15090:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15091:                         my @ok_bccs;
                   15092:                         foreach my $bcc (@bccs) {
                   15093:                             $bcc =~ s/^\s+//g;
                   15094:                             $bcc =~ s/\s+$//g;
                   15095:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15096:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15097:                                     push(@ok_bccs,$bcc);
                   15098:                                 }
                   15099:                             }
                   15100:                         }
                   15101:                         if (@ok_bccs > 0) {
                   15102:                             $allbcc = join(', ',@ok_bccs);
                   15103:                         }
                   15104:                     }
                   15105:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15106:                 }
                   15107:             }
1.766     raeburn  15108:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15109:             $lastresort = $origmail;
1.618     raeburn  15110:         }
1.1075.2.139  raeburn  15111:         if ($mailing eq 'helpdeskmail') {
                   15112:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15113:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15114:                 my ($inststatus,$inststatus_checked);
                   15115:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15116:                     ($env{'user.domain'} ne 'public')) {
                   15117:                     $inststatus_checked = 1;
                   15118:                     $inststatus = $env{'environment.inststatus'};
                   15119:                 }
                   15120:                 unless ($inststatus_checked) {
                   15121:                     if (($requname ne '') && ($requdom ne '')) {
                   15122:                         if (($requname =~ /^$match_username$/) &&
                   15123:                             ($requdom =~ /^$match_domain$/) &&
                   15124:                             (&Apache::lonnet::domain($requdom))) {
                   15125:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15126:                                                                       $requdom);
                   15127:                             unless ($requhome eq 'no_host') {
                   15128:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15129:                                 $inststatus = $userenv{'inststatus'};
                   15130:                                 $inststatus_checked = 1;
                   15131:                             }
                   15132:                         }
                   15133:                     }
                   15134:                 }
                   15135:                 unless ($inststatus_checked) {
                   15136:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15137:                         my %srch = (srchby     => 'email',
                   15138:                                     srchdomain => $defdom,
                   15139:                                     srchterm   => $reqemail,
                   15140:                                     srchtype   => 'exact');
                   15141:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15142:                         foreach my $uname (keys(%srch_results)) {
                   15143:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15144:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15145:                                 $inststatus_checked = 1;
                   15146:                                 last;
                   15147:                             }
                   15148:                         }
                   15149:                         unless ($inststatus_checked) {
                   15150:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15151:                             if ($dirsrchres eq 'ok') {
                   15152:                                 foreach my $uname (keys(%srch_results)) {
                   15153:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15154:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15155:                                         $inststatus_checked = 1;
                   15156:                                         last;
                   15157:                                     }
                   15158:                                 }
                   15159:                             }
                   15160:                         }
                   15161:                     }
                   15162:                 }
                   15163:                 if ($inststatus ne '') {
                   15164:                     foreach my $status (split(/\:/,$inststatus)) {
                   15165:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15166:                             my @contacts = ('adminemail','supportemail');
                   15167:                             foreach my $item (@contacts) {
                   15168:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15169:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15170:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15171:                                         push(@recipients,$addr);
                   15172:                                     }
                   15173:                                 }
                   15174:                             }
                   15175:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15176:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15177:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15178:                                 my @ok_bccs;
                   15179:                                 foreach my $bcc (@bccs) {
                   15180:                                     $bcc =~ s/^\s+//g;
                   15181:                                     $bcc =~ s/\s+$//g;
                   15182:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15183:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15184:                                             push(@ok_bccs,$bcc);
                   15185:                                         }
                   15186:                                     }
                   15187:                                 }
                   15188:                                 if (@ok_bccs > 0) {
                   15189:                                     $allbcc = join(', ',@ok_bccs);
                   15190:                                 }
                   15191:                             }
                   15192:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15193:                             last;
                   15194:                         }
                   15195:                     }
                   15196:                 }
                   15197:             }
                   15198:         }
1.619     raeburn  15199:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15200:         $lastresort = $origmail;
                   15201:     }
1.1075.2.128  raeburn  15202:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15203:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15204:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15205:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15206:             my %what = (
                   15207:                           perlvar => 1,
                   15208:                        );
                   15209:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15210:             if ($primary) {
                   15211:                 my $gotaddr;
                   15212:                 my ($result,$returnhash) =
                   15213:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15214:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15215:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15216:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15217:                         $gotaddr = 1;
                   15218:                     }
                   15219:                 }
                   15220:                 unless ($gotaddr) {
                   15221:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15222:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15223:                     unless ($uintdom eq $intdom) {
                   15224:                         my %domconfig =
                   15225:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15226:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15227:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15228:                                 my @contacts = ('adminemail','supportemail');
                   15229:                                 foreach my $item (@contacts) {
                   15230:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15231:                                         my $addr = $domconfig{'contacts'}{$item};
                   15232:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15233:                                             push(@recipients,$addr);
                   15234:                                         }
                   15235:                                     }
                   15236:                                 }
                   15237:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15238:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15239:                                 }
                   15240:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15241:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15242:                                     my @ok_bccs;
                   15243:                                     foreach my $bcc (@bccs) {
                   15244:                                         $bcc =~ s/^\s+//g;
                   15245:                                         $bcc =~ s/\s+$//g;
                   15246:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15247:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15248:                                                 push(@ok_bccs,$bcc);
                   15249:                                             }
                   15250:                                         }
                   15251:                                     }
                   15252:                                     if (@ok_bccs > 0) {
                   15253:                                         $allbcc = join(', ',@ok_bccs);
                   15254:                                     }
                   15255:                                 }
                   15256:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15257:                             }
                   15258:                         }
                   15259:                     }
                   15260:                 }
                   15261:             }
                   15262:         }
1.618     raeburn  15263:     }
1.688     raeburn  15264:     if (defined($defmail)) {
                   15265:         if ($defmail ne '') {
                   15266:             push(@recipients,$defmail);
                   15267:         }
1.618     raeburn  15268:     }
                   15269:     if ($otheremails) {
1.619     raeburn  15270:         my @others;
                   15271:         if ($otheremails =~ /,/) {
                   15272:             @others = split(/,/,$otheremails);
1.618     raeburn  15273:         } else {
1.619     raeburn  15274:             push(@others,$otheremails);
                   15275:         }
                   15276:         foreach my $addr (@others) {
                   15277:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15278:                 push(@recipients,$addr);
                   15279:             }
1.618     raeburn  15280:         }
                   15281:     }
1.1075.2.128  raeburn  15282:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15283:         if ((!@recipients) && ($lastresort ne '')) {
                   15284:             push(@recipients,$lastresort);
                   15285:         }
                   15286:     } elsif ($lastresort ne '') {
                   15287:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15288:             push(@recipients,$lastresort);
                   15289:         }
                   15290:     }
                   15291:     my $recipientlist = join(',',@recipients);
                   15292:     if (wantarray) {
                   15293:         return ($recipientlist,$allbcc,$addtext);
                   15294:     } else {
                   15295:         return $recipientlist;
                   15296:     }
1.618     raeburn  15297: }
                   15298: 
1.127     matthew  15299: ############################################################
                   15300: ############################################################
1.154     albertel 15301: 
1.655     raeburn  15302: =pod
                   15303: 
                   15304: =head1 Course Catalog Routines
                   15305: 
                   15306: =over 4
                   15307: 
                   15308: =item * &gather_categories()
                   15309: 
                   15310: Converts category definitions - keys of categories hash stored in  
                   15311: coursecategories in configuration.db on the primary library server in a 
                   15312: domain - to an array.  Also generates javascript and idx hash used to 
                   15313: generate Domain Coordinator interface for editing Course Categories.
                   15314: 
                   15315: Inputs:
1.663     raeburn  15316: 
1.655     raeburn  15317: categories (reference to hash of category definitions).
1.663     raeburn  15318: 
1.655     raeburn  15319: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15320:       categories and subcategories).
1.663     raeburn  15321: 
1.655     raeburn  15322: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15323:       editing Course Categories).
1.663     raeburn  15324: 
1.655     raeburn  15325: jsarray (reference to array of categories used to create Javascript arrays for
                   15326:          Domain Coordinator interface for editing Course Categories).
                   15327: 
                   15328: Returns: nothing
                   15329: 
                   15330: Side effects: populates cats, idx and jsarray. 
                   15331: 
                   15332: =cut
                   15333: 
                   15334: sub gather_categories {
                   15335:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15336:     my %counters;
                   15337:     my $num = 0;
                   15338:     foreach my $item (keys(%{$categories})) {
                   15339:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15340:         if ($container eq '' && $depth == 0) {
                   15341:             $cats->[$depth][$categories->{$item}] = $cat;
                   15342:         } else {
                   15343:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15344:         }
                   15345:         my ($escitem,$tail) = split(/:/,$item,2);
                   15346:         if ($counters{$tail} eq '') {
                   15347:             $counters{$tail} = $num;
                   15348:             $num ++;
                   15349:         }
                   15350:         if (ref($idx) eq 'HASH') {
                   15351:             $idx->{$item} = $counters{$tail};
                   15352:         }
                   15353:         if (ref($jsarray) eq 'ARRAY') {
                   15354:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15355:         }
                   15356:     }
                   15357:     return;
                   15358: }
                   15359: 
                   15360: =pod
                   15361: 
                   15362: =item * &extract_categories()
                   15363: 
                   15364: Used to generate breadcrumb trails for course categories.
                   15365: 
                   15366: Inputs:
1.663     raeburn  15367: 
1.655     raeburn  15368: categories (reference to hash of category definitions).
1.663     raeburn  15369: 
1.655     raeburn  15370: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15371:       categories and subcategories).
1.663     raeburn  15372: 
1.655     raeburn  15373: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15374: 
1.655     raeburn  15375: allitems (reference to hash - key is category key 
                   15376:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15377: 
1.655     raeburn  15378: idx (reference to hash of counters used in Domain Coordinator interface for
                   15379:       editing Course Categories).
1.663     raeburn  15380: 
1.655     raeburn  15381: jsarray (reference to array of categories used to create Javascript arrays for
                   15382:          Domain Coordinator interface for editing Course Categories).
                   15383: 
1.665     raeburn  15384: subcats (reference to hash of arrays containing all subcategories within each 
                   15385:          category, -recursive)
                   15386: 
1.1075.2.132  raeburn  15387: maxd (reference to hash used to hold max depth for all top-level categories).
                   15388: 
1.655     raeburn  15389: Returns: nothing
                   15390: 
                   15391: Side effects: populates trails and allitems hash references.
                   15392: 
                   15393: =cut
                   15394: 
                   15395: sub extract_categories {
1.1075.2.132  raeburn  15396:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15397:     if (ref($categories) eq 'HASH') {
                   15398:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15399:         if (ref($cats->[0]) eq 'ARRAY') {
                   15400:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15401:                 my $name = $cats->[0][$i];
                   15402:                 my $item = &escape($name).'::0';
                   15403:                 my $trailstr;
                   15404:                 if ($name eq 'instcode') {
                   15405:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15406:                 } elsif ($name eq 'communities') {
                   15407:                     $trailstr = &mt('Communities');
1.655     raeburn  15408:                 } else {
                   15409:                     $trailstr = $name;
                   15410:                 }
                   15411:                 if ($allitems->{$item} eq '') {
                   15412:                     push(@{$trails},$trailstr);
                   15413:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15414:                 }
                   15415:                 my @parents = ($name);
                   15416:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15417:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15418:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15419:                         if (ref($subcats) eq 'HASH') {
                   15420:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15421:                         }
1.1075.2.132  raeburn  15422:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15423:                     }
                   15424:                 } else {
                   15425:                     if (ref($subcats) eq 'HASH') {
                   15426:                         $subcats->{$item} = [];
1.655     raeburn  15427:                     }
1.1075.2.132  raeburn  15428:                     if (ref($maxd) eq 'HASH') {
                   15429:                         $maxd->{$name} = 1;
                   15430:                     }
1.655     raeburn  15431:                 }
                   15432:             }
                   15433:         }
                   15434:     }
                   15435:     return;
                   15436: }
                   15437: 
                   15438: =pod
                   15439: 
1.1075.2.56  raeburn  15440: =item * &recurse_categories()
1.655     raeburn  15441: 
                   15442: Recursively used to generate breadcrumb trails for course categories.
                   15443: 
                   15444: Inputs:
1.663     raeburn  15445: 
1.655     raeburn  15446: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15447:       categories and subcategories).
1.663     raeburn  15448: 
1.655     raeburn  15449: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15450: 
                   15451: category (current course category, for which breadcrumb trail is being generated).
                   15452: 
                   15453: trails (reference to array of breadcrumb trails for each category).
                   15454: 
1.655     raeburn  15455: allitems (reference to hash - key is category key
                   15456:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15457: 
1.655     raeburn  15458: parents (array containing containers directories for current category, 
                   15459:          back to top level). 
                   15460: 
                   15461: Returns: nothing
                   15462: 
                   15463: Side effects: populates trails and allitems hash references
                   15464: 
                   15465: =cut
                   15466: 
                   15467: sub recurse_categories {
1.1075.2.132  raeburn  15468:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15469:     my $shallower = $depth - 1;
                   15470:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15471:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15472:             my $name = $cats->[$depth]{$category}[$k];
                   15473:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 15474:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15475:             if ($allitems->{$item} eq '') {
                   15476:                 push(@{$trails},$trailstr);
                   15477:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15478:             }
                   15479:             my $deeper = $depth+1;
                   15480:             push(@{$parents},$category);
1.665     raeburn  15481:             if (ref($subcats) eq 'HASH') {
                   15482:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15483:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15484:                     my $higher;
                   15485:                     if ($j > 0) {
                   15486:                         $higher = &escape($parents->[$j]).':'.
                   15487:                                   &escape($parents->[$j-1]).':'.$j;
                   15488:                     } else {
                   15489:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15490:                     }
                   15491:                     push(@{$subcats->{$higher}},$subcat);
                   15492:                 }
                   15493:             }
                   15494:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  15495:                                 $subcats,$maxd);
1.655     raeburn  15496:             pop(@{$parents});
                   15497:         }
                   15498:     } else {
                   15499:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  15500:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15501:         if ($allitems->{$item} eq '') {
                   15502:             push(@{$trails},$trailstr);
                   15503:             $allitems->{$item} = scalar(@{$trails})-1;
                   15504:         }
1.1075.2.132  raeburn  15505:         if (ref($maxd) eq 'HASH') {
                   15506:             if ($depth > $maxd->{$parents->[0]}) {
                   15507:                 $maxd->{$parents->[0]} = $depth;
                   15508:             }
                   15509:         }
1.655     raeburn  15510:     }
                   15511:     return;
                   15512: }
                   15513: 
1.663     raeburn  15514: =pod
                   15515: 
1.1075.2.56  raeburn  15516: =item * &assign_categories_table()
1.663     raeburn  15517: 
                   15518: Create a datatable for display of hierarchical categories in a domain,
                   15519: with checkboxes to allow a course to be categorized. 
                   15520: 
                   15521: Inputs:
                   15522: 
                   15523: cathash - reference to hash of categories defined for the domain (from
                   15524:           configuration.db)
                   15525: 
                   15526: currcat - scalar with an & separated list of categories assigned to a course. 
                   15527: 
1.919     raeburn  15528: type    - scalar contains course type (Course or Community).
                   15529: 
1.1075.2.117  raeburn  15530: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15531:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15532: 
1.663     raeburn  15533: Returns: $output (markup to be displayed) 
                   15534: 
                   15535: =cut
                   15536: 
                   15537: sub assign_categories_table {
1.1075.2.117  raeburn  15538:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15539:     my $output;
                   15540:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  15541:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15542:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15543:         $maxdepth = scalar(@cats);
                   15544:         if (@cats > 0) {
                   15545:             my $itemcount = 0;
                   15546:             if (ref($cats[0]) eq 'ARRAY') {
                   15547:                 my @currcategories;
                   15548:                 if ($currcat ne '') {
                   15549:                     @currcategories = split('&',$currcat);
                   15550:                 }
1.919     raeburn  15551:                 my $table;
1.663     raeburn  15552:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15553:                     my $parent = $cats[0][$i];
1.919     raeburn  15554:                     next if ($parent eq 'instcode');
                   15555:                     if ($type eq 'Community') {
                   15556:                         next unless ($parent eq 'communities');
                   15557:                     } else {
                   15558:                         next if ($parent eq 'communities');
                   15559:                     }
1.663     raeburn  15560:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15561:                     my $item = &escape($parent).'::0';
                   15562:                     my $checked = '';
                   15563:                     if (@currcategories > 0) {
                   15564:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15565:                             $checked = ' checked="checked"';
1.663     raeburn  15566:                         }
                   15567:                     }
1.919     raeburn  15568:                     my $parent_title = $parent;
                   15569:                     if ($parent eq 'communities') {
                   15570:                         $parent_title = &mt('Communities');
                   15571:                     }
                   15572:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15573:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15574:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15575:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15576:                     my $depth = 1;
                   15577:                     push(@path,$parent);
1.1075.2.117  raeburn  15578:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15579:                     pop(@path);
1.919     raeburn  15580:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15581:                     $itemcount ++;
                   15582:                 }
1.919     raeburn  15583:                 if ($itemcount) {
                   15584:                     $output = &Apache::loncommon::start_data_table().
                   15585:                               $table.
                   15586:                               &Apache::loncommon::end_data_table();
                   15587:                 }
1.663     raeburn  15588:             }
                   15589:         }
                   15590:     }
                   15591:     return $output;
                   15592: }
                   15593: 
                   15594: =pod
                   15595: 
1.1075.2.56  raeburn  15596: =item * &assign_category_rows()
1.663     raeburn  15597: 
                   15598: Create a datatable row for display of nested categories in a domain,
                   15599: with checkboxes to allow a course to be categorized,called recursively.
                   15600: 
                   15601: Inputs:
                   15602: 
                   15603: itemcount - track row number for alternating colors
                   15604: 
                   15605: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15606:       categories and subcategories.
                   15607: 
                   15608: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15609: 
                   15610: parent - parent of current category item
                   15611: 
                   15612: path - Array containing all categories back up through the hierarchy from the
                   15613:        current category to the top level.
                   15614: 
                   15615: currcategories - reference to array of current categories assigned to the course
                   15616: 
1.1075.2.117  raeburn  15617: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15618:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15619: 
1.663     raeburn  15620: Returns: $output (markup to be displayed).
                   15621: 
                   15622: =cut
                   15623: 
                   15624: sub assign_category_rows {
1.1075.2.117  raeburn  15625:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15626:     my ($text,$name,$item,$chgstr);
                   15627:     if (ref($cats) eq 'ARRAY') {
                   15628:         my $maxdepth = scalar(@{$cats});
                   15629:         if (ref($cats->[$depth]) eq 'HASH') {
                   15630:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15631:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15632:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  15633:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15634:                 for (my $j=0; $j<$numchildren; $j++) {
                   15635:                     $name = $cats->[$depth]{$parent}[$j];
                   15636:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15637:                     my $deeper = $depth+1;
                   15638:                     my $checked = '';
                   15639:                     if (ref($currcategories) eq 'ARRAY') {
                   15640:                         if (@{$currcategories} > 0) {
                   15641:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15642:                                 $checked = ' checked="checked"';
1.663     raeburn  15643:                             }
                   15644:                         }
                   15645:                     }
1.664     raeburn  15646:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15647:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15648:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15649:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15650:                              '</td><td>';
1.663     raeburn  15651:                     if (ref($path) eq 'ARRAY') {
                   15652:                         push(@{$path},$name);
1.1075.2.117  raeburn  15653:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15654:                         pop(@{$path});
                   15655:                     }
                   15656:                     $text .= '</td></tr>';
                   15657:                 }
                   15658:                 $text .= '</table></td>';
                   15659:             }
                   15660:         }
                   15661:     }
                   15662:     return $text;
                   15663: }
                   15664: 
1.1075.2.69  raeburn  15665: =pod
                   15666: 
                   15667: =back
                   15668: 
                   15669: =cut
                   15670: 
1.655     raeburn  15671: ############################################################
                   15672: ############################################################
                   15673: 
                   15674: 
1.443     albertel 15675: sub commit_customrole {
1.664     raeburn  15676:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15677:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15678:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15679:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15680:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15681:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15682:                  '</b><br />';
                   15683:     return $output;
                   15684: }
                   15685: 
                   15686: sub commit_standardrole {
1.1075.2.31  raeburn  15687:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15688:     my ($output,$logmsg,$linefeed);
                   15689:     if ($context eq 'auto') {
                   15690:         $linefeed = "\n";
                   15691:     } else {
                   15692:         $linefeed = "<br />\n";
                   15693:     }  
1.443     albertel 15694:     if ($three eq 'st') {
1.541     raeburn  15695:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  15696:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15697:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15698:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15699:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15700:         } else {
1.541     raeburn  15701:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15702:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15703:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15704:             if ($context eq 'auto') {
                   15705:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15706:             } else {
                   15707:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15708:                &mt('Add to classlist').': <b>ok</b>';
                   15709:             }
                   15710:             $output .= $linefeed;
1.443     albertel 15711:         }
                   15712:     } else {
                   15713:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15714:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15715:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15716:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15717:         if ($context eq 'auto') {
                   15718:             $output .= $result.$linefeed;
                   15719:         } else {
                   15720:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15721:         }
1.443     albertel 15722:     }
                   15723:     return $output;
                   15724: }
                   15725: 
                   15726: sub commit_studentrole {
1.1075.2.31  raeburn  15727:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15728:         $credits) = @_;
1.626     raeburn  15729:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15730:     if ($context eq 'auto') {
                   15731:         $linefeed = "\n";
                   15732:     } else {
                   15733:         $linefeed = '<br />'."\n";
                   15734:     }
1.443     albertel 15735:     if (defined($one) && defined($two)) {
                   15736:         my $cid=$one.'_'.$two;
                   15737:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15738:         my $secchange = 0;
                   15739:         my $expire_role_result;
                   15740:         my $modify_section_result;
1.628     raeburn  15741:         if ($oldsec ne '-1') { 
                   15742:             if ($oldsec ne $sec) {
1.443     albertel 15743:                 $secchange = 1;
1.628     raeburn  15744:                 my $now = time;
1.443     albertel 15745:                 my $uurl='/'.$cid;
                   15746:                 $uurl=~s/\_/\//g;
                   15747:                 if ($oldsec) {
                   15748:                     $uurl.='/'.$oldsec;
                   15749:                 }
1.626     raeburn  15750:                 $oldsecurl = $uurl;
1.628     raeburn  15751:                 $expire_role_result = 
1.652     raeburn  15752:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15753:                 if ($env{'request.course.sec'} ne '') { 
                   15754:                     if ($expire_role_result eq 'refused') {
                   15755:                         my @roles = ('st');
                   15756:                         my @statuses = ('previous');
                   15757:                         my @roledoms = ($one);
                   15758:                         my $withsec = 1;
                   15759:                         my %roleshash = 
                   15760:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15761:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15762:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15763:                             my ($oldstart,$oldend) = 
                   15764:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15765:                             if ($oldend > 0 && $oldend <= $now) {
                   15766:                                 $expire_role_result = 'ok';
                   15767:                             }
                   15768:                         }
                   15769:                     }
                   15770:                 }
1.443     albertel 15771:                 $result = $expire_role_result;
                   15772:             }
                   15773:         }
                   15774:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15775:             $modify_section_result = 
                   15776:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15777:                                                            undef,undef,undef,$sec,
                   15778:                                                            $end,$start,'','',$cid,
                   15779:                                                            '',$context,$credits);
1.443     albertel 15780:             if ($modify_section_result =~ /^ok/) {
                   15781:                 if ($secchange == 1) {
1.628     raeburn  15782:                     if ($sec eq '') {
                   15783:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15784:                     } else {
                   15785:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15786:                     }
1.443     albertel 15787:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15788:                     if ($sec eq '') {
                   15789:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15790:                     } else {
                   15791:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15792:                     }
1.443     albertel 15793:                 } else {
1.628     raeburn  15794:                     if ($sec eq '') {
                   15795:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15796:                     } else {
                   15797:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15798:                     }
1.443     albertel 15799:                 }
                   15800:             } else {
1.628     raeburn  15801:                 if ($secchange) {       
                   15802:                     $$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;
                   15803:                 } else {
                   15804:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15805:                 }
1.443     albertel 15806:             }
                   15807:             $result = $modify_section_result;
                   15808:         } elsif ($secchange == 1) {
1.628     raeburn  15809:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15810:                 $$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  15811:             } else {
                   15812:                 $$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;
                   15813:             }
1.626     raeburn  15814:             if ($expire_role_result eq 'refused') {
                   15815:                 my $newsecurl = '/'.$cid;
                   15816:                 $newsecurl =~ s/\_/\//g;
                   15817:                 if ($sec ne '') {
                   15818:                     $newsecurl.='/'.$sec;
                   15819:                 }
                   15820:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15821:                     if ($sec eq '') {
                   15822:                         $$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;
                   15823:                     } else {
                   15824:                         $$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;
                   15825:                     }
                   15826:                 }
                   15827:             }
1.443     albertel 15828:         }
                   15829:     } else {
1.626     raeburn  15830:         $$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 15831:         $result = "error: incomplete course id\n";
                   15832:     }
                   15833:     return $result;
                   15834: }
                   15835: 
1.1075.2.25  raeburn  15836: sub show_role_extent {
                   15837:     my ($scope,$context,$role) = @_;
                   15838:     $scope =~ s{^/}{};
                   15839:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15840:     push(@courseroles,'co');
                   15841:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15842:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15843:         $scope =~ s{/}{_};
                   15844:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15845:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15846:         my ($audom,$auname) = split(/\//,$scope);
                   15847:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15848:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15849:     } else {
                   15850:         $scope =~ s{/$}{};
                   15851:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15852:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15853:     }
                   15854: }
                   15855: 
1.443     albertel 15856: ############################################################
                   15857: ############################################################
                   15858: 
1.566     albertel 15859: sub check_clone {
1.578     raeburn  15860:     my ($args,$linefeed) = @_;
1.566     albertel 15861:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15862:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15863:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 15864:21):     my $clonetitle;
                   15865:21):     my @clonemsg;
1.566     albertel 15866:     my $can_clone = 0;
1.944     raeburn  15867:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15868:     if ($lctype ne 'community') {
                   15869:         $lctype = 'course';
                   15870:     }
1.566     albertel 15871:     if ($clonehome eq 'no_host') {
1.944     raeburn  15872:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15873:21):             push(@clonemsg,({
                   15874:21):                               mt => 'No new community created.',
                   15875:21):                               args => [],
                   15876:21):                             },
                   15877:21):                             {
                   15878:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15879:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15880:21):                             }));
1.908     raeburn  15881:         } else {
1.1075.2.161.  .1(raebu 15882:21):             push(@clonemsg,({
                   15883:21):                               mt => 'No new course created.',
                   15884:21):                               args => [],
                   15885:21):                             },
                   15886:21):                             {
                   15887:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15888:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15889:21):                             }));
                   15890:21):         }
1.566     albertel 15891:     } else {
                   15892: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 15893:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15894:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15895:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 15896:21):                 push(@clonemsg,({
                   15897:21):                                   mt => 'No new community created.',
                   15898:21):                                   args => [],
                   15899:21):                                 },
                   15900:21):                                 {
                   15901:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15902:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15903:21):                                 }));
                   15904:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15905:             }
                   15906:         }
1.1075.2.119  raeburn  15907: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15908:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15909: 	    $can_clone = 1;
                   15910: 	} else {
1.1075.2.95  raeburn  15911: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15912: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15913:             if ($clonehash{'cloners'} eq '') {
                   15914:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15915:                 if ($domdefs{'canclone'}) {
                   15916:                     unless ($domdefs{'canclone'} eq 'none') {
                   15917:                         if ($domdefs{'canclone'} eq 'domain') {
                   15918:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15919:                                 $can_clone = 1;
                   15920:                             }
                   15921:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15922:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15923:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15924:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15925:                                 $can_clone = 1;
                   15926:                             }
                   15927:                         }
                   15928:                     }
1.908     raeburn  15929:                 }
1.1075.2.95  raeburn  15930:             } else {
                   15931: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15932:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15933:                     $can_clone = 1;
1.1075.2.95  raeburn  15934:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15935:                     $can_clone = 1;
1.1075.2.96  raeburn  15936:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15937:                     $can_clone = 1;
1.1075.2.95  raeburn  15938:                 }
                   15939:                 unless ($can_clone) {
1.1075.2.96  raeburn  15940:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15941:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15942:                         my (%gotdomdefaults,%gotcodedefaults);
                   15943:                         foreach my $cloner (@cloners) {
                   15944:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15945:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15946:                                 my (%codedefaults,@code_order);
                   15947:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15948:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15949:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15950:                                     }
                   15951:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15952:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15953:                                     }
                   15954:                                 } else {
                   15955:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15956:                                                                             \%codedefaults,
                   15957:                                                                             \@code_order);
                   15958:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15959:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15960:                                 }
                   15961:                                 if (@code_order > 0) {
                   15962:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15963:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15964:                                                                                 $args->{'crscode'})) {
                   15965:                                         $can_clone = 1;
                   15966:                                         last;
                   15967:                                     }
                   15968:                                 }
                   15969:                             }
                   15970:                         }
                   15971:                     }
1.1075.2.96  raeburn  15972:                 }
                   15973:             }
                   15974:             unless ($can_clone) {
                   15975:                 my $ccrole = 'cc';
                   15976:                 if ($args->{'crstype'} eq 'Community') {
                   15977:                     $ccrole = 'co';
                   15978:                 }
                   15979:                 my %roleshash =
                   15980:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15981:                                                   $args->{'ccdomain'},
                   15982:                                                   'userroles',['active'],[$ccrole],
                   15983:                                                   [$args->{'clonedomain'}]);
                   15984:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15985:                     $can_clone = 1;
                   15986:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15987:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15988:                     $can_clone = 1;
1.1075.2.95  raeburn  15989:                 }
                   15990:             }
                   15991:             unless ($can_clone) {
                   15992:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15993:21):                     push(@clonemsg,({
                   15994:21):                                       mt => 'No new community created.',
                   15995:21):                                       args => [],
                   15996:21):                                     },
                   15997:21):                                     {
                   15998:21):                                       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]).',
                   15999:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16000:21):                                     }));
1.1075.2.95  raeburn  16001:                 } else {
1.1075.2.161.  .1(raebu 16002:21):                     push(@clonemsg,({
                   16003:21):                                       mt => 'No new course created.',
                   16004:21):                                       args => [],
                   16005:21):                                     },
                   16006:21):                                     {
                   16007:21):                                       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]).',
                   16008:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16009:21):                                     }));
1.578     raeburn  16010: 	        }
1.566     albertel 16011: 	    }
1.578     raeburn  16012:         }
1.566     albertel 16013:     }
1.1075.2.161.  .1(raebu 16014:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16015: }
                   16016: 
1.444     albertel 16017: sub construct_course {
1.1075.2.119  raeburn  16018:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16019:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16020:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16021:     my $linefeed =  '<br />'."\n";
                   16022:     if ($context eq 'auto') {
                   16023:         $linefeed = "\n";
                   16024:     }
1.566     albertel 16025: 
                   16026: #
                   16027: # Are we cloning?
                   16028: #
1.1075.2.161.  .1(raebu 16029:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16030:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16031:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16032:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16033:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16034: 	}
                   16035:     }
                   16036: 
1.444     albertel 16037: #
                   16038: # Open course
                   16039: #
                   16040:     my $crstype = lc($args->{'crstype'});
                   16041:     my %cenv=();
                   16042:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16043:                                              $args->{'cdescr'},
                   16044:                                              $args->{'curl'},
                   16045:                                              $args->{'course_home'},
                   16046:                                              $args->{'nonstandard'},
                   16047:                                              $args->{'crscode'},
                   16048:                                              $args->{'ccuname'}.':'.
                   16049:                                              $args->{'ccdomain'},
1.882     raeburn  16050:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16051:21):                                              $cnum,$context,$category,
                   16052:21):                                              $callercontext);
1.444     albertel 16053: 
                   16054:     # Note: The testing routines depend on this being output; see 
                   16055:     # Utils::Course. This needs to at least be output as a comment
                   16056:     # if anyone ever decides to not show this, and Utils::Course::new
                   16057:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16058:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16059:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16060:21):     } else {
                   16061:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16062:21):     }
1.943     raeburn  16063:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16064:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16065:     }
                   16066: 
1.444     albertel 16067: #
                   16068: # Check if created correctly
                   16069: #
1.479     albertel 16070:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16071:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16072:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16073:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16074:21):             $outcome .= &mt_user($user_lh,
                   16075:21):                             'Course creation failed, unrecognized course home server.');
                   16076:21):         } else {
                   16077:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16078:21):         }
                   16079:21):         $outcome .= $linefeed;
                   16080:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16081:     }
1.541     raeburn  16082:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16083: 
1.444     albertel 16084: #
1.566     albertel 16085: # Do the cloning
1.1075.2.161.  .1(raebu 16086:21): #
                   16087:21):     my @clonemsg;
1.566     albertel 16088:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16089:21):         push(@clonemsg,
                   16090:21):                       {
                   16091:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16092:21):                           args => [$crstype,$clonetitle],
                   16093:21):                       });
1.566     albertel 16094: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16095: # Copy all files
1.1075.2.161.  .1(raebu 16096:21):         my @info =
                   16097:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16098:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16099:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16100:21):                                                      $args->{'tinyurls'});
                   16101:21):         if (@info) {
                   16102:21):             push(@clonemsg,@info);
                   16103:21):         }
1.444     albertel 16104: # Restore URL
1.566     albertel 16105: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16106: # Restore title
1.566     albertel 16107: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16108: # Restore creation date, creator and creation context.
                   16109:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16110:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16111:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16112: # Mark as cloned
1.566     albertel 16113: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16114: # Need to clone grading mode
                   16115:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16116:         $cenv{'grading'}=$newenv{'grading'};
                   16117: # Do not clone these environment entries
                   16118:         &Apache::lonnet::del('environment',
                   16119:                   ['default_enrollment_start_date',
                   16120:                    'default_enrollment_end_date',
                   16121:                    'question.email',
                   16122:                    'policy.email',
                   16123:                    'comment.email',
                   16124:                    'pch.users.denied',
1.725     raeburn  16125:                    'plc.users.denied',
                   16126:                    'hidefromcat',
1.1075.2.36  raeburn  16127:                    'checkforpriv',
1.1075.2.158  raeburn  16128:                    'categories'],
1.638     www      16129:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16130:         if ($args->{'textbook'}) {
                   16131:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16132:         }
1.444     albertel 16133:     }
1.566     albertel 16134: 
1.444     albertel 16135: #
                   16136: # Set environment (will override cloned, if existing)
                   16137: #
                   16138:     my @sections = ();
                   16139:     my @xlists = ();
                   16140:     if ($args->{'crstype'}) {
                   16141:         $cenv{'type'}=$args->{'crstype'};
                   16142:     }
                   16143:     if ($args->{'crsid'}) {
                   16144:         $cenv{'courseid'}=$args->{'crsid'};
                   16145:     }
                   16146:     if ($args->{'crscode'}) {
                   16147:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16148:     }
                   16149:     if ($args->{'crsquota'} ne '') {
                   16150:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16151:     } else {
                   16152:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16153:     }
                   16154:     if ($args->{'ccuname'}) {
                   16155:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16156:                                         ':'.$args->{'ccdomain'};
                   16157:     } else {
                   16158:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16159:     }
1.1075.2.31  raeburn  16160:     if ($args->{'defaultcredits'}) {
                   16161:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16162:     }
1.444     albertel 16163:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16164:     if ($args->{'crssections'}) {
                   16165:         $cenv{'internal.sectionnums'} = '';
                   16166:         if ($args->{'crssections'} =~ m/,/) {
                   16167:             @sections = split/,/,$args->{'crssections'};
                   16168:         } else {
                   16169:             $sections[0] = $args->{'crssections'};
                   16170:         }
                   16171:         if (@sections > 0) {
                   16172:             foreach my $item (@sections) {
                   16173:                 my ($sec,$gp) = split/:/,$item;
                   16174:                 my $class = $args->{'crscode'}.$sec;
                   16175:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16176:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16177:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16178:                     push(@badclasses,$class);
1.444     albertel 16179:                 }
                   16180:             }
                   16181:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16182:         }
                   16183:     }
                   16184: # do not hide course coordinator from staff listing, 
                   16185: # even if privileged
                   16186:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16187: # add course coordinator's domain to domains to check for privileged users
                   16188: # if different to course domain
                   16189:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16190:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16191:     }
1.444     albertel 16192: # add crosslistings
                   16193:     if ($args->{'crsxlist'}) {
                   16194:         $cenv{'internal.crosslistings'}='';
                   16195:         if ($args->{'crsxlist'} =~ m/,/) {
                   16196:             @xlists = split/,/,$args->{'crsxlist'};
                   16197:         } else {
                   16198:             $xlists[0] = $args->{'crsxlist'};
                   16199:         }
                   16200:         if (@xlists > 0) {
                   16201:             foreach my $item (@xlists) {
                   16202:                 my ($xl,$gp) = split/:/,$item;
                   16203:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16204:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16205:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16206:                     push(@badclasses,$xl);
1.444     albertel 16207:                 }
                   16208:             }
                   16209:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16210:         }
                   16211:     }
                   16212:     if ($args->{'autoadds'}) {
                   16213:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16214:     }
                   16215:     if ($args->{'autodrops'}) {
                   16216:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16217:     }
                   16218: # check for notification of enrollment changes
                   16219:     my @notified = ();
                   16220:     if ($args->{'notify_owner'}) {
                   16221:         if ($args->{'ccuname'} ne '') {
                   16222:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16223:         }
                   16224:     }
                   16225:     if ($args->{'notify_dc'}) {
                   16226:         if ($uname ne '') { 
1.630     raeburn  16227:             push(@notified,$uname.':'.$udom);
1.444     albertel 16228:         }
                   16229:     }
                   16230:     if (@notified > 0) {
                   16231:         my $notifylist;
                   16232:         if (@notified > 1) {
                   16233:             $notifylist = join(',',@notified);
                   16234:         } else {
                   16235:             $notifylist = $notified[0];
                   16236:         }
                   16237:         $cenv{'internal.notifylist'} = $notifylist;
                   16238:     }
                   16239:     if (@badclasses > 0) {
                   16240:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16241:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16242:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16243:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16244:         );
1.1075.2.119  raeburn  16245:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16246:                            &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  16247:         if ($context eq 'auto') {
                   16248:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16249:         } else {
1.566     albertel 16250:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16251:         }
                   16252:         foreach my $item (@badclasses) {
1.541     raeburn  16253:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16254:                 $outcome .= " - $item\n";
1.541     raeburn  16255:             } else {
1.1075.2.119  raeburn  16256:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16257:             }
1.1075.2.119  raeburn  16258:         }
                   16259:         if ($context eq 'auto') {
                   16260:             $outcome .= $linefeed;
                   16261:         } else {
                   16262:             $outcome .= "</ul><br /><br /></div>\n";
                   16263:         }
1.444     albertel 16264:     }
                   16265:     if ($args->{'no_end_date'}) {
                   16266:         $args->{'endaccess'} = 0;
                   16267:     }
                   16268:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16269:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16270:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16271:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16272:     if ($args->{'showphotos'}) {
                   16273:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16274:     }
                   16275:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16276:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16277:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16278:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16279:             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'); 
                   16280:             if ($context eq 'auto') {
                   16281:                 $outcome .= $krb_msg;
                   16282:             } else {
1.566     albertel 16283:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16284:             }
                   16285:             $outcome .= $linefeed;
1.444     albertel 16286:         }
                   16287:     }
                   16288:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16289:        if ($args->{'setpolicy'}) {
                   16290:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16291:        }
                   16292:        if ($args->{'setcontent'}) {
                   16293:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16294:        }
1.1075.2.110  raeburn  16295:        if ($args->{'setcomment'}) {
                   16296:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16297:        }
1.444     albertel 16298:     }
                   16299:     if ($args->{'reshome'}) {
                   16300: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16301: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16302:     }
                   16303: #
                   16304: # course has keyed access
                   16305: #
                   16306:     if ($args->{'setkeys'}) {
                   16307:        $cenv{'keyaccess'}='yes';
                   16308:     }
                   16309: # if specified, key authority is not course, but user
                   16310: # only active if keyaccess is yes
                   16311:     if ($args->{'keyauth'}) {
1.487     albertel 16312: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16313: 	$user = &LONCAPA::clean_username($user);
                   16314: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16315: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16316: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16317: 	}
                   16318:     }
                   16319: 
1.1075.2.59  raeburn  16320: #
                   16321: #  generate and store uniquecode (available to course requester), if course should have one.
                   16322: #
                   16323:     if ($args->{'uniquecode'}) {
                   16324:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16325:         if ($code) {
                   16326:             $cenv{'internal.uniquecode'} = $code;
                   16327:             my %crsinfo =
                   16328:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16329:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16330:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16331:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16332:             }
                   16333:             if (ref($coderef)) {
                   16334:                 $$coderef = $code;
                   16335:             }
                   16336:         }
                   16337:     }
                   16338: 
1.444     albertel 16339:     if ($args->{'disresdis'}) {
                   16340:         $cenv{'pch.roles.denied'}='st';
                   16341:     }
                   16342:     if ($args->{'disablechat'}) {
                   16343:         $cenv{'plc.roles.denied'}='st';
                   16344:     }
                   16345: 
                   16346:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16347:     # course
                   16348:     $cenv{'course.helper.not.run'} = 1;
                   16349:     #
                   16350:     # Use new Randomseed
                   16351:     #
                   16352:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16353:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16354:     #
                   16355:     # The encryption code and receipt prefix for this course
                   16356:     #
                   16357:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16358:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16359:     #
                   16360:     # By default, use standard grading
                   16361:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16362: 
1.541     raeburn  16363:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16364:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16365: #
                   16366: # Open all assignments
                   16367: #
                   16368:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16369:        my $opendate = time;
                   16370:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16371:            $opendate = $args->{'openallfrom'};
                   16372:        }
1.444     albertel 16373:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16374:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16375:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16376:        $outcome .= &mt('All assignments open starting [_1]',
                   16377:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16378:                    &Apache::lonnet::cput
                   16379:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16380:    }
                   16381: #
                   16382: # Set first page
                   16383: #
                   16384:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16385: 	    || ($cloneid)) {
1.445     albertel 16386: 	use LONCAPA::map;
1.444     albertel 16387: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16388: 
                   16389: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16390:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16391: 
1.444     albertel 16392:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16393:         my $title; my $url;
                   16394:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16395: 	    $title=&mt('Syllabus');
1.444     albertel 16396:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16397:         } else {
1.963     raeburn  16398:             $title=&mt('Table of Contents');
1.444     albertel 16399:             $url='/adm/navmaps';
                   16400:         }
1.445     albertel 16401: 
                   16402:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16403: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16404: 
                   16405: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16406:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16407:     }
1.566     albertel 16408: 
1.1075.2.161.  .1(raebu 16409:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16410: }
                   16411: 
1.1075.2.59  raeburn  16412: sub make_unique_code {
                   16413:     my ($cdom,$cnum) = @_;
                   16414:     # get lock on uniquecodes db
                   16415:     my $lockhash = {
                   16416:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16417:                                                   ':'.$env{'user.domain'},
                   16418:                    };
                   16419:     my $tries = 0;
                   16420:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16421:     my ($code,$error);
                   16422: 
                   16423:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16424:         $tries ++;
                   16425:         sleep 1;
                   16426:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16427:     }
                   16428:     if ($gotlock eq 'ok') {
                   16429:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16430:         my $gotcode;
                   16431:         my $attempts = 0;
                   16432:         while ((!$gotcode) && ($attempts < 100)) {
                   16433:             $code = &generate_code();
                   16434:             if (!exists($currcodes{$code})) {
                   16435:                 $gotcode = 1;
                   16436:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16437:                     $error = 'nostore';
                   16438:                 }
                   16439:             }
                   16440:             $attempts ++;
                   16441:         }
                   16442:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16443:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16444:     } else {
                   16445:         $error = 'nolock';
                   16446:     }
                   16447:     return ($code,$error);
                   16448: }
                   16449: 
                   16450: sub generate_code {
                   16451:     my $code;
                   16452:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16453:     for (my $i=0; $i<6; $i++) {
                   16454:         my $lettnum = int (rand 2);
                   16455:         my $item = '';
                   16456:         if ($lettnum) {
                   16457:             $item = $letts[int( rand(18) )];
                   16458:         } else {
                   16459:             $item = 1+int( rand(8) );
                   16460:         }
                   16461:         $code .= $item;
                   16462:     }
                   16463:     return $code;
                   16464: }
                   16465: 
1.444     albertel 16466: ############################################################
                   16467: ############################################################
                   16468: 
1.953     droeschl 16469: #SD
                   16470: # only Community and Course, or anything else?
1.378     raeburn  16471: sub course_type {
                   16472:     my ($cid) = @_;
                   16473:     if (!defined($cid)) {
                   16474:         $cid = $env{'request.course.id'};
                   16475:     }
1.404     albertel 16476:     if (defined($env{'course.'.$cid.'.type'})) {
                   16477:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16478:     } else {
                   16479:         return 'Course';
1.377     raeburn  16480:     }
                   16481: }
1.156     albertel 16482: 
1.406     raeburn  16483: sub group_term {
                   16484:     my $crstype = &course_type();
                   16485:     my %names = (
                   16486:                   'Course' => 'group',
1.865     raeburn  16487:                   'Community' => 'group',
1.406     raeburn  16488:                 );
                   16489:     return $names{$crstype};
                   16490: }
                   16491: 
1.902     raeburn  16492: sub course_types {
1.1075.2.59  raeburn  16493:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  16494:     my %typename = (
                   16495:                          official   => 'Official course',
                   16496:                          unofficial => 'Unofficial course',
                   16497:                          community  => 'Community',
1.1075.2.59  raeburn  16498:                          textbook   => 'Textbook course',
1.902     raeburn  16499:                    );
                   16500:     return (\@types,\%typename);
                   16501: }
                   16502: 
1.156     albertel 16503: sub icon {
                   16504:     my ($file)=@_;
1.505     albertel 16505:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16506:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16507:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16508:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16509: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16510: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16511: 	            $curfext.".gif") {
                   16512: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16513: 		$curfext.".gif";
                   16514: 	}
                   16515:     }
1.249     albertel 16516:     return &lonhttpdurl($iconname);
1.154     albertel 16517: } 
1.84      albertel 16518: 
1.575     albertel 16519: sub lonhttpdurl {
1.692     www      16520: #
                   16521: # Had been used for "small fry" static images on separate port 8080.
                   16522: # Modify here if lightweight http functionality desired again.
                   16523: # Currently eliminated due to increasing firewall issues.
                   16524: #
1.575     albertel 16525:     my ($url)=@_;
1.692     www      16526:     return $url;
1.215     albertel 16527: }
                   16528: 
1.213     albertel 16529: sub connection_aborted {
                   16530:     my ($r)=@_;
                   16531:     $r->print(" ");$r->rflush();
                   16532:     my $c = $r->connection;
                   16533:     return $c->aborted();
                   16534: }
                   16535: 
1.221     foxr     16536: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16537: #    strings as 'strings'.
                   16538: sub escape_single {
1.221     foxr     16539:     my ($input) = @_;
1.223     albertel 16540:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16541:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16542:     return $input;
                   16543: }
1.223     albertel 16544: 
1.222     foxr     16545: #  Same as escape_single, but escape's "'s  This 
                   16546: #  can be used for  "strings"
                   16547: sub escape_double {
                   16548:     my ($input) = @_;
                   16549:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16550:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16551:     return $input;
                   16552: }
1.223     albertel 16553:  
1.222     foxr     16554: #   Escapes the last element of a full URL.
                   16555: sub escape_url {
                   16556:     my ($url)   = @_;
1.238     raeburn  16557:     my @urlslices = split(/\//, $url,-1);
1.369     www      16558:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  16559:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16560: }
1.462     albertel 16561: 
1.820     raeburn  16562: sub compare_arrays {
                   16563:     my ($arrayref1,$arrayref2) = @_;
                   16564:     my (@difference,%count);
                   16565:     @difference = ();
                   16566:     %count = ();
                   16567:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16568:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16569:         foreach my $element (keys(%count)) {
                   16570:             if ($count{$element} == 1) {
                   16571:                 push(@difference,$element);
                   16572:             }
                   16573:         }
                   16574:     }
                   16575:     return @difference;
                   16576: }
                   16577: 
1.1075.2.152  raeburn  16578: sub lon_status_items {
                   16579:     my %defaults = (
                   16580:                      E         => 100,
                   16581:                      W         => 4,
                   16582:                      N         => 1,
                   16583:                      U         => 5,
                   16584:                      threshold => 200,
                   16585:                      sysmail   => 2500,
                   16586:                    );
                   16587:     my %names = (
                   16588:                    E => 'Errors',
                   16589:                    W => 'Warnings',
                   16590:                    N => 'Notices',
                   16591:                    U => 'Unsent',
                   16592:                 );
                   16593:     return (\%defaults,\%names);
                   16594: }
                   16595: 
1.817     bisitz   16596: # -------------------------------------------------------- Initialize user login
1.462     albertel 16597: sub init_user_environment {
1.463     albertel 16598:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16599:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16600: 
                   16601:     my $public=($username eq 'public' && $domain eq 'public');
                   16602: 
                   16603: # See if old ID present, if so, remove
                   16604: 
1.1062    raeburn  16605:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16606:     my $now=time;
                   16607: 
                   16608:     if ($public) {
                   16609: 	my $max_public=100;
                   16610: 	my $oldest;
                   16611: 	my $oldest_time=0;
                   16612: 	for(my $next=1;$next<=$max_public;$next++) {
                   16613: 	    if (-e $lonids."/publicuser_$next.id") {
                   16614: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16615: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16616: 		    $oldest_time=$mtime;
                   16617: 		    $oldest=$next;
                   16618: 		}
                   16619: 	    } else {
                   16620: 		$cookie="publicuser_$next";
                   16621: 		last;
                   16622: 	    }
                   16623: 	}
                   16624: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16625:     } else {
1.463     albertel 16626: 	# if this isn't a robot, kill any existing non-robot sessions
                   16627: 	if (!$args->{'robot'}) {
                   16628: 	    opendir(DIR,$lonids);
                   16629: 	    while ($filename=readdir(DIR)) {
                   16630: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  16631:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16632:                             &GDBM_READER(),0640)) {
                   16633:                         my $linkedfile;
                   16634:                         if (exists($oldenv{'user.linkedenv'})) {
                   16635:                             $linkedfile = $oldenv{'user.linkedenv'};
                   16636:                         }
                   16637:                         untie(%oldenv);
                   16638:                         if (unlink("$lonids/$filename")) {
                   16639:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16640:                                 if (-l "$lonids/$linkedfile.id") {
                   16641:                                     unlink("$lonids/$linkedfile.id");
                   16642:                                 }
                   16643:                             }
                   16644:                         }
                   16645:                     } else {
                   16646:                         unlink($lonids.'/'.$filename);
                   16647:                     }
1.463     albertel 16648: 		}
1.462     albertel 16649: 	    }
1.463     albertel 16650: 	    closedir(DIR);
1.1075.2.84  raeburn  16651: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16652:             my $namespace = 'nohist_courseeditor';
                   16653:             my $lockingkey = 'paste'."\0".'locked_num';
                   16654:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16655:                                                 $domain,$username);
                   16656:             if (exists($lockhash{$lockingkey})) {
                   16657:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16658:                 unless ($delresult eq 'ok') {
                   16659:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16660:                 }
                   16661:             }
1.462     albertel 16662: 	}
                   16663: # Give them a new cookie
1.463     albertel 16664: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16665: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16666: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16667:     
                   16668: # Initialize roles
                   16669: 
1.1062    raeburn  16670: 	($userroles,$firstaccenv,$timerintenv) = 
                   16671:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16672:     }
                   16673: # ------------------------------------ Check browser type and MathML capability
                   16674: 
1.1075.2.77  raeburn  16675:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16676:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16677: 
                   16678: # ------------------------------------------------------------- Get environment
                   16679: 
                   16680:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16681:     my ($tmp) = keys(%userenv);
                   16682:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   16683:     } else {
                   16684: 	undef(%userenv);
                   16685:     }
                   16686:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16687: 	$form->{'interface'}=$userenv{'interface'};
                   16688:     }
                   16689:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16690: 
                   16691: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16692:     foreach my $option ('interface','localpath','localres') {
                   16693:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16694:     }
                   16695: # --------------------------------------------------------- Write first profile
                   16696: 
                   16697:     {
1.1075.2.150  raeburn  16698:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 16699: 	my %initial_env = 
                   16700: 	    ("user.name"          => $username,
                   16701: 	     "user.domain"        => $domain,
                   16702: 	     "user.home"          => $authhost,
                   16703: 	     "browser.type"       => $clientbrowser,
                   16704: 	     "browser.version"    => $clientversion,
                   16705: 	     "browser.mathml"     => $clientmathml,
                   16706: 	     "browser.unicode"    => $clientunicode,
                   16707: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  16708:              "browser.mobile"     => $clientmobile,
                   16709:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  16710:              "browser.osversion"  => $clientosversion,
1.462     albertel 16711: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16712: 	     "request.course.fn"  => '',
                   16713: 	     "request.course.uri" => '',
                   16714: 	     "request.course.sec" => '',
                   16715: 	     "request.role"       => 'cm',
                   16716: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  16717: 	     "request.host"       => $ip,);
1.462     albertel 16718: 
                   16719:         if ($form->{'localpath'}) {
                   16720: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16721: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16722:         }
                   16723: 	
                   16724: 	if ($form->{'interface'}) {
                   16725: 	    $form->{'interface'}=~s/\W//gs;
                   16726: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16727: 	    $env{'browser.interface'}=$form->{'interface'};
                   16728: 	}
                   16729: 
1.1075.2.54  raeburn  16730:         if ($form->{'iptoken'}) {
                   16731:             my $lonhost = $r->dir_config('lonHostID');
                   16732:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16733:             $env{'user.noloadbalance'} = $lonhost;
                   16734:         }
                   16735: 
1.1075.2.120  raeburn  16736:         if ($form->{'noloadbalance'}) {
                   16737:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16738:             my $hosthere = $form->{'noloadbalance'};
                   16739:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16740:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16741:                 $env{'user.noloadbalance'} = $hosthere;
                   16742:             }
                   16743:         }
                   16744: 
1.1016    raeburn  16745:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  16746:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16747:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  16748: 
1.1075.2.161.  .10(raeb 16749:-22):             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1075.2.125  raeburn  16750:                 $userenv{'availabletools.'.$tool} = 
                   16751:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16752:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16753:             }
1.724     raeburn  16754: 
1.1075.2.125  raeburn  16755:             foreach my $crstype ('official','unofficial','community','textbook') {
                   16756:                 $userenv{'canrequest.'.$crstype} =
                   16757:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16758:                                                       'reload','requestcourses',
                   16759:                                                       \%userenv,\%domdef,\%is_adv);
                   16760:             }
1.765     raeburn  16761: 
1.1075.2.125  raeburn  16762:             $userenv{'canrequest.author'} =
                   16763:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16764:                                                   'reload','requestauthor',
                   16765:                                                   \%userenv,\%domdef,\%is_adv);
                   16766:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16767:                                                  $domain,$username);
                   16768:             my $reqstatus = $reqauthor{'author_status'};
                   16769:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16770:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16771:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16772:                                                       $reqauthor{'author'}{'timestamp'};
                   16773:                 }
1.1075.2.14  raeburn  16774:             }
                   16775:         }
                   16776: 
1.462     albertel 16777: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16778: 
1.462     albertel 16779: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16780: 		 &GDBM_WRCREAT(),0640)) {
                   16781: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16782: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16783: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16784:             if (ref($firstaccenv) eq 'HASH') {
                   16785:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16786:             }
                   16787:             if (ref($timerintenv) eq 'HASH') {
                   16788:                 &_add_to_env(\%disk_env,$timerintenv);
                   16789:             }
1.463     albertel 16790: 	    if (ref($args->{'extra_env'})) {
                   16791: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16792: 	    }
1.462     albertel 16793: 	    untie(%disk_env);
                   16794: 	} else {
1.705     tempelho 16795: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16796: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16797: 	    return 'error: '.$!;
                   16798: 	}
                   16799:     }
                   16800:     $env{'request.role'}='cm';
                   16801:     $env{'request.role.adv'}=$env{'user.adv'};
                   16802:     $env{'browser.type'}=$clientbrowser;
                   16803: 
                   16804:     return $cookie;
                   16805: 
                   16806: }
                   16807: 
                   16808: sub _add_to_env {
                   16809:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16810:     if (ref($env_data) eq 'HASH') {
                   16811:         while (my ($key,$value) = each(%$env_data)) {
                   16812: 	    $idf->{$prefix.$key} = $value;
                   16813: 	    $env{$prefix.$key}   = $value;
                   16814:         }
1.462     albertel 16815:     }
                   16816: }
                   16817: 
1.685     tempelho 16818: # --- Get the symbolic name of a problem and the url
                   16819: sub get_symb {
                   16820:     my ($request,$silent) = @_;
1.726     raeburn  16821:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16822:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16823:     if ($symb eq '') {
                   16824:         if (!$silent) {
1.1071    raeburn  16825:             if (ref($request)) { 
                   16826:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16827:             }
1.685     tempelho 16828:             return ();
                   16829:         }
                   16830:     }
                   16831:     &Apache::lonenc::check_decrypt(\$symb);
                   16832:     return ($symb);
                   16833: }
                   16834: 
                   16835: # --------------------------------------------------------------Get annotation
                   16836: 
                   16837: sub get_annotation {
                   16838:     my ($symb,$enc) = @_;
                   16839: 
                   16840:     my $key = $symb;
                   16841:     if (!$enc) {
                   16842:         $key =
                   16843:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16844:     }
                   16845:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16846:     return $annotation{$key};
                   16847: }
                   16848: 
                   16849: sub clean_symb {
1.731     raeburn  16850:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16851: 
                   16852:     &Apache::lonenc::check_decrypt(\$symb);
                   16853:     my $enc = $env{'request.enc'};
1.731     raeburn  16854:     if ($delete_enc) {
1.730     raeburn  16855:         delete($env{'request.enc'});
                   16856:     }
1.685     tempelho 16857: 
                   16858:     return ($symb,$enc);
                   16859: }
1.462     albertel 16860: 
1.1075.2.69  raeburn  16861: ############################################################
                   16862: ############################################################
                   16863: 
                   16864: =pod
                   16865: 
                   16866: =head1 Routines for building display used to search for courses
                   16867: 
                   16868: 
                   16869: =over 4
                   16870: 
                   16871: =item * &build_filters()
                   16872: 
                   16873: Create markup for a table used to set filters to use when selecting
                   16874: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16875: and quotacheck.pl
                   16876: 
                   16877: 
                   16878: Inputs:
                   16879: 
                   16880: filterlist - anonymous array of fields to include as potential filters
                   16881: 
                   16882: crstype - course type
                   16883: 
                   16884: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16885:               to pop-open a course selector (will contain "extra element").
                   16886: 
                   16887: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16888: 
                   16889: filter - anonymous hash of criteria and their values
                   16890: 
                   16891: action - form action
                   16892: 
                   16893: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16894: 
                   16895: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16896: 
                   16897: cloneruname - username of owner of new course who wants to clone
                   16898: 
                   16899: clonerudom - domain of owner of new course who wants to clone
                   16900: 
                   16901: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16902: 
                   16903: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16904: 
                   16905: codedom - domain
                   16906: 
                   16907: formname - value of form element named "form".
                   16908: 
                   16909: fixeddom - domain, if fixed.
                   16910: 
                   16911: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16912: 
                   16913: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16914: 
                   16915: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16916: 
                   16917: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16918: 
                   16919: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16920: 
                   16921: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16922: 
                   16923: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16924: 
                   16925: 
                   16926: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16927: 
                   16928: 
                   16929: Side Effects: None
                   16930: 
                   16931: =cut
                   16932: 
                   16933: # ---------------------------------------------- search for courses based on last activity etc.
                   16934: 
                   16935: sub build_filters {
                   16936:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16937:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16938:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16939:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16940:         $clonetext,$clonewarning) = @_;
                   16941:     my ($list,$jscript);
                   16942:     my $onchange = 'javascript:updateFilters(this)';
                   16943:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16944:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16945:         $typeselectform,$instcodetitle);
                   16946:     if ($formname eq '') {
                   16947:         $formname = $caller;
                   16948:     }
                   16949:     foreach my $item (@{$filterlist}) {
                   16950:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16951:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16952:             if ($item eq 'domainfilter') {
                   16953:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16954:             } elsif ($item eq 'coursefilter') {
                   16955:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16956:             } elsif ($item eq 'ownerfilter') {
                   16957:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16958:             } elsif ($item eq 'ownerdomfilter') {
                   16959:                 $filter->{'ownerdomfilter'} =
                   16960:                     &LONCAPA::clean_domain($filter->{$item});
                   16961:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16962:                                                        'ownerdomfilter',1);
                   16963:             } elsif ($item eq 'personfilter') {
                   16964:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16965:             } elsif ($item eq 'persondomfilter') {
                   16966:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16967:                                                         'persondomfilter',1);
                   16968:             } else {
                   16969:                 $filter->{$item} =~ s/\W//g;
                   16970:             }
                   16971:             if (!$filter->{$item}) {
                   16972:                 $filter->{$item} = '';
                   16973:             }
                   16974:         }
                   16975:         if ($item eq 'domainfilter') {
                   16976:             my $allow_blank = 1;
                   16977:             if ($formname eq 'portform') {
                   16978:                 $allow_blank=0;
                   16979:             } elsif ($formname eq 'studentform') {
                   16980:                 $allow_blank=0;
                   16981:             }
                   16982:             if ($fixeddom) {
                   16983:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16984:                                     ' value="'.$codedom.'" />'.
                   16985:                                     &Apache::lonnet::domain($codedom,'description');
                   16986:             } else {
                   16987:                 $domainselectform = &select_dom_form($filter->{$item},
                   16988:                                                      'domainfilter',
                   16989:                                                       $allow_blank,'',$onchange);
                   16990:             }
                   16991:         } else {
                   16992:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16993:         }
                   16994:     }
                   16995: 
                   16996:     # last course activity filter and selection
                   16997:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16998: 
                   16999:     # course created filter and selection
                   17000:     if (exists($filter->{'createdfilter'})) {
                   17001:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17002:     }
                   17003: 
                   17004:     my %lt = &Apache::lonlocal::texthash(
                   17005:                 'cac' => "$crstype Activity",
                   17006:                 'ccr' => "$crstype Created",
                   17007:                 'cde' => "$crstype Title",
                   17008:                 'cdo' => "$crstype Domain",
                   17009:                 'ins' => 'Institutional Code',
                   17010:                 'inc' => 'Institutional Categorization',
                   17011:                 'cow' => "$crstype Owner/Co-owner",
                   17012:                 'cop' => "$crstype Personnel Includes",
                   17013:                 'cog' => 'Type',
                   17014:              );
                   17015: 
                   17016:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17017:         my $typeval = 'Course';
                   17018:         if ($crstype eq 'Community') {
                   17019:             $typeval = 'Community';
                   17020:         }
                   17021:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17022:     } else {
                   17023:         $typeselectform =  '<select name="type" size="1"';
                   17024:         if ($onchange) {
                   17025:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17026:         }
                   17027:         $typeselectform .= '>'."\n";
                   17028:         foreach my $posstype ('Course','Community') {
                   17029:             $typeselectform.='<option value="'.$posstype.'"'.
                   17030:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17031:         }
                   17032:         $typeselectform.="</select>";
                   17033:     }
                   17034: 
                   17035:     my ($cloneableonlyform,$cloneabletitle);
                   17036:     if (exists($filter->{'cloneableonly'})) {
                   17037:         my $cloneableon = '';
                   17038:         my $cloneableoff = ' checked="checked"';
                   17039:         if ($filter->{'cloneableonly'}) {
                   17040:             $cloneableon = $cloneableoff;
                   17041:             $cloneableoff = '';
                   17042:         }
                   17043:         $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>';
                   17044:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17045:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17046:         } else {
                   17047:             $cloneabletitle = &mt('Cloneable by you');
                   17048:         }
                   17049:     }
                   17050:     my $officialjs;
                   17051:     if ($crstype eq 'Course') {
                   17052:         if (exists($filter->{'instcodefilter'})) {
                   17053: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17054: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17055:             if ($codedom) {
                   17056:                 $officialjs = 1;
                   17057:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17058:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17059:                                                                   $officialjs,$codetitlesref);
                   17060:                 if ($jscript) {
                   17061:                     $jscript = '<script type="text/javascript">'."\n".
                   17062:                                '// <![CDATA['."\n".
                   17063:                                $jscript."\n".
                   17064:                                '// ]]>'."\n".
                   17065:                                '</script>'."\n";
                   17066:                 }
                   17067:             }
                   17068:             if ($instcodeform eq '') {
                   17069:                 $instcodeform =
                   17070:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17071:                     $list->{'instcodefilter'}.'" />';
                   17072:                 $instcodetitle = $lt{'ins'};
                   17073:             } else {
                   17074:                 $instcodetitle = $lt{'inc'};
                   17075:             }
                   17076:             if ($fixeddom) {
                   17077:                 $instcodetitle .= '<br />('.$codedom.')';
                   17078:             }
                   17079:         }
                   17080:     }
                   17081:     my $output = qq|
                   17082: <form method="post" name="filterpicker" action="$action">
                   17083: <input type="hidden" name="form" value="$formname" />
                   17084: |;
                   17085:     if ($formname eq 'modifycourse') {
                   17086:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17087:                    '<input type="hidden" name="prevphase" value="'.
                   17088:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17089:     } elsif ($formname eq 'quotacheck') {
                   17090:         $output .= qq|
                   17091: <input type="hidden" name="sortby" value="" />
                   17092: <input type="hidden" name="sortorder" value="" />
                   17093: |;
                   17094:     } else {
1.1075.2.69  raeburn  17095:         my $name_input;
                   17096:         if ($cnameelement ne '') {
                   17097:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17098:                           $cnameelement.'" />';
                   17099:         }
                   17100:         $output .= qq|
                   17101: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17102: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17103: $name_input
                   17104: $roleelement
                   17105: $multelement
                   17106: $typeelement
                   17107: |;
                   17108:         if ($formname eq 'portform') {
                   17109:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17110:         }
                   17111:     }
                   17112:     if ($fixeddom) {
                   17113:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17114:     }
                   17115:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17116:     if ($sincefilterform) {
                   17117:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17118:                   .$sincefilterform
                   17119:                   .&Apache::lonhtmlcommon::row_closure();
                   17120:     }
                   17121:     if ($createdfilterform) {
                   17122:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17123:                   .$createdfilterform
                   17124:                   .&Apache::lonhtmlcommon::row_closure();
                   17125:     }
                   17126:     if ($domainselectform) {
                   17127:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17128:                   .$domainselectform
                   17129:                   .&Apache::lonhtmlcommon::row_closure();
                   17130:     }
                   17131:     if ($typeselectform) {
                   17132:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17133:             $output .= $typeselectform;
                   17134:         } else {
                   17135:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17136:                       .$typeselectform
                   17137:                       .&Apache::lonhtmlcommon::row_closure();
                   17138:         }
                   17139:     }
                   17140:     if ($instcodeform) {
                   17141:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17142:                   .$instcodeform
                   17143:                   .&Apache::lonhtmlcommon::row_closure();
                   17144:     }
                   17145:     if (exists($filter->{'ownerfilter'})) {
                   17146:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17147:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17148:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17149:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17150:                    $ownerdomselectform.'</td></tr></table>'.
                   17151:                    &Apache::lonhtmlcommon::row_closure();
                   17152:     }
                   17153:     if (exists($filter->{'personfilter'})) {
                   17154:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17155:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17156:                    '<input type="text" name="personfilter" size="20" value="'.
                   17157:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17158:                    $persondomselectform.'</td></tr></table>'.
                   17159:                    &Apache::lonhtmlcommon::row_closure();
                   17160:     }
                   17161:     if (exists($filter->{'coursefilter'})) {
                   17162:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17163:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17164:                   .$list->{'coursefilter'}.'" />'
                   17165:                   .&Apache::lonhtmlcommon::row_closure();
                   17166:     }
                   17167:     if ($cloneableonlyform) {
                   17168:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17169:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17170:     }
                   17171:     if (exists($filter->{'descriptfilter'})) {
                   17172:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17173:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17174:                   .$list->{'descriptfilter'}.'" />'
                   17175:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17176:     }
                   17177:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17178:                '<input type="hidden" name="updater" value="" />'."\n".
                   17179:                '<input type="submit" name="gosearch" value="'.
                   17180:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17181:     return $jscript.$clonewarning.$output;
                   17182: }
                   17183: 
                   17184: =pod
                   17185: 
                   17186: =item * &timebased_select_form()
                   17187: 
                   17188: Create markup for a dropdown list used to select a time-based
                   17189: filter e.g., Course Activity, Course Created, when searching for courses
                   17190: or communities
                   17191: 
                   17192: Inputs:
                   17193: 
                   17194: item - name of form element (sincefilter or createdfilter)
                   17195: 
                   17196: filter - anonymous hash of criteria and their values
                   17197: 
                   17198: Returns: HTML for a select box contained a blank, then six time selections,
                   17199:          with value set in incoming form variables currently selected.
                   17200: 
                   17201: Side Effects: None
                   17202: 
                   17203: =cut
                   17204: 
                   17205: sub timebased_select_form {
                   17206:     my ($item,$filter) = @_;
                   17207:     if (ref($filter) eq 'HASH') {
                   17208:         $filter->{$item} =~ s/[^\d-]//g;
                   17209:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17210:         return &select_form(
                   17211:                             $filter->{$item},
                   17212:                             $item,
                   17213:                             {      '-1' => '',
                   17214:                                 '86400' => &mt('today'),
                   17215:                                '604800' => &mt('last week'),
                   17216:                               '2592000' => &mt('last month'),
                   17217:                               '7776000' => &mt('last three months'),
                   17218:                              '15552000' => &mt('last six months'),
                   17219:                              '31104000' => &mt('last year'),
                   17220:                     'select_form_order' =>
                   17221:                            ['-1','86400','604800','2592000','7776000',
                   17222:                             '15552000','31104000']});
                   17223:     }
                   17224: }
                   17225: 
                   17226: =pod
                   17227: 
                   17228: =item * &js_changer()
                   17229: 
                   17230: Create script tag containing Javascript used to submit course search form
                   17231: when course type or domain is changed, and also to hide 'Searching ...' on
                   17232: page load completion for page showing search result.
                   17233: 
                   17234: Inputs: None
                   17235: 
                   17236: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17237: 
                   17238: Side Effects: None
                   17239: 
                   17240: =cut
                   17241: 
                   17242: sub js_changer {
                   17243:     return <<ENDJS;
                   17244: <script type="text/javascript">
                   17245: // <![CDATA[
                   17246: function updateFilters(caller) {
                   17247:     if (typeof(caller) != "undefined") {
                   17248:         document.filterpicker.updater.value = caller.name;
                   17249:     }
                   17250:     document.filterpicker.submit();
                   17251: }
                   17252: 
                   17253: function hideSearching() {
                   17254:     if (document.getElementById('searching')) {
                   17255:         document.getElementById('searching').style.display = 'none';
                   17256:     }
                   17257:     return;
                   17258: }
                   17259: 
                   17260: // ]]>
                   17261: </script>
                   17262: 
                   17263: ENDJS
                   17264: }
                   17265: 
                   17266: =pod
                   17267: 
                   17268: =item * &search_courses()
                   17269: 
                   17270: Process selected filters form course search form and pass to lonnet::courseiddump
                   17271: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17272: 
                   17273: Inputs:
                   17274: 
                   17275: dom - domain being searched
                   17276: 
                   17277: type - course type ('Course' or 'Community' or '.' if any).
                   17278: 
                   17279: filter - anonymous hash of criteria and their values
                   17280: 
                   17281: numtitles - for institutional codes - number of categories
                   17282: 
                   17283: cloneruname - optional username of new course owner
                   17284: 
                   17285: clonerudom - optional domain of new course owner
                   17286: 
1.1075.2.95  raeburn  17287: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17288:             (used when DC is using course creation form)
                   17289: 
                   17290: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17291: 
1.1075.2.95  raeburn  17292: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17293:            (and so can clone automatically)
                   17294: 
                   17295: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17296: 
                   17297: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17298:               courses to clone
1.1075.2.69  raeburn  17299: 
                   17300: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17301: 
                   17302: 
                   17303: Side Effects: None
                   17304: 
                   17305: =cut
                   17306: 
                   17307: 
                   17308: sub search_courses {
1.1075.2.95  raeburn  17309:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17310:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17311:     my (%courses,%showcourses,$cloner);
                   17312:     if (($filter->{'ownerfilter'} ne '') ||
                   17313:         ($filter->{'ownerdomfilter'} ne '')) {
                   17314:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17315:                                        $filter->{'ownerdomfilter'};
                   17316:     }
                   17317:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17318:         if (!$filter->{$item}) {
                   17319:             $filter->{$item}='.';
                   17320:         }
                   17321:     }
                   17322:     my $now = time;
                   17323:     my $timefilter =
                   17324:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17325:     my ($createdbefore,$createdafter);
                   17326:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17327:         $createdbefore = $now;
                   17328:         $createdafter = $now-$filter->{'createdfilter'};
                   17329:     }
                   17330:     my ($instcodefilter,$regexpok);
                   17331:     if ($numtitles) {
                   17332:         if ($env{'form.official'} eq 'on') {
                   17333:             $instcodefilter =
                   17334:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17335:             $regexpok = 1;
                   17336:         } elsif ($env{'form.official'} eq 'off') {
                   17337:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17338:             unless ($instcodefilter eq '') {
                   17339:                 $regexpok = -1;
                   17340:             }
                   17341:         }
                   17342:     } else {
                   17343:         $instcodefilter = $filter->{'instcodefilter'};
                   17344:     }
                   17345:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17346:     if ($type eq '') { $type = '.'; }
                   17347: 
                   17348:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17349:         $cloner = $cloneruname.':'.$clonerudom;
                   17350:     }
                   17351:     %courses = &Apache::lonnet::courseiddump($dom,
                   17352:                                              $filter->{'descriptfilter'},
                   17353:                                              $timefilter,
                   17354:                                              $instcodefilter,
                   17355:                                              $filter->{'combownerfilter'},
                   17356:                                              $filter->{'coursefilter'},
                   17357:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17358:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17359:                                              $filter->{'cloneableonly'},
                   17360:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17361:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17362:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17363:         my $ccrole;
                   17364:         if ($type eq 'Community') {
                   17365:             $ccrole = 'co';
                   17366:         } else {
                   17367:             $ccrole = 'cc';
                   17368:         }
                   17369:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17370:                                                      $filter->{'persondomfilter'},
                   17371:                                                      'userroles',undef,
                   17372:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17373:                                                      $dom);
                   17374:         foreach my $role (keys(%rolehash)) {
                   17375:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17376:             my $cid = $cdom.'_'.$cnum;
                   17377:             if (exists($courses{$cid})) {
                   17378:                 if (ref($courses{$cid}) eq 'HASH') {
                   17379:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17380:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17381:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17382:                         }
                   17383:                     } else {
                   17384:                         $courses{$cid}{roles} = [$courserole];
                   17385:                     }
                   17386:                     $showcourses{$cid} = $courses{$cid};
                   17387:                 }
                   17388:             }
                   17389:         }
                   17390:         %courses = %showcourses;
                   17391:     }
                   17392:     return %courses;
                   17393: }
                   17394: 
                   17395: =pod
                   17396: 
                   17397: =back
                   17398: 
1.1075.2.88  raeburn  17399: =head1 Routines for version requirements for current course.
                   17400: 
                   17401: =over 4
                   17402: 
                   17403: =item * &check_release_required()
                   17404: 
                   17405: Compares required LON-CAPA version with version on server, and
                   17406: if required version is newer looks for a server with the required version.
                   17407: 
                   17408: Looks first at servers in user's owen domain; if none suitable, looks at
                   17409: servers in course's domain are permitted to host sessions for user's domain.
                   17410: 
                   17411: Inputs:
                   17412: 
                   17413: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17414: 
                   17415: $courseid - Course ID of current course
                   17416: 
                   17417: $rolecode - User's current role in course (for switchserver query string).
                   17418: 
                   17419: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17420: 
                   17421: 
                   17422: Returns:
                   17423: 
                   17424: $switchserver - query string tp append to /adm/switchserver call (if
                   17425:                 current server's LON-CAPA version is too old.
                   17426: 
                   17427: $warning - Message is displayed if no suitable server could be found.
                   17428: 
                   17429: =cut
                   17430: 
                   17431: sub check_release_required {
                   17432:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17433:     my ($switchserver,$warning);
                   17434:     if ($required ne '') {
                   17435:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17436:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17437:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17438:             my $otherserver;
                   17439:             if (($major eq '' && $minor eq '') ||
                   17440:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17441:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17442:                 my $switchlcrev =
                   17443:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17444:                                                            $userdomserver);
                   17445:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17446:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17447:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17448:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17449:                     if ($cdom ne $env{'user.domain'}) {
                   17450:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17451:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17452:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17453:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17454:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17455:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17456:                         my $canhost =
                   17457:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17458:                                                               $coursedomserver,
                   17459:                                                               $remoterev,
                   17460:                                                               $udomdefaults{'remotesessions'},
                   17461:                                                               $defdomdefaults{'hostedsessions'});
                   17462: 
                   17463:                         if ($canhost) {
                   17464:                             $otherserver = $coursedomserver;
                   17465:                         } else {
                   17466:                             $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.");
                   17467:                         }
                   17468:                     } else {
                   17469:                         $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).");
                   17470:                     }
                   17471:                 } else {
                   17472:                     $otherserver = $userdomserver;
                   17473:                 }
                   17474:             }
                   17475:             if ($otherserver ne '') {
                   17476:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17477:             }
                   17478:         }
                   17479:     }
                   17480:     return ($switchserver,$warning);
                   17481: }
                   17482: 
                   17483: =pod
                   17484: 
                   17485: =item * &check_release_result()
                   17486: 
                   17487: Inputs:
                   17488: 
                   17489: $switchwarning - Warning message if no suitable server found to host session.
                   17490: 
                   17491: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17492:                 and current role.
                   17493: 
                   17494: Returns: HTML to display with information about requirement to switch server.
                   17495:          Either displaying warning with link to Roles/Courses screen or
                   17496:          display link to switchserver.
                   17497: 
1.1075.2.69  raeburn  17498: =cut
                   17499: 
1.1075.2.88  raeburn  17500: sub check_release_result {
                   17501:     my ($switchwarning,$switchserver) = @_;
                   17502:     my $output = &start_page('Selected course unavailable on this server').
                   17503:                  '<p class="LC_warning">';
                   17504:     if ($switchwarning) {
                   17505:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17506:         if (&show_course()) {
                   17507:             $output .= &mt('Display courses');
                   17508:         } else {
                   17509:             $output .= &mt('Display roles');
                   17510:         }
                   17511:         $output .= '</a>';
                   17512:     } elsif ($switchserver) {
                   17513:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17514:                    '<br />'.
                   17515:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17516:                    &mt('Switch Server').
                   17517:                    '</a>';
                   17518:     }
                   17519:     $output .= '</p>'.&end_page();
                   17520:     return $output;
                   17521: }
                   17522: 
                   17523: =pod
                   17524: 
                   17525: =item * &needs_coursereinit()
                   17526: 
                   17527: Determine if course contents stored for user's session needs to be
                   17528: refreshed, because content has changed since "Big Hash" last tied.
                   17529: 
                   17530: Check for change is made if time last checked is more than 10 minutes ago
                   17531: (by default).
                   17532: 
                   17533: Inputs:
                   17534: 
                   17535: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17536: 
                   17537: $interval (optional) - Time which may elapse (in s) between last check for content
                   17538:                        change in current course. (default: 600 s).
                   17539: 
                   17540: Returns: an array; first element is:
                   17541: 
                   17542: =over 4
                   17543: 
                   17544: 'switch' - if content updates mean user's session
                   17545:            needs to be switched to a server running a newer LON-CAPA version
                   17546: 
                   17547: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17548:            on current server hosting user's session
                   17549: 
                   17550: ''       - if no action required.
                   17551: 
                   17552: =back
                   17553: 
                   17554: If first item element is 'switch':
                   17555: 
                   17556: second item is $switchwarning - Warning message if no suitable server found to host session.
                   17557: 
                   17558: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17559:                               and current role.
                   17560: 
                   17561: otherwise: no other elements returned.
                   17562: 
                   17563: =back
                   17564: 
                   17565: =cut
                   17566: 
                   17567: sub needs_coursereinit {
                   17568:     my ($loncaparev,$interval) = @_;
                   17569:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17570:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17571:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17572:     my $now = time;
                   17573:     if ($interval eq '') {
                   17574:         $interval = 600;
                   17575:     }
                   17576:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   17577:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 17578:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 17579:21):         if ($blocked) {
                   17580:21):             return ();
                   17581:21):         }
                   17582:21):         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
1.1075.2.88  raeburn  17583:         if ($lastchange > $env{'request.course.tied'}) {
                   17584:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17585:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17586:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17587:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17588:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17589:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17590:                     my ($switchserver,$switchwarning) =
                   17591:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17592:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17593:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17594:                         return ('switch',$switchwarning,$switchserver);
                   17595:                     }
                   17596:                 }
                   17597:             }
                   17598:             return ('update');
                   17599:         }
                   17600:     }
                   17601:     return ();
                   17602: }
1.1075.2.69  raeburn  17603: 
1.1075.2.11  raeburn  17604: sub update_content_constraints {
                   17605:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17606:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17607:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17608:     my %checkresponsetypes;
                   17609:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   17610:         my ($item,$name,$value) = split(/:/,$key);
                   17611:         if ($item eq 'resourcetag') {
                   17612:             if ($name eq 'responsetype') {
                   17613:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17614:             }
                   17615:         }
                   17616:     }
                   17617:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17618:     if (defined($navmap)) {
                   17619:         my %allresponses;
                   17620:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17621:             my %responses = $res->responseTypes();
                   17622:             foreach my $key (keys(%responses)) {
                   17623:                 next unless(exists($checkresponsetypes{$key}));
                   17624:                 $allresponses{$key} += $responses{$key};
                   17625:             }
                   17626:         }
                   17627:         foreach my $key (keys(%allresponses)) {
                   17628:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17629:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17630:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17631:             }
                   17632:         }
                   17633:         undef($navmap);
                   17634:     }
                   17635:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17636:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17637:     }
                   17638:     return;
                   17639: }
                   17640: 
1.1075.2.27  raeburn  17641: sub allmaps_incourse {
                   17642:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17643:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17644:         $cid = $env{'request.course.id'};
                   17645:         $cdom = $env{'course.'.$cid.'.domain'};
                   17646:         $cnum = $env{'course.'.$cid.'.num'};
                   17647:         $chome = $env{'course.'.$cid.'.home'};
                   17648:     }
                   17649:     my %allmaps = ();
                   17650:     my $lastchange =
                   17651:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17652:     if ($lastchange > $env{'request.course.tied'}) {
                   17653:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17654:         unless ($ferr) {
                   17655:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17656:         }
                   17657:     }
                   17658:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17659:     if (defined($navmap)) {
                   17660:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17661:             $allmaps{$res->src()} = 1;
                   17662:         }
                   17663:     }
                   17664:     return \%allmaps;
                   17665: }
                   17666: 
1.1075.2.11  raeburn  17667: sub parse_supplemental_title {
                   17668:     my ($title) = @_;
                   17669: 
                   17670:     my ($foldertitle,$renametitle);
                   17671:     if ($title =~ /&amp;&amp;&amp;/) {
                   17672:         $title = &HTML::Entites::decode($title);
                   17673:     }
                   17674:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17675:         $renametitle=$4;
                   17676:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17677:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17678:         my $name =  &plainname($uname,$udom);
                   17679:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17680:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17681:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17682:             $name.': <br />'.$foldertitle;
                   17683:     }
                   17684:     if (wantarray) {
                   17685:         return ($title,$foldertitle,$renametitle);
                   17686:     }
                   17687:     return $title;
                   17688: }
                   17689: 
1.1075.2.43  raeburn  17690: sub recurse_supplemental {
                   17691:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17692:     if ($suppmap) {
                   17693:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17694:         if ($fatal) {
                   17695:             $errors ++;
                   17696:         } else {
                   17697:             if ($#LONCAPA::map::resources > 0) {
                   17698:                 foreach my $res (@LONCAPA::map::resources) {
                   17699:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17700:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  17701:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17702:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  17703:                         } else {
                   17704:                             $numfiles ++;
                   17705:                         }
                   17706:                     }
                   17707:                 }
                   17708:             }
                   17709:         }
                   17710:     }
                   17711:     return ($numfiles,$errors);
                   17712: }
                   17713: 
1.1075.2.18  raeburn  17714: sub symb_to_docspath {
1.1075.2.119  raeburn  17715:     my ($symb,$navmapref) = @_;
                   17716:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  17717:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17718:     if ($resurl=~/\.(sequence|page)$/) {
                   17719:         $mapurl=$resurl;
                   17720:     } elsif ($resurl eq 'adm/navmaps') {
                   17721:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17722:     }
                   17723:     my $mapresobj;
1.1075.2.119  raeburn  17724:     unless (ref($$navmapref)) {
                   17725:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17726:     }
                   17727:     if (ref($$navmapref)) {
                   17728:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  17729:     }
                   17730:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17731:     my $type=$2;
                   17732:     my $path;
                   17733:     if (ref($mapresobj)) {
                   17734:         my $pcslist = $mapresobj->map_hierarchy();
                   17735:         if ($pcslist ne '') {
                   17736:             foreach my $pc (split(/,/,$pcslist)) {
                   17737:                 next if ($pc <= 1);
1.1075.2.119  raeburn  17738:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  17739:                 if (ref($res)) {
                   17740:                     my $thisurl = $res->src();
                   17741:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17742:                     my $thistitle = $res->title();
                   17743:                     $path .= '&'.
                   17744:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  17745:                              &escape($thistitle).
1.1075.2.18  raeburn  17746:                              ':'.$res->randompick().
                   17747:                              ':'.$res->randomout().
                   17748:                              ':'.$res->encrypted().
                   17749:                              ':'.$res->randomorder().
                   17750:                              ':'.$res->is_page();
                   17751:                 }
                   17752:             }
                   17753:         }
                   17754:         $path =~ s/^\&//;
                   17755:         my $maptitle = $mapresobj->title();
                   17756:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17757:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17758:         }
                   17759:         $path .= (($path ne '')? '&' : '').
                   17760:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17761:                  &escape($maptitle).
1.1075.2.18  raeburn  17762:                  ':'.$mapresobj->randompick().
                   17763:                  ':'.$mapresobj->randomout().
                   17764:                  ':'.$mapresobj->encrypted().
                   17765:                  ':'.$mapresobj->randomorder().
                   17766:                  ':'.$mapresobj->is_page();
                   17767:     } else {
                   17768:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17769:         my $ispage = (($type eq 'page')? 1 : '');
                   17770:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17771:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17772:         }
                   17773:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17774:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  17775:     }
                   17776:     unless ($mapurl eq 'default') {
                   17777:         $path = 'default&'.
1.1075.2.46  raeburn  17778:                 &escape('Main Content').
1.1075.2.18  raeburn  17779:                 ':::::&'.$path;
                   17780:     }
                   17781:     return $path;
                   17782: }
                   17783: 
1.1075.2.14  raeburn  17784: sub captcha_display {
1.1075.2.137  raeburn  17785:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17786:     my ($output,$error);
1.1075.2.107  raeburn  17787:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17788:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17789:     if ($captcha eq 'original') {
                   17790:         $output = &create_captcha();
                   17791:         unless ($output) {
                   17792:             $error = 'captcha';
                   17793:         }
                   17794:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17795:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17796:         unless ($output) {
                   17797:             $error = 'recaptcha';
                   17798:         }
                   17799:     }
1.1075.2.107  raeburn  17800:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17801: }
                   17802: 
                   17803: sub captcha_response {
1.1075.2.137  raeburn  17804:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17805:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17806:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17807:     if ($captcha eq 'original') {
                   17808:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17809:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17810:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17811:     } else {
                   17812:         $captcha_chk = 1;
                   17813:     }
                   17814:     return ($captcha_chk,$captcha_error);
                   17815: }
                   17816: 
                   17817: sub get_captcha_config {
1.1075.2.137  raeburn  17818:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17819:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17820:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17821:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17822:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17823:     if ($context eq 'usercreation') {
                   17824:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17825:         if (ref($domconfig{$context}) eq 'HASH') {
                   17826:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17827:             if (ref($hashtocheck) eq 'HASH') {
                   17828:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17829:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17830:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17831:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17832:                     }
                   17833:                     if ($privkey && $pubkey) {
                   17834:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17835:                         $version = $hashtocheck->{'recaptchaversion'};
                   17836:                         if ($version ne '2') {
                   17837:                             $version = 1;
                   17838:                         }
1.1075.2.14  raeburn  17839:                     } else {
                   17840:                         $captcha = 'original';
                   17841:                     }
                   17842:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17843:                     $captcha = 'original';
                   17844:                 }
                   17845:             }
                   17846:         } else {
                   17847:             $captcha = 'captcha';
                   17848:         }
                   17849:     } elsif ($context eq 'login') {
                   17850:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17851:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17852:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17853:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17854:             if ($privkey && $pubkey) {
                   17855:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17856:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17857:                 if ($version ne '2') {
                   17858:                     $version = 1;
                   17859:                 }
1.1075.2.14  raeburn  17860:             } else {
                   17861:                 $captcha = 'original';
                   17862:             }
                   17863:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17864:             $captcha = 'original';
                   17865:         }
1.1075.2.137  raeburn  17866:     } elsif ($context eq 'passwords') {
                   17867:         if ($dom_in_effect) {
                   17868:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17869:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17870:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17871:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17872:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17873:                 }
                   17874:                 if ($privkey && $pubkey) {
                   17875:                     $captcha = 'recaptcha';
                   17876:                     $version = $passwdconf{'recaptchaversion'};
                   17877:                     if ($version ne '2') {
                   17878:                         $version = 1;
                   17879:                     }
                   17880:                 } else {
                   17881:                     $captcha = 'original';
                   17882:                 }
                   17883:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17884:                 $captcha = 'original';
                   17885:             }
                   17886:         }
1.1075.2.14  raeburn  17887:     }
1.1075.2.107  raeburn  17888:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17889: }
                   17890: 
                   17891: sub create_captcha {
                   17892:     my %captcha_params = &captcha_settings();
                   17893:     my ($output,$maxtries,$tries) = ('',10,0);
                   17894:     while ($tries < $maxtries) {
                   17895:         $tries ++;
                   17896:         my $captcha = Authen::Captcha->new (
                   17897:                                            output_folder => $captcha_params{'output_dir'},
                   17898:                                            data_folder   => $captcha_params{'db_dir'},
                   17899:                                           );
                   17900:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17901: 
                   17902:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17903:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  17904:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  17905:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17906:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1075.2.158  raeburn  17907:                       '</span><br />'.
1.1075.2.66  raeburn  17908:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17909:             last;
                   17910:         }
                   17911:     }
1.1075.2.158  raeburn  17912:     if ($output eq '') {
                   17913:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   17914:     }
1.1075.2.14  raeburn  17915:     return $output;
                   17916: }
                   17917: 
                   17918: sub captcha_settings {
                   17919:     my %captcha_params = (
                   17920:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17921:                            www_output_dir => "/captchaspool",
                   17922:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17923:                            numchars       => '5',
                   17924:                          );
                   17925:     return %captcha_params;
                   17926: }
                   17927: 
                   17928: sub check_captcha {
                   17929:     my ($captcha_chk,$captcha_error);
                   17930:     my $code = $env{'form.code'};
                   17931:     my $md5sum = $env{'form.crypt'};
                   17932:     my %captcha_params = &captcha_settings();
                   17933:     my $captcha = Authen::Captcha->new(
                   17934:                       output_folder => $captcha_params{'output_dir'},
                   17935:                       data_folder   => $captcha_params{'db_dir'},
                   17936:                   );
1.1075.2.26  raeburn  17937:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17938:     my %captcha_hash = (
                   17939:                         0       => 'Code not checked (file error)',
                   17940:                        -1      => 'Failed: code expired',
                   17941:                        -2      => 'Failed: invalid code (not in database)',
                   17942:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17943:     );
                   17944:     if ($captcha_chk != 1) {
                   17945:         $captcha_error = $captcha_hash{$captcha_chk}
                   17946:     }
                   17947:     return ($captcha_chk,$captcha_error);
                   17948: }
                   17949: 
                   17950: sub create_recaptcha {
1.1075.2.107  raeburn  17951:     my ($pubkey,$version) = @_;
                   17952:     if ($version >= 2) {
1.1075.2.158  raeburn  17953:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   17954:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  17955:     } else {
                   17956:         my $use_ssl;
                   17957:         if ($ENV{'SERVER_PORT'} == 443) {
                   17958:             $use_ssl = 1;
                   17959:         }
                   17960:         my $captcha = Captcha::reCAPTCHA->new;
                   17961:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17962:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17963:                &mt('If the text is hard to read, [_1] will replace them.',
                   17964:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17965:                '<br /><br />';
                   17966:      }
1.1075.2.14  raeburn  17967: }
                   17968: 
                   17969: sub check_recaptcha {
1.1075.2.107  raeburn  17970:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17971:     my $captcha_chk;
1.1075.2.150  raeburn  17972:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  17973:     if ($version >= 2) {
                   17974:         my $ua = LWP::UserAgent->new;
                   17975:         $ua->timeout(10);
                   17976:         my %info = (
                   17977:                      secret   => $privkey,
                   17978:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  17979:                      remoteip => $ip,
1.1075.2.107  raeburn  17980:                    );
                   17981:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17982:         if ($response->is_success)  {
                   17983:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17984:             if (ref($data) eq 'HASH') {
                   17985:                 if ($data->{'success'}) {
                   17986:                     $captcha_chk = 1;
                   17987:                 }
                   17988:             }
                   17989:         }
                   17990:     } else {
                   17991:         my $captcha = Captcha::reCAPTCHA->new;
                   17992:         my $captcha_result =
                   17993:             $captcha->check_answer(
                   17994:                                     $privkey,
1.1075.2.150  raeburn  17995:                                     $ip,
1.1075.2.107  raeburn  17996:                                     $env{'form.recaptcha_challenge_field'},
                   17997:                                     $env{'form.recaptcha_response_field'},
                   17998:                                   );
                   17999:         if ($captcha_result->{is_valid}) {
                   18000:             $captcha_chk = 1;
                   18001:         }
1.1075.2.14  raeburn  18002:     }
                   18003:     return $captcha_chk;
                   18004: }
                   18005: 
1.1075.2.64  raeburn  18006: sub emailusername_info {
1.1075.2.103  raeburn  18007:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18008:     my %titles = &Apache::lonlocal::texthash (
                   18009:                      lastname      => 'Last Name',
                   18010:                      firstname     => 'First Name',
                   18011:                      institution   => 'School/college/university',
                   18012:                      location      => "School's city, state/province, country",
                   18013:                      web           => "School's web address",
                   18014:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18015:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18016:                  );
                   18017:     return (\@fields,\%titles);
                   18018: }
                   18019: 
1.1075.2.56  raeburn  18020: sub cleanup_html {
                   18021:     my ($incoming) = @_;
                   18022:     my $outgoing;
                   18023:     if ($incoming ne '') {
                   18024:         $outgoing = $incoming;
                   18025:         $outgoing =~ s/;/&#059;/g;
                   18026:         $outgoing =~ s/\#/&#035;/g;
                   18027:         $outgoing =~ s/\&/&#038;/g;
                   18028:         $outgoing =~ s/</&#060;/g;
                   18029:         $outgoing =~ s/>/&#062;/g;
                   18030:         $outgoing =~ s/\(/&#040/g;
                   18031:         $outgoing =~ s/\)/&#041;/g;
                   18032:         $outgoing =~ s/"/&#034;/g;
                   18033:         $outgoing =~ s/'/&#039;/g;
                   18034:         $outgoing =~ s/\$/&#036;/g;
                   18035:         $outgoing =~ s{/}{&#047;}g;
                   18036:         $outgoing =~ s/=/&#061;/g;
                   18037:         $outgoing =~ s/\\/&#092;/g
                   18038:     }
                   18039:     return $outgoing;
                   18040: }
                   18041: 
1.1075.2.74  raeburn  18042: # Checks for critical messages and returns a redirect url if one exists.
                   18043: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18044:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18045: sub critical_redirect {
1.1075.2.161.  .1(raebu 18046:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18047:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18048:         return ();
                   18049:     }
1.1075.2.74  raeburn  18050:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18051:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18052:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18053:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18054:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18055:21):             if ($blocked) {
                   18056:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18057:21):                 if ($env{'request.course.sec'} ne '') {
                   18058:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18059:21):                 }
                   18060:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18061:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18062:21):                     return;
                   18063:21):                 }
                   18064:21):             }
                   18065:21):         }
1.1075.2.74  raeburn  18066:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18067:                                         $env{'user.name'});
                   18068:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18069:         my $redirecturl;
                   18070:         if ($what[0]) {
1.1075.2.158  raeburn  18071:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18072:                 $redirecturl='/adm/email?critical=display';
                   18073:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18074:                 return (1, $url);
                   18075:             }
                   18076:         }
                   18077:     }
                   18078:     return ();
                   18079: }
                   18080: 
1.1075.2.64  raeburn  18081: # Use:
                   18082: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18083: #
                   18084: ##################################################
                   18085: #          password associated functions         #
                   18086: ##################################################
                   18087: sub des_keys {
                   18088:     # Make a new key for DES encryption.
                   18089:     # Each key has two parts which are returned separately.
                   18090:     # Please note:  Each key must be passed through the &hex function
                   18091:     # before it is output to the web browser.  The hex versions cannot
                   18092:     # be used to decrypt.
                   18093:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18094:                 '8','9','a','b','c','d','e','f');
                   18095:     my $lkey='';
                   18096:     for (0..7) {
                   18097:         $lkey.=$hexstr[rand(15)];
                   18098:     }
                   18099:     my $ukey='';
                   18100:     for (0..7) {
                   18101:         $ukey.=$hexstr[rand(15)];
                   18102:     }
                   18103:     return ($lkey,$ukey);
                   18104: }
                   18105: 
                   18106: sub des_decrypt {
                   18107:     my ($key,$cyphertext) = @_;
                   18108:     my $keybin=pack("H16",$key);
                   18109:     my $cypher;
                   18110:     if ($Crypt::DES::VERSION>=2.03) {
                   18111:         $cypher=new Crypt::DES $keybin;
                   18112:     } else {
                   18113:         $cypher=new DES $keybin;
                   18114:     }
1.1075.2.106  raeburn  18115:     my $plaintext='';
                   18116:     my $cypherlength = length($cyphertext);
                   18117:     my $numchunks = int($cypherlength/32);
                   18118:     for (my $j=0; $j<$numchunks; $j++) {
                   18119:         my $start = $j*32;
                   18120:         my $cypherblock = substr($cyphertext,$start,32);
                   18121:         my $chunk =
                   18122:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18123:         $chunk .=
                   18124:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18125:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18126:         $plaintext .= $chunk;
                   18127:     }
1.1075.2.64  raeburn  18128:     return $plaintext;
                   18129: }
                   18130: 
1.1075.2.161.  .1(raebu 18131:21): sub get_requested_shorturls {
                   18132:21):     my ($cdom,$cnum,$navmap) = @_;
                   18133:21):     return unless (ref($navmap));
                   18134:21):     my ($numnew,$errors);
                   18135:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18136:21):     if (@toshorten) {
                   18137:21):         my (%maps,%resources,%titles);
                   18138:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18139:21):                                                                'shorturls',$cdom,$cnum);
                   18140:21):         if (keys(%resources)) {
                   18141:21):             my %tocreate;
                   18142:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18143:21):                 my $symb = $resources{$item};
                   18144:21):                 if ($symb) {
                   18145:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18146:21):                 }
                   18147:21):             }
                   18148:21):             if (keys(%tocreate)) {
                   18149:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18150:21):                                                       \%tocreate);
                   18151:21):             }
                   18152:21):         }
                   18153:21):     }
                   18154:21):     return ($numnew,$errors);
                   18155:21): }
                   18156:21): 
                   18157:21): sub make_short_symbs {
                   18158:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18159:21):     my ($numnew,@errors);
                   18160:21):     if (ref($tocreateref) eq 'HASH') {
                   18161:21):         my %tocreate = %{$tocreateref};
                   18162:21):         if (keys(%tocreate)) {
                   18163:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18164:21):             my $su = Short::URL->new(no_vowels => 1);
                   18165:21):             my $init = '';
                   18166:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   18167:21):             # get lock on tiny db
                   18168:21):             my $now = time;
                   18169:21):             if ($lockuser eq '') {
                   18170:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18171:21):             }
                   18172:21):             my $lockhash = {
                   18173:21):                                 "lock\0$now" => $lockuser,
                   18174:21):                             };
                   18175:21):             my $tries = 0;
                   18176:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18177:21):             my ($code,$error);
                   18178:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   18179:21):                 $tries ++;
                   18180:21):                 sleep 1;
                   18181:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18182:21):             }
                   18183:21):             if ($gotlock eq 'ok') {
                   18184:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18185:21):                                        \%addcourse,\%courseonly,\%failed);
                   18186:21):                 if (keys(%failed)) {
                   18187:21):                     my $numfailed = scalar(keys(%failed));
                   18188:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18189:21):                 }
                   18190:21):                 if (keys(%newunique)) {
                   18191:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18192:21):                     if ($putres eq 'ok') {
                   18193:21):                         $numnew = scalar(keys(%newunique));
                   18194:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18195:21):                         unless ($newputres eq 'ok') {
                   18196:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18197:21):                         }
                   18198:21):                     } else {
                   18199:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18200:21):                     }
                   18201:21):                 }
                   18202:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18203:21):                 unless ($dellockres eq 'ok') {
                   18204:21):                     push(@errors,&mt('error: could not release lockfile'));
                   18205:21):                 }
                   18206:21):             } else {
                   18207:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   18208:21):             }
                   18209:21):             if (keys(%courseonly)) {
                   18210:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18211:21):                 if ($result ne 'ok') {
                   18212:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18213:21):                 }
                   18214:21):             }
                   18215:21):         }
                   18216:21):     }
                   18217:21):     return ($numnew,\@errors);
                   18218:21): }
                   18219:21): 
                   18220:21): sub shorten_symbs {
                   18221:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18222:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18223:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18224:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18225:21):     my (%possibles,%collisions);
                   18226:21):     foreach my $key (keys(%{$tocreate})) {
                   18227:21):         my $num = String::CRC32::crc32($key);
                   18228:21):         my $tiny = $su->encode($num,$init);
                   18229:21):         if ($tiny) {
                   18230:21):             $possibles{$tiny} = $key;
                   18231:21):         }
                   18232:21):     }
                   18233:21):     if (!$init) {
                   18234:21):         $init = 1;
                   18235:21):     } else {
                   18236:21):         $init ++;
                   18237:21):     }
                   18238:21):     if (keys(%possibles)) {
                   18239:21):         my @posstiny = keys(%possibles);
                   18240:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18241:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18242:21):         if (keys(%currtiny)) {
                   18243:21):             foreach my $key (keys(%currtiny)) {
                   18244:21):                 next if ($currtiny{$key} eq '');
                   18245:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   18246:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18247:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18248:21):                         $courseonly->{$tsymb} = $key;
                   18249:21):                     }
                   18250:21):                 } else {
                   18251:21):                     $collisions{$possibles{$key}} = 1;
                   18252:21):                 }
                   18253:21):                 delete($possibles{$key});
                   18254:21):             }
                   18255:21):         }
                   18256:21):         foreach my $key (keys(%possibles)) {
                   18257:21):             $newunique->{$key} = $possibles{$key};
                   18258:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18259:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18260:21):                 $addcourse->{$tsymb} = $key;
                   18261:21):             }
                   18262:21):         }
                   18263:21):     }
                   18264:21):     if (keys(%collisions)) {
                   18265:21):         if ($init <5) {
                   18266:21):             if (!$init) {
                   18267:21):                 $init = 1;
                   18268:21):             } else {
                   18269:21):                 $init ++;
                   18270:21):             }
                   18271:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18272:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   18273:21):         } else {
                   18274:21):             foreach my $key (keys(%collisions)) {
                   18275:21):                 $failed->{$key} = 1;
                   18276:21):                 $failed->{$key} = 1;
                   18277:21):             }
                   18278:21):         }
                   18279:21):     }
                   18280:21):     return $init;
                   18281:21): }
                   18282:21): 
1.1075.2.135  raeburn  18283: sub is_nonframeable {
                   18284:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18285:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   18286:     return if (($remprotocol eq '') || ($remhost eq ''));
                   18287: 
                   18288:     $remprotocol = lc($remprotocol);
                   18289:     $remhost = lc($remhost);
                   18290:     my $remport = 80;
                   18291:     if ($remprotocol eq 'https') {
                   18292:         $remport = 443;
                   18293:     }
                   18294:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   18295:     if ($cached) {
                   18296:         unless ($nocache) {
                   18297:             if ($result) {
                   18298:                 return 1;
                   18299:             } else {
                   18300:                 return 0;
                   18301:             }
                   18302:         }
                   18303:     }
                   18304:     my $uselink;
                   18305:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  18306:     my $ua = LWP::UserAgent->new;
                   18307:     $ua->timeout(5);
                   18308:     my $response=$ua->request($request);
1.1075.2.135  raeburn  18309:     if ($response->is_success()) {
                   18310:         my $secpolicy = lc($response->header('content-security-policy'));
                   18311:         my $xframeop = lc($response->header('x-frame-options'));
                   18312:         $secpolicy =~ s/^\s+|\s+$//g;
                   18313:         $xframeop =~ s/^\s+|\s+$//g;
                   18314:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   18315:             my $remotehost = $remprotocol.'://'.$remhost;
                   18316:             my ($origin,$protocol,$port);
                   18317:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18318:                 $port = $ENV{'SERVER_PORT'};
                   18319:             } else {
                   18320:                 $port = 80;
                   18321:             }
                   18322:             if ($absolute eq '') {
                   18323:                 $protocol = 'http:';
                   18324:                 if ($port == 443) {
                   18325:                     $protocol = 'https:';
                   18326:                 }
                   18327:                 $origin = $protocol.'//'.lc($hostname);
                   18328:             } else {
                   18329:                 $origin = lc($absolute);
                   18330:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18331:             }
                   18332:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18333:                 my $framepolicy = $1;
                   18334:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18335:                 my @policies = split(/\s+/,$framepolicy);
                   18336:                 if (@policies) {
                   18337:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18338:                         $uselink = 1;
                   18339:                     } else {
                   18340:                         $uselink = 1;
                   18341:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18342:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18343:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18344:                             undef($uselink);
                   18345:                         }
                   18346:                         if ($uselink) {
                   18347:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18348:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18349:                                     undef($uselink);
                   18350:                                 }
                   18351:                             }
                   18352:                         }
                   18353:                         if ($uselink) {
                   18354:                             my @possok;
                   18355:                             if ($ip ne '') {
                   18356:                                 push(@possok,$ip);
                   18357:                             }
                   18358:                             my $hoststr = '';
                   18359:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18360:                                 if ($hoststr eq '') {
                   18361:                                     $hoststr = $part;
                   18362:                                 } else {
                   18363:                                     $hoststr = "$part.$hoststr";
                   18364:                                 }
                   18365:                                 if ($hoststr eq $hostname) {
                   18366:                                     push(@possok,$hostname);
                   18367:                                 } else {
                   18368:                                     push(@possok,"*.$hoststr");
                   18369:                                 }
                   18370:                             }
                   18371:                             if (@possok) {
                   18372:                                 foreach my $poss (@possok) {
                   18373:                                     last if (!$uselink);
                   18374:                                     foreach my $policy (@policies) {
                   18375:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18376:                                             undef($uselink);
                   18377:                                             last;
                   18378:                                         }
                   18379:                                     }
                   18380:                                 }
                   18381:                             }
                   18382:                         }
                   18383:                     }
                   18384:                 }
                   18385:             } elsif ($xframeop ne '') {
                   18386:                 $uselink = 1;
                   18387:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18388:                 if (@policies) {
                   18389:                     unless (grep(/^deny$/,@policies)) {
                   18390:                         if ($origin ne '') {
                   18391:                             if (grep(/^sameorigin$/,@policies)) {
                   18392:                                 if ($remotehost eq $origin) {
                   18393:                                     undef($uselink);
                   18394:                                 }
                   18395:                             }
                   18396:                             if ($uselink) {
                   18397:                                 foreach my $policy (@policies) {
                   18398:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18399:                                         my $allowfrom = $1;
                   18400:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18401:                                             undef($uselink);
                   18402:                                             last;
                   18403:                                         }
                   18404:                                     }
                   18405:                                 }
                   18406:                             }
                   18407:                         }
                   18408:                     }
                   18409:                 }
                   18410:             }
                   18411:         }
                   18412:     }
                   18413:     if ($nocache) {
                   18414:         if ($cached) {
                   18415:             my $devalidate;
                   18416:             if ($uselink && !$result) {
                   18417:                 $devalidate = 1;
                   18418:             } elsif (!$uselink && $result) {
                   18419:                 $devalidate = 1;
                   18420:             }
                   18421:             if ($devalidate) {
                   18422:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18423:             }
                   18424:         }
                   18425:     } else {
                   18426:         if ($uselink) {
                   18427:             $result = 1;
                   18428:         } else {
                   18429:             $result = 0;
                   18430:         }
                   18431:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18432:     }
                   18433:     return $uselink;
                   18434: }
                   18435: 
1.1075.2.161.  .1(raebu 18436:21): sub page_menu {
                   18437:21):     my ($menucolls,$menunum) = @_;
                   18438:21):     my %menu;
                   18439:21):     foreach my $item (split(/;/,$menucolls)) {
                   18440:21):         my ($num,$value) = split(/\%/,$item);
                   18441:21):         if ($num eq $menunum) {
                   18442:21):             my @entries = split(/\&/,$value);
                   18443:21):             foreach my $entry (@entries) {
                   18444:21):                 my ($name,$fields) = split(/=/,$entry);
                   18445:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   18446:21):                     $menu{$name} = $fields;
                   18447:21):                 } else {
                   18448:21):                     my @shown;
                   18449:21):                     if ($fields =~ /,/) {
                   18450:21):                         @shown = split(/,/,$fields);
                   18451:21):                     } else {
                   18452:21):                         @shown = ($fields);
                   18453:21):                     }
                   18454:21):                     if (@shown) {
                   18455:21):                         foreach my $field (@shown) {
                   18456:21):                             next if ($field eq '');
                   18457:21):                             $menu{$field} = 1;
                   18458:21):                         }
                   18459:21):                     }
                   18460:21):                 }
                   18461:21):             }
                   18462:21):         }
                   18463:21):     }
                   18464:21):     return %menu;
                   18465:21): }
                   18466:21): 
1.112     bowersj2 18467: 1;
                   18468: __END__;
1.41      ng       18469: 

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