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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.141.  .4(raebu    4:20): # $Id: loncommon.pm,v 1.1075.2.141.2.3 2020/02/12 22:06:59 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.1075.2.141.  .1(raebu   86:20): use String::CRC32();
                     87:20): use Short::URL();
1.117     www        88: 
1.517     raeburn    89: # ---------------------------------------------- Designs
                     90: use vars qw(%defaultdesign);
                     91: 
1.22      www        92: my $readit;
                     93: 
1.517     raeburn    94: 
1.157     matthew    95: ##
                     96: ## Global Variables
                     97: ##
1.46      matthew    98: 
1.643     foxr       99: 
                    100: # ----------------------------------------------- SSI with retries:
                    101: #
                    102: 
                    103: =pod
                    104: 
1.648     raeburn   105: =head1 Server Side include with retries:
1.643     foxr      106: 
                    107: =over 4
                    108: 
1.648     raeburn   109: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      110: 
                    111: Performs an ssi with some number of retries.  Retries continue either
                    112: until the result is ok or until the retry count supplied by the
                    113: caller is exhausted.  
                    114: 
                    115: Inputs:
1.648     raeburn   116: 
                    117: =over 4
                    118: 
1.643     foxr      119: resource   - Identifies the resource to insert.
1.648     raeburn   120: 
1.643     foxr      121: retries    - Count of the number of retries allowed.
1.648     raeburn   122: 
1.643     foxr      123: form       - Hash that identifies the rendering options.
                    124: 
1.648     raeburn   125: =back
                    126: 
                    127: Returns:
                    128: 
                    129: =over 4
                    130: 
1.643     foxr      131: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   132: 
1.643     foxr      133: response   - The response from the last attempt (which may or may not have been successful.
                    134: 
1.648     raeburn   135: =back
                    136: 
                    137: =back
                    138: 
1.643     foxr      139: =cut
                    140: 
                    141: sub ssi_with_retries {
                    142:     my ($resource, $retries, %form) = @_;
                    143: 
                    144: 
                    145:     my $ok = 0;			# True if we got a good response.
                    146:     my $content;
                    147:     my $response;
                    148: 
                    149:     # Try to get the ssi done. within the retries count:
                    150: 
                    151:     do {
                    152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    153: 	$ok      = $response->is_success;
1.650     www       154:         if (!$ok) {
                    155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    156:         }
1.643     foxr      157: 	$retries--;
                    158:     } while (!$ok && ($retries > 0));
                    159: 
                    160:     if (!$ok) {
                    161: 	$content = '';		# On error return an empty content.
                    162:     }
                    163:     return ($content, $response);
                    164: 
                    165: }
                    166: 
                    167: 
                    168: 
1.20      www       169: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  170: my %language;
1.124     www       171: my %supported_language;
1.1048    foxr      172: my %latex_language;		# For choosing hyphenation in <transl..>
                    173: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  174: my %cprtag;
1.192     taceyjo1  175: my %scprtag;
1.351     www       176: my %fe; my %fd; my %fm;
1.41      ng        177: my %category_extensions;
1.12      harris41  178: 
1.46      matthew   179: # ---------------------------------------------- Thesaurus variables
1.144     matthew   180: #
                    181: # %Keywords:
                    182: #      A hash used by &keyword to determine if a word is considered a keyword.
                    183: # $thesaurus_db_file 
                    184: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   185: 
                    186: my %Keywords;
                    187: my $thesaurus_db_file;
                    188: 
1.144     matthew   189: #
                    190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    191: # thesaurus.tab, and filecategories.tab.
                    192: #
1.18      www       193: BEGIN {
1.46      matthew   194:     # Variable initialization
                    195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    196:     #
1.22      www       197:     unless ($readit) {
1.12      harris41  198: # ------------------------------------------------------------------- languages
                    199:     {
1.158     raeburn   200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    201:                                    '/language.tab';
1.1075.2.128  raeburn   202:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
1.1048    foxr      206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   207:                 $language{$key}=$val.' - '.$enc;
                    208:                 if ($sup) {
                    209:                     $supported_language{$key}=$sup;
                    210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
                    213: 		    $latex_language{$two} = $latex;
                    214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
1.1075.2.128  raeburn   223:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   251:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
1.1075.2.128  raeburn   265:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   270:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
1.1075.2.128  raeburn   280:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.1075.2.141.  .3(raebu  433:20):     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.141.  .3(raebu  448:20):         if (courseadv == 'condition') {
                    449:20):             if (document.getElementById('courseadv')) {
                    450:20):                 courseadv = document.getElementById('courseadv').value;
                    451:20):             }
                    452:20):         }
                    453:20):         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       454:         var title = 'Student_Browser';
1.74      www       455:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    456:         options += ',width=700,height=600';
                    457:         stdeditbrowser = open(url,title,options,'1');
                    458:         stdeditbrowser.focus();
                    459:     }
1.824     bisitz    460: // ]]>
1.74      www       461: </script>
                    462: ENDSTDBRW
                    463: }
1.42      matthew   464: 
1.1003    www       465: sub resourcebrowser_javascript {
                    466:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       467:    return (<<'ENDRESBRW');
1.1003    www       468: <script type="text/javascript" language="Javascript">
                    469: // <![CDATA[
                    470:     var reseditbrowser;
1.1004    www       471:     function openresbrowser(formname,reslink) {
1.1005    www       472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       473:         var title = 'Resource_Browser';
                    474:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       475:         options += ',width=700,height=500';
1.1004    www       476:         reseditbrowser = open(url,title,options,'1');
                    477:         reseditbrowser.focus();
1.1003    www       478:     }
                    479: // ]]>
                    480: </script>
1.1004    www       481: ENDRESBRW
1.1003    www       482: }
                    483: 
1.74      www       484: sub selectstudent_link {
1.1075.2.141.  .3(raebu  485:20):    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  489:    if ($env{'request.course.id'}) {  
1.302     albertel  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    492: 					'/'.$env{'request.course.sec'})) {
1.111     www       493: 	   return '';
                    494:        }
1.999     www       495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.141.  .3(raebu  496:20):        if ($courseadv eq 'only') {
                    497:20):            $callargs .= ",'',1,'$courseadv'";
                    498:20):        } elsif ($courseadv eq 'none') {
                    499:20):            $callargs .= ",'','','$courseadv'";
                    500:20):        } elsif ($courseadv eq 'condition') {
                    501:20):            $callargs .= ",'','','$courseadv'";
1.793     raeburn   502:        }
                    503:        return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    505:               &mt('Select User').'</a></span>';
1.74      www       506:    }
1.258     albertel  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       508:        $callargs .= ",'',1"; 
1.793     raeburn   509:        return '<span class="LC_nobreak">'.
                    510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    511:               &mt('Select User').'</a></span>';
1.111     www       512:    }
                    513:    return '';
1.91      www       514: }
                    515: 
1.1004    www       516: sub selectresource_link {
                    517:    my ($form,$reslink,$arg)=@_;
                    518:    
                    519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    521:    unless ($env{'request.course.id'}) { return $arg; }
                    522:    return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    524:               $arg.'</a></span>';
                    525: }
                    526: 
                    527: 
                    528: 
1.653     raeburn   529: sub authorbrowser_javascript {
                    530:     return <<"ENDAUTHORBRW";
1.776     bisitz    531: <script type="text/javascript" language="JavaScript">
1.824     bisitz    532: // <![CDATA[
1.653     raeburn   533: var stdeditbrowser;
                    534: 
                    535: function openauthorbrowser(formname,udom) {
                    536:     var url = '/adm/pickauthor?';
                    537:     url += 'form='+formname+'&roledom='+udom;
                    538:     var title = 'Author_Browser';
                    539:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    540:     options += ',width=700,height=600';
                    541:     stdeditbrowser = open(url,title,options,'1');
                    542:     stdeditbrowser.focus();
                    543: }
                    544: 
1.824     bisitz    545: // ]]>
1.653     raeburn   546: </script>
                    547: ENDAUTHORBRW
                    548: }
                    549: 
1.91      www       550: sub coursebrowser_javascript {
1.1075.2.31  raeburn   551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   552:         $credits_element,$instcode) = @_;
1.932     raeburn   553:     my $wintitle = 'Course_Browser';
1.931     raeburn   554:     if ($crstype eq 'Community') {
1.932     raeburn   555:         $wintitle = 'Community_Browser';
1.909     raeburn   556:     }
1.876     raeburn   557:     my $id_functions = &javascript_index_functions();
                    558:     my $output = '
1.776     bisitz    559: <script type="text/javascript" language="JavaScript">
1.824     bisitz    560: // <![CDATA[
1.468     raeburn   561:     var stdeditbrowser;'."\n";
1.876     raeburn   562: 
                    563:     $output .= <<"ENDSTDBRW";
1.909     raeburn   564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       565:         var url = '/adm/pickcourse?';
1.895     raeburn   566:         var formid = getFormIdByName(formname);
1.876     raeburn   567:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  568:         if (domainfilter != null) {
                    569:            if (domainfilter != '') {
                    570:                url += 'domainfilter='+domainfilter+'&';
                    571: 	   }
                    572:         }
1.91      www       573:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  574: 	                            '&cdomelement='+udom+
                    575:                                     '&cnameelement='+desc;
1.468     raeburn   576:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   577:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   578:                 url += '&roleelement='+extra_element;
                    579:                 if (domainfilter == null || domainfilter == '') {
                    580:                     url += '&domainfilter='+extra_element;
                    581:                 }
1.234     raeburn   582:             }
1.468     raeburn   583:             else {
                    584:                 if (formname == 'portform') {
                    585:                     url += '&setroles='+extra_element;
1.800     raeburn   586:                 } else {
                    587:                     if (formname == 'rules') {
                    588:                         url += '&fixeddom='+extra_element; 
                    589:                     }
1.468     raeburn   590:                 }
                    591:             }     
1.230     raeburn   592:         }
1.909     raeburn   593:         if (type != null && type != '') {
                    594:             url += '&type='+type;
                    595:         }
                    596:         if (type_elem != null && type_elem != '') {
                    597:             url += '&typeelement='+type_elem;
                    598:         }
1.872     raeburn   599:         if (formname == 'ccrs') {
                    600:             var ownername = document.forms[formid].ccuname.value;
                    601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   602:             url += '&cloner='+ownername+':'+ownerdom;
                    603:             if (type == 'Course') {
                    604:                 url += '&crscode='+document.forms[formid].crscode.value;
                    605:             }
1.1075.2.95  raeburn   606:         }
                    607:         if (formname == 'requestcrs') {
                    608:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   609:         }
1.293     raeburn   610:         if (multflag !=null && multflag != '') {
                    611:             url += '&multiple='+multflag;
                    612:         }
1.909     raeburn   613:         var title = '$wintitle';
1.91      www       614:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    615:         options += ',width=700,height=600';
                    616:         stdeditbrowser = open(url,title,options,'1');
                    617:         stdeditbrowser.focus();
                    618:     }
1.876     raeburn   619: $id_functions
                    620: ENDSTDBRW
1.1075.2.31  raeburn   621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    623:                                       $credits_element);
1.876     raeburn   624:     }
                    625:     $output .= '
                    626: // ]]>
                    627: </script>';
                    628:     return $output;
                    629: }
                    630: 
                    631: sub javascript_index_functions {
                    632:     return <<"ENDJS";
                    633: 
                    634: function getFormIdByName(formname) {
                    635:     for (var i=0;i<document.forms.length;i++) {
                    636:         if (document.forms[i].name == formname) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
                    642: 
                    643: function getIndexByName(formid,item) {
                    644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    645:         if (document.forms[formid].elements[i].name == item) {
                    646:             return i;
                    647:         }
                    648:     }
                    649:     return -1;
                    650: }
1.468     raeburn   651: 
1.876     raeburn   652: function getDomainFromSelectbox(formname,udom) {
                    653:     var userdom;
                    654:     var formid = getFormIdByName(formname);
                    655:     if (formid > -1) {
                    656:         var domid = getIndexByName(formid,udom);
                    657:         if (domid > -1) {
                    658:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    660:             }
                    661:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    662:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   663:             }
                    664:         }
                    665:     }
1.876     raeburn   666:     return userdom;
                    667: }
                    668: 
                    669: ENDJS
1.468     raeburn   670: 
1.876     raeburn   671: }
                    672: 
1.1017    raeburn   673: sub javascript_array_indexof {
1.1018    raeburn   674:     return <<ENDJS;
1.1017    raeburn   675: <script type="text/javascript" language="JavaScript">
                    676: // <![CDATA[
                    677: 
                    678: if (!Array.prototype.indexOf) {
                    679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    680:         "use strict";
                    681:         if (this === void 0 || this === null) {
                    682:             throw new TypeError();
                    683:         }
                    684:         var t = Object(this);
                    685:         var len = t.length >>> 0;
                    686:         if (len === 0) {
                    687:             return -1;
                    688:         }
                    689:         var n = 0;
                    690:         if (arguments.length > 0) {
                    691:             n = Number(arguments[1]);
                    692:             if (n !== n) { // shortcut for verifying if it's NaN
                    693:                 n = 0;
                    694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    696:             }
                    697:         }
                    698:         if (n >= len) {
                    699:             return -1;
                    700:         }
                    701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    702:         for (; k < len; k++) {
                    703:             if (k in t && t[k] === searchElement) {
                    704:                 return k;
                    705:             }
                    706:         }
                    707:         return -1;
                    708:     }
                    709: }
                    710: 
                    711: // ]]>
                    712: </script>
                    713: 
                    714: ENDJS
                    715: 
                    716: }
                    717: 
1.876     raeburn   718: sub userbrowser_javascript {
                    719:     my $id_functions = &javascript_index_functions();
                    720:     return <<"ENDUSERBRW";
                    721: 
1.888     raeburn   722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   723:     var url = '/adm/pickuser?';
                    724:     var userdom = getDomainFromSelectbox(formname,udom);
                    725:     if (userdom != null) {
                    726:        if (userdom != '') {
                    727:            url += 'srchdom='+userdom+'&';
                    728:        }
                    729:     }
                    730:     url += 'form=' + formname + '&unameelement='+uname+
                    731:                                 '&udomelement='+udom+
                    732:                                 '&ulastelement='+ulast+
                    733:                                 '&ufirstelement='+ufirst+
                    734:                                 '&uemailelement='+uemail+
1.881     raeburn   735:                                 '&hideudomelement='+hideudom+
                    736:                                 '&coursedom='+crsdom;
1.888     raeburn   737:     if ((caller != null) && (caller != undefined)) {
                    738:         url += '&caller='+caller;
                    739:     }
1.876     raeburn   740:     var title = 'User_Browser';
                    741:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    742:     options += ',width=700,height=600';
                    743:     var stdeditbrowser = open(url,title,options,'1');
                    744:     stdeditbrowser.focus();
                    745: }
                    746: 
1.888     raeburn   747: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   748:     var formid = getFormIdByName(formname);
                    749:     if (formid > -1) {
1.888     raeburn   750:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   751:         var domid = getIndexByName(formid,udom);
                    752:         var hidedomid = getIndexByName(formid,origdom);
                    753:         if (hidedomid > -1) {
                    754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   755:             var unameval = document.forms[formid].elements[unameid].value;
                    756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    757:                 if (domid > -1) {
                    758:                     var slct = document.forms[formid].elements[domid];
                    759:                     if (slct.type == 'select-one') {
                    760:                         var i;
                    761:                         for (i=0;i<slct.length;i++) {
                    762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    763:                         }
                    764:                     }
                    765:                     if (slct.type == 'hidden') {
                    766:                         slct.value = fixeddom;
1.876     raeburn   767:                     }
                    768:                 }
1.468     raeburn   769:             }
                    770:         }
                    771:     }
1.876     raeburn   772:     return;
                    773: }
                    774: 
                    775: $id_functions
                    776: ENDUSERBRW
1.468     raeburn   777: }
                    778: 
                    779: sub setsec_javascript {
1.1075.2.31  raeburn   780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    782:         $communityrolestr);
                    783:     if ($role_element ne '') {
                    784:         my @allroles = ('st','ta','ep','in','ad');
                    785:         foreach my $crstype ('Course','Community') {
                    786:             if ($crstype eq 'Community') {
                    787:                 foreach my $role (@allroles) {
                    788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    789:                 }
                    790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    791:             } else {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    796:             }
                    797:         }
                    798:         $rolestr = '"'.join('","',@allroles).'"';
                    799:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    801:     }
1.468     raeburn   802:     my $setsections = qq|
                    803: function setSect(sectionlist) {
1.629     raeburn   804:     var sectionsArray = new Array();
                    805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    806:         sectionsArray = sectionlist.split(",");
                    807:     }
1.468     raeburn   808:     var numSections = sectionsArray.length;
                    809:     document.$formname.$sec_element.length = 0;
                    810:     if (numSections == 0) {
                    811:         document.$formname.$sec_element.multiple=false;
                    812:         document.$formname.$sec_element.size=1;
                    813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    814:     } else {
                    815:         if (numSections == 1) {
                    816:             document.$formname.$sec_element.multiple=false;
                    817:             document.$formname.$sec_element.size=1;
                    818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    821:         } else {
                    822:             for (var i=0; i<numSections; i++) {
                    823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    824:             }
                    825:             document.$formname.$sec_element.multiple=true
                    826:             if (numSections < 3) {
                    827:                 document.$formname.$sec_element.size=numSections;
                    828:             } else {
                    829:                 document.$formname.$sec_element.size=3;
                    830:             }
                    831:             document.$formname.$sec_element.options[0].selected = false
                    832:         }
                    833:     }
1.91      www       834: }
1.905     raeburn   835: 
                    836: function setRole(crstype) {
1.468     raeburn   837: |;
1.905     raeburn   838:     if ($role_element eq '') {
                    839:         $setsections .= '    return;
                    840: }
                    841: ';
                    842:     } else {
                    843:         $setsections .= qq|
                    844:     var elementLength = document.$formname.$role_element.length;
                    845:     var allroles = Array($rolestr);
                    846:     var courserolenames = Array($courserolestr);
                    847:     var communityrolenames = Array($communityrolestr);
                    848:     if (elementLength != undefined) {
                    849:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    850:             if (crstype == 'Course') {
                    851:                 return;
                    852:             } else {
                    853:                 allroles[5] = 'co';
                    854:                 for (var i=0; i<6; i++) {
                    855:                     document.$formname.$role_element.options[i].value = allroles[i];
                    856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    857:                 }
                    858:             }
                    859:         } else {
                    860:             if (crstype == 'Community') {
                    861:                 return;
                    862:             } else {
                    863:                 allroles[5] = 'cc';
                    864:                 for (var i=0; i<6; i++) {
                    865:                     document.$formname.$role_element.options[i].value = allroles[i];
                    866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    867:                 }
                    868:             }
                    869:         }
                    870:     }
                    871:     return;
                    872: }
                    873: |;
                    874:     }
1.1075.2.31  raeburn   875:     if ($credits_element) {
                    876:         $setsections .= qq|
                    877: function setCredits(defaultcredits) {
                    878:     document.$formname.$credits_element.value = defaultcredits;
                    879:     return;
                    880: }
                    881: |;
                    882:     }
1.468     raeburn   883:     return $setsections;
                    884: }
                    885: 
1.91      www       886: sub selectcourse_link {
1.909     raeburn   887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    888:        $typeelement) = @_;
                    889:    my $type = $selecttype;
1.871     raeburn   890:    my $linktext = &mt('Select Course');
                    891:    if ($selecttype eq 'Community') {
1.909     raeburn   892:        $linktext = &mt('Select Community');
1.906     raeburn   893:    } elsif ($selecttype eq 'Course/Community') {
                    894:        $linktext = &mt('Select Course/Community');
1.909     raeburn   895:        $type = '';
1.1019    raeburn   896:    } elsif ($selecttype eq 'Select') {
                    897:        $linktext = &mt('Select');
                    898:        $type = '';
1.871     raeburn   899:    }
1.787     bisitz    900:    return '<span class="LC_nobreak">'
                    901:          ."<a href='"
                    902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   905:          ."'>".$linktext.'</a>'
1.787     bisitz    906:          .'</span>';
1.74      www       907: }
1.42      matthew   908: 
1.653     raeburn   909: sub selectauthor_link {
                    910:    my ($form,$udom)=@_;
                    911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    912:           &mt('Select Author').'</a>';
                    913: }
                    914: 
1.876     raeburn   915: sub selectuser_link {
1.881     raeburn   916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   917:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   920:            ');">'.$linktext.'</a>';
1.876     raeburn   921: }
                    922: 
1.273     raeburn   923: sub check_uncheck_jscript {
                    924:     my $jscript = <<"ENDSCRT";
                    925: function checkAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   928:             if (!field[i].disabled) {
                    929:                 field[i].checked = true;
                    930:             }
1.273     raeburn   931:         }
                    932:     } else {
1.1075.2.14  raeburn   933:         if (!field.disabled) {
                    934:             field.checked = true;
                    935:         }
1.273     raeburn   936:     }
                    937: }
                    938:  
                    939: function uncheckAll(field) {
                    940:     if (field.length > 0) {
                    941:         for (i = 0; i < field.length; i++) {
                    942:             field[i].checked = false ;
1.543     albertel  943:         }
                    944:     } else {
1.273     raeburn   945:         field.checked = false ;
                    946:     }
                    947: }
                    948: ENDSCRT
                    949:     return $jscript;
                    950: }
                    951: 
1.656     www       952: sub select_timezone {
1.1075.2.115  raeburn   953:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    954:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   955:    if ($includeempty) {
                    956:        $output .= '<option value=""';
                    957:        if (($selected eq '') || ($selected eq 'local')) {
                    958:            $output .= ' selected="selected" ';
                    959:        }
                    960:        $output .= '> </option>';
                    961:    }
1.657     raeburn   962:    my @timezones = DateTime::TimeZone->all_names;
                    963:    foreach my $tzone (@timezones) {
                    964:        $output.= '<option value="'.$tzone.'"';
                    965:        if ($tzone eq $selected) {
                    966:            $output.=' selected="selected"';
                    967:        }
                    968:        $output.=">$tzone</option>\n";
1.656     www       969:    }
                    970:    $output.="</select>";
                    971:    return $output;
                    972: }
1.273     raeburn   973: 
1.687     raeburn   974: sub select_datelocale {
1.1075.2.115  raeburn   975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   977:     if ($includeempty) {
                    978:         $output .= '<option value=""';
                    979:         if ($selected eq '') {
                    980:             $output .= ' selected="selected" ';
                    981:         }
                    982:         $output .= '> </option>';
                    983:     }
1.1075.2.102  raeburn   984:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   985:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   986:     my @locales = DateTime::Locale->ids();
                    987:     foreach my $id (@locales) {
                    988:         if ($id ne '') {
                    989:             my ($en_terr,$native_terr);
                    990:             my $loc = DateTime::Locale->load($id);
                    991:             if (ref($loc)) {
                    992:                 $en_terr = $loc->name();
                    993:                 $native_terr = $loc->native_name();
1.687     raeburn   994:                 if (grep(/^en$/,@languages) || !@languages) {
                    995:                     if ($en_terr ne '') {
                    996:                         $locale_names{$id} = '('.$en_terr.')';
                    997:                     } elsif ($native_terr ne '') {
                    998:                         $locale_names{$id} = $native_terr;
                    999:                     }
                   1000:                 } else {
                   1001:                     if ($native_terr ne '') {
                   1002:                         $locale_names{$id} = $native_terr.' ';
                   1003:                     } elsif ($en_terr ne '') {
                   1004:                         $locale_names{$id} = '('.$en_terr.')';
                   1005:                     }
                   1006:                 }
1.1075.2.94  raeburn  1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1008:                 push(@possibles,$id);
1.687     raeburn  1009:             }
                   1010:         }
                   1011:     }
                   1012:     foreach my $item (sort(@possibles)) {
                   1013:         $output.= '<option value="'.$item.'"';
                   1014:         if ($item eq $selected) {
                   1015:             $output.=' selected="selected"';
                   1016:         }
                   1017:         $output.=">$item";
                   1018:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1019:             $output.='  '.$locale_names{$item};
1.687     raeburn  1020:         }
                   1021:         $output.="</option>\n";
                   1022:     }
                   1023:     $output.="</select>";
                   1024:     return $output;
                   1025: }
                   1026: 
1.792     raeburn  1027: sub select_language {
1.1075.2.115  raeburn  1028:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1029:     my %langchoices;
                   1030:     if ($includeempty) {
1.1075.2.32  raeburn  1031:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1032:     }
                   1033:     foreach my $id (&languageids()) {
                   1034:         my $code = &supportedlanguagecode($id);
                   1035:         if ($code) {
                   1036:             $langchoices{$code} = &plainlanguagedescription($id);
                   1037:         }
                   1038:     }
1.1075.2.32  raeburn  1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1041: }
                   1042: 
1.42      matthew  1043: =pod
1.36      matthew  1044: 
1.648     raeburn  1045: =item * &linked_select_forms(...)
1.36      matthew  1046: 
                   1047: linked_select_forms returns a string containing a <script></script> block
                   1048: and html for two <select> menus.  The select menus will be linked in that
                   1049: changing the value of the first menu will result in new values being placed
                   1050: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1051: order unless a defined order is provided.
1.36      matthew  1052: 
                   1053: linked_select_forms takes the following ordered inputs:
                   1054: 
                   1055: =over 4
                   1056: 
1.112     bowersj2 1057: =item * $formname, the name of the <form> tag
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstdefault, the default value for the first menu
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1066: 
1.112     bowersj2 1067: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1068: 
1.609     raeburn  1069: =item * $menuorder, the order of values in the first menu
                   1070: 
1.1075.2.31  raeburn  1071: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1072:         event for the first <select> tag
                   1073: 
                   1074: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1075:         event for the second <select> tag
                   1076: 
1.41      ng       1077: =back 
                   1078: 
1.36      matthew  1079: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1081: values for the first select menu.  The text that coincides with the 
1.41      ng       1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1083: and text for the second menu are given in the hash pointed to by 
                   1084: $menu{$choice1}->{'select2'}.  
                   1085: 
1.112     bowersj2 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1087:                        default => "B3",
                   1088:                        select2 => { 
                   1089:                            B1 => "Choice B1",
                   1090:                            B2 => "Choice B2",
                   1091:                            B3 => "Choice B3",
                   1092:                            B4 => "Choice B4"
1.609     raeburn  1093:                            },
                   1094:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1095:                    },
                   1096:                A2 => { text =>"Choice A2" ,
                   1097:                        default => "C2",
                   1098:                        select2 => { 
                   1099:                            C1 => "Choice C1",
                   1100:                            C2 => "Choice C2",
                   1101:                            C3 => "Choice C3"
1.609     raeburn  1102:                            },
                   1103:                        order => ['C2','C1','C3'],
1.112     bowersj2 1104:                    },
                   1105:                A3 => { text =>"Choice A3" ,
                   1106:                        default => "D6",
                   1107:                        select2 => { 
                   1108:                            D1 => "Choice D1",
                   1109:                            D2 => "Choice D2",
                   1110:                            D3 => "Choice D3",
                   1111:                            D4 => "Choice D4",
                   1112:                            D5 => "Choice D5",
                   1113:                            D6 => "Choice D6",
                   1114:                            D7 => "Choice D7"
1.609     raeburn  1115:                            },
                   1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1117:                    }
                   1118:                );
1.36      matthew  1119: 
                   1120: =cut
                   1121: 
                   1122: sub linked_select_forms {
                   1123:     my ($formname,
                   1124:         $middletext,
                   1125:         $firstdefault,
                   1126:         $firstselectname,
                   1127:         $secondselectname, 
1.609     raeburn  1128:         $hashref,
                   1129:         $menuorder,
1.1075.2.31  raeburn  1130:         $onchangefirst,
                   1131:         $onchangesecond
1.36      matthew  1132:         ) = @_;
                   1133:     my $second = "document.$formname.$secondselectname";
                   1134:     my $first = "document.$formname.$firstselectname";
                   1135:     # output the javascript to do the changing
                   1136:     my $result = '';
1.776     bisitz   1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1138:     $result.="// <![CDATA[\n";
1.36      matthew  1139:     $result.="var select2data = new Object();\n";
                   1140:     $" = '","';
                   1141:     my $debug = '';
                   1142:     foreach my $s1 (sort(keys(%$hashref))) {
                   1143:         $result.="select2data.d_$s1 = new Object();\n";        
                   1144:         $result.="select2data.d_$s1.def = new String('".
                   1145:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1146:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1149:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1150:         }
1.36      matthew  1151:         $result.="\"@s2values\");\n";
                   1152:         $result.="select2data.d_$s1.texts = new Array(";        
                   1153:         my @s2texts;
                   1154:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1156:         }
                   1157:         $result.="\"@s2texts\");\n";
                   1158:     }
                   1159:     $"=' ';
                   1160:     $result.= <<"END";
                   1161: 
                   1162: function select1_changed() {
                   1163:     // Determine new choice
                   1164:     var newvalue = "d_" + $first.value;
                   1165:     // update select2
                   1166:     var values     = select2data[newvalue].values;
                   1167:     var texts      = select2data[newvalue].texts;
                   1168:     var select2def = select2data[newvalue].def;
                   1169:     var i;
                   1170:     // out with the old
                   1171:     for (i = 0; i < $second.options.length; i++) {
                   1172:         $second.options[i] = null;
                   1173:     }
                   1174:     // in with the nuclear
                   1175:     for (i=0;i<values.length; i++) {
                   1176:         $second.options[i] = new Option(values[i]);
1.143     matthew  1177:         $second.options[i].value = values[i];
1.36      matthew  1178:         $second.options[i].text = texts[i];
                   1179:         if (values[i] == select2def) {
                   1180:             $second.options[i].selected = true;
                   1181:         }
                   1182:     }
                   1183: }
1.824     bisitz   1184: // ]]>
1.36      matthew  1185: </script>
                   1186: END
                   1187:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1189:     my @order = sort(keys(%{$hashref}));
                   1190:     if (ref($menuorder) eq 'ARRAY') {
                   1191:         @order = @{$menuorder};
                   1192:     }
                   1193:     foreach my $value (@order) {
1.36      matthew  1194:         $result.="    <option value=\"$value\" ";
1.253     albertel 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1197:     }
                   1198:     $result .= "</select>\n";
                   1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1200:     $result .= $middletext;
1.1075.2.31  raeburn  1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1202:     if ($onchangesecond) {
                   1203:         $result .= ' onchange="'.$onchangesecond.'"';
                   1204:     }
                   1205:     $result .= ">\n";
1.36      matthew  1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1207:     
                   1208:     my @secondorder = sort(keys(%select2));
                   1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1211:     }
                   1212:     foreach my $value (@secondorder) {
1.36      matthew  1213:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1215:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1216:     }
                   1217:     $result .= "</select>\n";
                   1218:     #    return $debug;
                   1219:     return $result;
                   1220: }   #  end of sub linked_select_forms {
                   1221: 
1.45      matthew  1222: =pod
1.44      bowersj2 1223: 
1.973     raeburn  1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1225: 
1.112     bowersj2 1226: Returns a string corresponding to an HTML link to the given help
                   1227: $topic, where $topic corresponds to the name of a .tex file in
                   1228: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1229: spaces. 
                   1230: 
                   1231: $text will optionally be linked to the same topic, allowing you to
                   1232: link text in addition to the graphic. If you do not want to link
                   1233: text, but wish to specify one of the later parameters, pass an
                   1234: empty string. 
                   1235: 
                   1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1237: the link will not open a new window. If false, the link will open
                   1238: a new window using Javascript. (Default is false.) 
                   1239: 
                   1240: $width and $height are optional numerical parameters that will
                   1241: override the width and height of the popped up window, which may
1.973     raeburn  1242: be useful for certain help topics with big pictures included.
                   1243: 
                   1244: $imgid is the id of the img tag used for the help icon. This may be
                   1245: used in a javascript call to switch the image src.  See 
                   1246: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1247: 
                   1248: =cut
                   1249: 
                   1250: sub help_open_topic {
1.973     raeburn  1251:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1252:     $text = "" if (not defined $text);
1.44      bowersj2 1253:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1254:     $width = 500 if (not defined $width);
1.44      bowersj2 1255:     $height = 400 if (not defined $height);
                   1256:     my $filename = $topic;
                   1257:     $filename =~ s/ /_/g;
                   1258: 
1.48      bowersj2 1259:     my $template = "";
                   1260:     my $link;
1.572     banghart 1261:     
1.159     www      1262:     $topic=~s/\W/\_/g;
1.44      bowersj2 1263: 
1.572     banghart 1264:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1265:         if ($env{'browser.mobile'}) {
                   1266: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1267:         } else {
                   1268:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1269:         }
1.1037    www      1270:     } elsif ($stayOnPage eq 'popup') {
                   1271:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1272:     } else {
1.48      bowersj2 1273: 	$link = "/adm/help/${filename}.hlp";
                   1274:     }
                   1275: 
                   1276:     # Add the text
1.755     neumanie 1277:     if ($text ne "") {	
1.763     bisitz   1278: 	$template.='<span class="LC_help_open_topic">'
                   1279:                   .'<a target="_top" href="'.$link.'">'
                   1280:                   .$text.'</a>';
1.48      bowersj2 1281:     }
                   1282: 
1.763     bisitz   1283:     # (Always) Add the graphic
1.179     matthew  1284:     my $title = &mt('Online Help');
1.667     raeburn  1285:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1286:     if ($imgid ne '') {
                   1287:         $imgid = ' id="'.$imgid.'"';
                   1288:     }
1.763     bisitz   1289:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1290:               .'<img src="'.$helpicon.'" border="0"'
                   1291:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1292:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1293:               .' /></a>';
                   1294:     if ($text ne "") {	
                   1295:         $template.='</span>';
                   1296:     }
1.44      bowersj2 1297:     return $template;
                   1298: 
1.106     bowersj2 1299: }
                   1300: 
                   1301: # This is a quicky function for Latex cheatsheet editing, since it 
                   1302: # appears in at least four places
                   1303: sub helpLatexCheatsheet {
1.1037    www      1304:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1305:     my $out;
1.106     bowersj2 1306:     my $addOther = '';
1.732     raeburn  1307:     if ($topic) {
1.1037    www      1308: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1309:     }
                   1310:     $out = '<span>' # Start cheatsheet
                   1311: 	  .$addOther
                   1312:           .'<span>'
1.1037    www      1313: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span> <span>'
1.1037    www      1315: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1316: 	  .'</span>';
1.732     raeburn  1317:     unless ($not_author) {
1.763     bisitz   1318:         $out .= ' <span>'
1.1037    www      1319: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320: 	       .'</span> <span>'
1.1075.2.78  raeburn  1321:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1322:                .'</span>';
1.732     raeburn  1323:     }
1.763     bisitz   1324:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1325:     return $out;
1.172     www      1326: }
                   1327: 
1.430     albertel 1328: sub general_help {
                   1329:     my $helptopic='Student_Intro';
                   1330:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1331: 	$helptopic='Authoring_Intro';
1.907     raeburn  1332:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1333: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1334:     } elsif ($env{'request.role'}=~/^dc/) {
                   1335:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1336:     }
                   1337:     return $helptopic;
                   1338: }
                   1339: 
                   1340: sub update_help_link {
                   1341:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1342:     my $origurl = $ENV{'REQUEST_URI'};
                   1343:     $origurl=~s|^/~|/priv/|;
                   1344:     my $timestamp = time;
                   1345:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1346:         $$datum = &escape($$datum);
                   1347:     }
                   1348: 
                   1349:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1350:     my $output .= <<"ENDOUTPUT";
                   1351: <script type="text/javascript">
1.824     bisitz   1352: // <![CDATA[
1.430     albertel 1353: banner_link = '$banner_link';
1.824     bisitz   1354: // ]]>
1.430     albertel 1355: </script>
                   1356: ENDOUTPUT
                   1357:     return $output;
                   1358: }
                   1359: 
                   1360: # now just updates the help link and generates a blue icon
1.193     raeburn  1361: sub help_open_menu {
1.430     albertel 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1363: 	= @_;    
1.949     droeschl 1364:     $stayOnPage = 1;
1.430     albertel 1365:     my $output;
                   1366:     if ($component_help) {
                   1367: 	if (!$text) {
                   1368: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1369: 				       $width,$height);
                   1370: 	} else {
                   1371: 	    my $help_text;
                   1372: 	    $help_text=&unescape($topic);
                   1373: 	    $output='<table><tr><td>'.
                   1374: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1375: 				 $width,$height).'</td></tr></table>';
                   1376: 	}
                   1377:     }
                   1378:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1379:     return $output.$banner_link;
                   1380: }
                   1381: 
                   1382: sub top_nav_help {
                   1383:     my ($text) = @_;
1.436     albertel 1384:     $text = &mt($text);
1.1075.2.60  raeburn  1385:     my $stay_on_page;
                   1386:     unless ($env{'environment.remote'} eq 'on') {
                   1387:         $stay_on_page = 1;
                   1388:     }
1.1075.2.61  raeburn  1389:     my ($link,$banner_link);
                   1390:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1391:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1392: 	                         : "javascript:helpMenu('open')";
                   1393:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1394:     }
1.201     raeburn  1395:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1396:     if ($link) {
                   1397:         return <<"END";
1.436     albertel 1398: $banner_link
1.1075.2.56  raeburn  1399: <a href="$link" title="$title">$text</a>
1.436     albertel 1400: END
1.1075.2.61  raeburn  1401:     } else {
                   1402:         return '&nbsp;'.$text.'&nbsp;';
                   1403:     }
1.436     albertel 1404: }
                   1405: 
                   1406: sub help_menu_js {
1.1075.2.52  raeburn  1407:     my ($httphost) = @_;
1.949     droeschl 1408:     my $stayOnPage = 1;
1.436     albertel 1409:     my $width = 620;
                   1410:     my $height = 600;
1.430     albertel 1411:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1412:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1413:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1414:     my $start_page =
                   1415:         &Apache::loncommon::start_page('Help Menu', undef,
                   1416: 				       {'frameset'    => 1,
                   1417: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1418:                                         'use_absolute' => $httphost,
1.331     albertel 1419: 					'add_entries' => {
                   1420: 					    'border' => '0',
1.579     raeburn  1421: 					    'rows'   => "110,*",},});
1.331     albertel 1422:     my $end_page =
                   1423:         &Apache::loncommon::end_page({'frameset' => 1,
                   1424: 				      'js_ready' => 1,});
                   1425: 
1.436     albertel 1426:     my $template .= <<"ENDTEMPLATE";
                   1427: <script type="text/javascript">
1.877     bisitz   1428: // <![CDATA[
1.253     albertel 1429: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1430: var banner_link = '';
1.243     raeburn  1431: function helpMenu(target) {
                   1432:     var caller = this;
                   1433:     if (target == 'open') {
                   1434:         var newWindow = null;
                   1435:         try {
1.262     albertel 1436:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1437:         }
                   1438:         catch(error) {
                   1439:             writeHelp(caller);
                   1440:             return;
                   1441:         }
                   1442:         if (newWindow) {
                   1443:             caller = newWindow;
                   1444:         }
1.193     raeburn  1445:     }
1.243     raeburn  1446:     writeHelp(caller);
                   1447:     return;
                   1448: }
                   1449: function writeHelp(caller) {
1.1075.2.61  raeburn  1450:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1451:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1452:     caller.document.close();
                   1453:     caller.focus();
1.193     raeburn  1454: }
1.877     bisitz   1455: // END LON-CAPA Internal -->
1.253     albertel 1456: // ]]>
1.436     albertel 1457: </script>
1.193     raeburn  1458: ENDTEMPLATE
                   1459:     return $template;
                   1460: }
                   1461: 
1.172     www      1462: sub help_open_bug {
                   1463:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1464:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1465:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1466:     $text = "" if (not defined $text);
                   1467: 	$stayOnPage=1;
1.184     albertel 1468:     $width = 600 if (not defined $width);
                   1469:     $height = 600 if (not defined $height);
1.172     www      1470: 
                   1471:     $topic=~s/\W+/\+/g;
                   1472:     my $link='';
                   1473:     my $template='';
1.379     albertel 1474:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1475: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1476:     if (!$stayOnPage)
                   1477:     {
                   1478: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1479:     }
                   1480:     else
                   1481:     {
                   1482: 	$link = $url;
                   1483:     }
                   1484:     # Add the text
                   1485:     if ($text ne "")
                   1486:     {
                   1487: 	$template .= 
                   1488:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1489:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1490:     }
                   1491: 
                   1492:     # Add the graphic
1.179     matthew  1493:     my $title = &mt('Report a Bug');
1.215     albertel 1494:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1495:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1496:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1497: ENDTEMPLATE
                   1498:     if ($text ne '') { $template.='</td></tr></table>' };
                   1499:     return $template;
                   1500: 
                   1501: }
                   1502: 
                   1503: sub help_open_faq {
                   1504:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1505:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1506:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1507:     $text = "" if (not defined $text);
                   1508: 	$stayOnPage=1;
                   1509:     $width = 350 if (not defined $width);
                   1510:     $height = 400 if (not defined $height);
                   1511: 
                   1512:     $topic=~s/\W+/\+/g;
                   1513:     my $link='';
                   1514:     my $template='';
                   1515:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1516:     if (!$stayOnPage)
                   1517:     {
                   1518: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1519:     }
                   1520:     else
                   1521:     {
                   1522: 	$link = $url;
                   1523:     }
                   1524: 
                   1525:     # Add the text
                   1526:     if ($text ne "")
                   1527:     {
                   1528: 	$template .= 
1.173     www      1529:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1530:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1531:     }
                   1532: 
                   1533:     # Add the graphic
1.179     matthew  1534:     my $title = &mt('View the FAQ');
1.215     albertel 1535:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1536:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1537:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1538: ENDTEMPLATE
                   1539:     if ($text ne '') { $template.='</td></tr></table>' };
                   1540:     return $template;
                   1541: 
1.44      bowersj2 1542: }
1.37      matthew  1543: 
1.180     matthew  1544: ###############################################################
                   1545: ###############################################################
                   1546: 
1.45      matthew  1547: =pod
                   1548: 
1.648     raeburn  1549: =item * &change_content_javascript():
1.256     matthew  1550: 
                   1551: This and the next function allow you to create small sections of an
                   1552: otherwise static HTML page that you can update on the fly with
                   1553: Javascript, even in Netscape 4.
                   1554: 
                   1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1556: must be written to the HTML page once. It will prove the Javascript
                   1557: function "change(name, content)". Calling the change function with the
                   1558: name of the section 
                   1559: you want to update, matching the name passed to C<changable_area>, and
                   1560: the new content you want to put in there, will put the content into
                   1561: that area.
                   1562: 
                   1563: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1564: to contain room for the original contents. You need to "make space"
                   1565: for whatever changes you wish to make, and be B<sure> to check your
                   1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1567: it's adequate for updating a one-line status display, but little more.
                   1568: This script will set the space to 100% width, so you only need to
                   1569: worry about height in Netscape 4.
                   1570: 
                   1571: Modern browsers are much less limiting, and if you can commit to the
                   1572: user not using Netscape 4, this feature may be used freely with
                   1573: pretty much any HTML.
                   1574: 
                   1575: =cut
                   1576: 
                   1577: sub change_content_javascript {
                   1578:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1579:     if ($env{'browser.type'} eq 'netscape' &&
                   1580: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1581: 	return (<<NETSCAPE4);
                   1582: 	function change(name, content) {
                   1583: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1584: 	    doc.open();
                   1585: 	    doc.write(content);
                   1586: 	    doc.close();
                   1587: 	}
                   1588: NETSCAPE4
                   1589:     } else {
                   1590: 	# Otherwise, we need to use semi-standards-compliant code
                   1591: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1592: 	# is really scary, and every useful browser supports it
                   1593: 	return (<<DOMBASED);
                   1594: 	function change(name, content) {
                   1595: 	    element = document.getElementById(name);
                   1596: 	    element.innerHTML = content;
                   1597: 	}
                   1598: DOMBASED
                   1599:     }
                   1600: }
                   1601: 
                   1602: =pod
                   1603: 
1.648     raeburn  1604: =item * &changable_area($name,$origContent):
1.256     matthew  1605: 
                   1606: This provides a "changable area" that can be modified on the fly via
                   1607: the Javascript code provided in C<change_content_javascript>. $name is
                   1608: the name you will use to reference the area later; do not repeat the
                   1609: same name on a given HTML page more then once. $origContent is what
                   1610: the area will originally contain, which can be left blank.
                   1611: 
                   1612: =cut
                   1613: 
                   1614: sub changable_area {
                   1615:     my ($name, $origContent) = @_;
                   1616: 
1.258     albertel 1617:     if ($env{'browser.type'} eq 'netscape' &&
                   1618: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1619: 	# If this is netscape 4, we need to use the Layer tag
                   1620: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1621:     } else {
                   1622: 	return "<span id='$name'>$origContent</span>";
                   1623:     }
                   1624: }
                   1625: 
                   1626: =pod
                   1627: 
1.648     raeburn  1628: =item * &viewport_geometry_js 
1.590     raeburn  1629: 
                   1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1631: 
                   1632: =cut
                   1633: 
                   1634: 
                   1635: sub viewport_geometry_js { 
                   1636:     return <<"GEOMETRY";
                   1637: var Geometry = {};
                   1638: function init_geometry() {
                   1639:     if (Geometry.init) { return };
                   1640:     Geometry.init=1;
                   1641:     if (window.innerHeight) {
                   1642:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1643:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1644:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1645:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1646:     }
                   1647:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1648:         Geometry.getViewportHeight =
                   1649:             function() { return document.documentElement.clientHeight; };
                   1650:         Geometry.getViewportWidth =
                   1651:             function() { return document.documentElement.clientWidth; };
                   1652: 
                   1653:         Geometry.getHorizontalScroll =
                   1654:             function() { return document.documentElement.scrollLeft; };
                   1655:         Geometry.getVerticalScroll =
                   1656:             function() { return document.documentElement.scrollTop; };
                   1657:     }
                   1658:     else if (document.body.clientHeight) {
                   1659:         Geometry.getViewportHeight =
                   1660:             function() { return document.body.clientHeight; };
                   1661:         Geometry.getViewportWidth =
                   1662:             function() { return document.body.clientWidth; };
                   1663:         Geometry.getHorizontalScroll =
                   1664:             function() { return document.body.scrollLeft; };
                   1665:         Geometry.getVerticalScroll =
                   1666:             function() { return document.body.scrollTop; };
                   1667:     }
                   1668: }
                   1669: 
                   1670: GEOMETRY
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_size_js()
1.590     raeburn  1676: 
                   1677: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1678: 
                   1679: =cut
                   1680: 
                   1681: sub viewport_size_js {
                   1682:     my $geometry = &viewport_geometry_js();
                   1683:     return <<"DIMS";
                   1684: 
                   1685: $geometry
                   1686: 
                   1687: function getViewportDims(width,height) {
                   1688:     init_geometry();
                   1689:     width.value = Geometry.getViewportWidth();
                   1690:     height.value = Geometry.getViewportHeight();
                   1691:     return;
                   1692: }
                   1693: 
                   1694: DIMS
                   1695: }
                   1696: 
                   1697: =pod
                   1698: 
1.648     raeburn  1699: =item * &resize_textarea_js()
1.565     albertel 1700: 
                   1701: emits the needed javascript to resize a textarea to be as big as possible
                   1702: 
                   1703: creates a function resize_textrea that takes two IDs first should be
                   1704: the id of the element to resize, second should be the id of a div that
                   1705: surrounds everything that comes after the textarea, this routine needs
                   1706: to be attached to the <body> for the onload and onresize events.
                   1707: 
1.648     raeburn  1708: =back
1.565     albertel 1709: 
                   1710: =cut
                   1711: 
                   1712: sub resize_textarea_js {
1.590     raeburn  1713:     my $geometry = &viewport_geometry_js();
1.565     albertel 1714:     return <<"RESIZE";
                   1715:     <script type="text/javascript">
1.824     bisitz   1716: // <![CDATA[
1.590     raeburn  1717: $geometry
1.565     albertel 1718: 
1.588     albertel 1719: function getX(element) {
                   1720:     var x = 0;
                   1721:     while (element) {
                   1722: 	x += element.offsetLeft;
                   1723: 	element = element.offsetParent;
                   1724:     }
                   1725:     return x;
                   1726: }
                   1727: function getY(element) {
                   1728:     var y = 0;
                   1729:     while (element) {
                   1730: 	y += element.offsetTop;
                   1731: 	element = element.offsetParent;
                   1732:     }
                   1733:     return y;
                   1734: }
                   1735: 
                   1736: 
1.565     albertel 1737: function resize_textarea(textarea_id,bottom_id) {
                   1738:     init_geometry();
                   1739:     var textarea        = document.getElementById(textarea_id);
                   1740:     //alert(textarea);
                   1741: 
1.588     albertel 1742:     var textarea_top    = getY(textarea);
1.565     albertel 1743:     var textarea_height = textarea.offsetHeight;
                   1744:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1745:     var bottom_top      = getY(bottom);
1.565     albertel 1746:     var bottom_height   = bottom.offsetHeight;
                   1747:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1748:     var fudge           = 23;
1.565     albertel 1749:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1750:     if (new_height < 300) {
                   1751: 	new_height = 300;
                   1752:     }
                   1753:     textarea.style.height=new_height+'px';
                   1754: }
1.824     bisitz   1755: // ]]>
1.565     albertel 1756: </script>
                   1757: RESIZE
                   1758: 
                   1759: }
                   1760: 
1.1075.2.112  raeburn  1761: sub colorfuleditor_js {
                   1762:     return <<"COLORFULEDIT"
                   1763: <script type="text/javascript">
                   1764: // <![CDATA[>
                   1765:     function fold_box(curDepth, lastresource){
                   1766: 
                   1767:     // we need a list because there can be several blocks you need to fold in one tag
                   1768:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1769:     // but there is only one folding button per tag
                   1770:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1771: 
                   1772:         if(block.item(0).style.display == 'none'){
                   1773: 
                   1774:             foldbutton.value = '@{[&mt("Hide")]}';
                   1775:             for (i = 0; i < block.length; i++){
                   1776:                 block.item(i).style.display = '';
                   1777:             }
                   1778:         }else{
                   1779: 
                   1780:             foldbutton.value = '@{[&mt("Show")]}';
                   1781:             for (i = 0; i < block.length; i++){
                   1782:                 // block.item(i).style.visibility = 'collapse';
                   1783:                 block.item(i).style.display = 'none';
                   1784:             }
                   1785:         };
                   1786:         saveState(lastresource);
                   1787:     }
                   1788: 
                   1789:     function saveState (lastresource) {
                   1790: 
                   1791:         var tag_list = getTagList();
                   1792:         if(tag_list != null){
                   1793:             var timestamp = new Date().getTime();
                   1794:             var key = lastresource;
                   1795: 
                   1796:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1797:             // starting with timestamp
                   1798:             var value = timestamp+';';
                   1799: 
                   1800:             // building the list of key-value pairs
                   1801:             for(var i = 0; i < tag_list.length; i++){
                   1802:                 value += tag_list[i]+',';
                   1803:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1804:             }
                   1805: 
                   1806:             // only iterate whole storage if nothing to override
                   1807:             if(localStorage.getItem(key) == null){
                   1808: 
                   1809:                 // prevent storage from growing large
                   1810:                 if(localStorage.length > 50){
                   1811:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1812:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1813:                     var oldest_key;
                   1814: 
                   1815:                     for(var i = 1; i < localStorage.length; i++){
                   1816:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1817:                             oldest_key = localStorage.key(i);
                   1818:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1819:                         }
                   1820:                     }
                   1821:                     localStorage.removeItem(oldest_key);
                   1822:                 }
                   1823:             }
                   1824:             localStorage.setItem(key,value);
                   1825:         }
                   1826:     }
                   1827: 
                   1828:     // restore folding status of blocks (on page load)
                   1829:     function restoreState (lastresource) {
                   1830:         if(localStorage.getItem(lastresource) != null){
                   1831:             var key = lastresource;
                   1832:             var value = localStorage.getItem(key);
                   1833:             var regex_delTimestamp = /^\d+;/;
                   1834: 
                   1835:             value.replace(regex_delTimestamp, '');
                   1836: 
                   1837:             var valueArr = value.split(';');
                   1838:             var pairs;
                   1839:             var elements;
                   1840:             for (var i = 0; i < valueArr.length; i++){
                   1841:                 pairs = valueArr[i].split(',');
                   1842:                 elements = document.getElementsByName(pairs[0]);
                   1843: 
                   1844:                 for (var j = 0; j < elements.length; j++){
                   1845:                     elements[j].style.display = pairs[1];
                   1846:                     if (pairs[1] == "none"){
                   1847:                         var regex_id = /([_\\d]+)\$/;
                   1848:                         regex_id.exec(pairs[0]);
                   1849:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1850:                     }
                   1851:                 }
                   1852:             }
                   1853:         }
                   1854:     }
                   1855: 
                   1856:     function getTagList () {
                   1857: 
                   1858:         var stringToSearch = document.lonhomework.innerHTML;
                   1859: 
                   1860:         var ret = new Array();
                   1861:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1862:         var tag_list = stringToSearch.match(regex_findBlock);
                   1863: 
                   1864:         if(tag_list != null){
                   1865:             for(var i = 0; i < tag_list.length; i++){
                   1866:                 ret.push(tag_list[i].replace(/"/, ''));
                   1867:             }
                   1868:         }
                   1869:         return ret;
                   1870:     }
                   1871: 
                   1872:     function saveScrollPosition (resource) {
                   1873:         var tag_list = getTagList();
                   1874: 
                   1875:         // we dont always want to jump to the first block
                   1876:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1877:         if(\$(window).scrollTop() > 170){
                   1878:             if(tag_list != null){
                   1879:                 var result;
                   1880:                 for(var i = 0; i < tag_list.length; i++){
                   1881:                     if(isElementInViewport(tag_list[i])){
                   1882:                         result += tag_list[i]+';';
                   1883:                     }
                   1884:                 }
                   1885:                 sessionStorage.setItem('anchor_'+resource, result);
                   1886:             }
                   1887:         } else {
                   1888:             // we dont need to save zero, just delete the item to leave everything tidy
                   1889:             sessionStorage.removeItem('anchor_'+resource);
                   1890:         }
                   1891:     }
                   1892: 
                   1893:     function restoreScrollPosition(resource){
                   1894: 
                   1895:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1896:         if(elem != null){
                   1897:             var tag_list = elem.split(';');
                   1898:             var elem_list;
                   1899: 
                   1900:             for(var i = 0; i < tag_list.length; i++){
                   1901:                 elem_list = document.getElementsByName(tag_list[i]);
                   1902: 
                   1903:                 if(elem_list.length > 0){
                   1904:                     elem = elem_list[0];
                   1905:                     break;
                   1906:                 }
                   1907:             }
                   1908:             elem.scrollIntoView();
                   1909:         }
                   1910:     }
                   1911: 
                   1912:     function isElementInViewport(el) {
                   1913: 
                   1914:         // change to last element instead of first
                   1915:         var elem = document.getElementsByName(el);
                   1916:         var rect = elem[0].getBoundingClientRect();
                   1917: 
                   1918:         return (
                   1919:             rect.top >= 0 &&
                   1920:             rect.left >= 0 &&
                   1921:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1922:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1923:         );
                   1924:     }
                   1925: 
                   1926:     function autosize(depth){
                   1927:         var cmInst = window['cm'+depth];
                   1928:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1929: 
                   1930:         // is fixed size, switching to dynamic
                   1931:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1932:             cmInst.setSize("","auto");
                   1933:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1934:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1935: 
                   1936:         // is dynamic size, switching to fixed
                   1937:         } else {
                   1938:             cmInst.setSize("","300px");
                   1939:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1940:             sessionStorage.removeItem("autosized_"+depth);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: 
                   1945: 
                   1946: // ]]>
                   1947: </script>
                   1948: COLORFULEDIT
                   1949: }
                   1950: 
                   1951: sub xmleditor_js {
                   1952:     return <<XMLEDIT
                   1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1954: <script type="text/javascript">
                   1955: // <![CDATA[>
                   1956: 
                   1957:     function saveScrollPosition (resource) {
                   1958: 
                   1959:         var scrollPos = \$(window).scrollTop();
                   1960:         sessionStorage.setItem(resource,scrollPos);
                   1961:     }
                   1962: 
                   1963:     function restoreScrollPosition(resource){
                   1964: 
                   1965:         var scrollPos = sessionStorage.getItem(resource);
                   1966:         \$(window).scrollTop(scrollPos);
                   1967:     }
                   1968: 
                   1969:     // unless internet explorer
                   1970:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1971: 
                   1972:         \$(document).ready(function() {
                   1973:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1974:         });
                   1975:     }
                   1976: 
                   1977:     // inserts text at cursor position into codemirror (xml editor only)
                   1978:     function insertText(text){
                   1979:         cm.focus();
                   1980:         var curPos = cm.getCursor();
                   1981:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1982:     }
                   1983: // ]]>
                   1984: </script>
                   1985: XMLEDIT
                   1986: }
                   1987: 
                   1988: sub insert_folding_button {
                   1989:     my $curDepth = $Apache::lonxml::curdepth;
                   1990:     my $lastresource = $env{'request.ambiguous'};
                   1991: 
                   1992:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1993:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1994: }
                   1995: 
                   1996: 
1.565     albertel 1997: =pod
                   1998: 
1.256     matthew  1999: =head1 Excel and CSV file utility routines
                   2000: 
                   2001: =cut
                   2002: 
                   2003: ###############################################################
                   2004: ###############################################################
                   2005: 
                   2006: =pod
                   2007: 
1.1075.2.56  raeburn  2008: =over 4
                   2009: 
1.648     raeburn  2010: =item * &csv_translate($text) 
1.37      matthew  2011: 
1.185     www      2012: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2013: format.
                   2014: 
                   2015: =cut
                   2016: 
1.180     matthew  2017: ###############################################################
                   2018: ###############################################################
1.37      matthew  2019: sub csv_translate {
                   2020:     my $text = shift;
                   2021:     $text =~ s/\"/\"\"/g;
1.209     albertel 2022:     $text =~ s/\n/ /g;
1.37      matthew  2023:     return $text;
                   2024: }
1.180     matthew  2025: 
                   2026: ###############################################################
                   2027: ###############################################################
                   2028: 
                   2029: =pod
                   2030: 
1.648     raeburn  2031: =item * &define_excel_formats()
1.180     matthew  2032: 
                   2033: Define some commonly used Excel cell formats.
                   2034: 
                   2035: Currently supported formats:
                   2036: 
                   2037: =over 4
                   2038: 
                   2039: =item header
                   2040: 
                   2041: =item bold
                   2042: 
                   2043: =item h1
                   2044: 
                   2045: =item h2
                   2046: 
                   2047: =item h3
                   2048: 
1.256     matthew  2049: =item h4
                   2050: 
                   2051: =item i
                   2052: 
1.180     matthew  2053: =item date
                   2054: 
                   2055: =back
                   2056: 
                   2057: Inputs: $workbook
                   2058: 
                   2059: Returns: $format, a hash reference.
                   2060: 
1.1057    foxr     2061: 
1.180     matthew  2062: =cut
                   2063: 
                   2064: ###############################################################
                   2065: ###############################################################
                   2066: sub define_excel_formats {
                   2067:     my ($workbook) = @_;
                   2068:     my $format;
                   2069:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2070:                                                 bottom    => 1,
                   2071:                                                 align     => 'center');
                   2072:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2073:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2074:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2075:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2076:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2077:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2078:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2079:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2080:     return $format;
                   2081: }
                   2082: 
                   2083: ###############################################################
                   2084: ###############################################################
1.113     bowersj2 2085: 
                   2086: =pod
                   2087: 
1.648     raeburn  2088: =item * &create_workbook()
1.255     matthew  2089: 
                   2090: Create an Excel worksheet.  If it fails, output message on the
                   2091: request object and return undefs.
                   2092: 
                   2093: Inputs: Apache request object
                   2094: 
                   2095: Returns (undef) on failure, 
                   2096:     Excel worksheet object, scalar with filename, and formats 
                   2097:     from &Apache::loncommon::define_excel_formats on success
                   2098: 
                   2099: =cut
                   2100: 
                   2101: ###############################################################
                   2102: ###############################################################
                   2103: sub create_workbook {
                   2104:     my ($r) = @_;
                   2105:         #
                   2106:     # Create the excel spreadsheet
                   2107:     my $filename = '/prtspool/'.
1.258     albertel 2108:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2109:         time.'_'.rand(1000000000).'.xls';
                   2110:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2111:     if (! defined($workbook)) {
                   2112:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2113:         $r->print(
                   2114:             '<p class="LC_error">'
                   2115:            .&mt('Problems occurred in creating the new Excel file.')
                   2116:            .' '.&mt('This error has been logged.')
                   2117:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2118:            .'</p>'
                   2119:         );
1.255     matthew  2120:         return (undef);
                   2121:     }
                   2122:     #
1.1014    foxr     2123:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2124:     #
                   2125:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2126:     return ($workbook,$filename,$format);
                   2127: }
                   2128: 
                   2129: ###############################################################
                   2130: ###############################################################
                   2131: 
                   2132: =pod
                   2133: 
1.648     raeburn  2134: =item * &create_text_file()
1.113     bowersj2 2135: 
1.542     raeburn  2136: Create a file to write to and eventually make available to the user.
1.256     matthew  2137: If file creation fails, outputs an error message on the request object and 
                   2138: return undefs.
1.113     bowersj2 2139: 
1.256     matthew  2140: Inputs: Apache request object, and file suffix
1.113     bowersj2 2141: 
1.256     matthew  2142: Returns (undef) on failure, 
                   2143:     Filehandle and filename on success.
1.113     bowersj2 2144: 
                   2145: =cut
                   2146: 
1.256     matthew  2147: ###############################################################
                   2148: ###############################################################
                   2149: sub create_text_file {
                   2150:     my ($r,$suffix) = @_;
                   2151:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2152:     my $fh;
                   2153:     my $filename = '/prtspool/'.
1.258     albertel 2154:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2155:         time.'_'.rand(1000000000).'.'.$suffix;
                   2156:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2157:     if (! defined($fh)) {
                   2158:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2159:         $r->print(
                   2160:             '<p class="LC_error">'
                   2161:            .&mt('Problems occurred in creating the output file.')
                   2162:            .' '.&mt('This error has been logged.')
                   2163:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2164:            .'</p>'
                   2165:         );
1.113     bowersj2 2166:     }
1.256     matthew  2167:     return ($fh,$filename)
1.113     bowersj2 2168: }
                   2169: 
                   2170: 
1.256     matthew  2171: =pod 
1.113     bowersj2 2172: 
                   2173: =back
                   2174: 
                   2175: =cut
1.37      matthew  2176: 
                   2177: ###############################################################
1.33      matthew  2178: ##        Home server <option> list generating code          ##
                   2179: ###############################################################
1.35      matthew  2180: 
1.169     www      2181: # ------------------------------------------
                   2182: 
                   2183: sub domain_select {
                   2184:     my ($name,$value,$multiple)=@_;
                   2185:     my %domains=map { 
1.514     albertel 2186: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2187:     } &Apache::lonnet::all_domains();
1.169     www      2188:     if ($multiple) {
                   2189: 	$domains{''}=&mt('Any domain');
1.550     albertel 2190: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2191: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2192:     } else {
1.550     albertel 2193: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2194: 	return &select_form($name,$value,\%domains);
1.169     www      2195:     }
                   2196: }
                   2197: 
1.282     albertel 2198: #-------------------------------------------
                   2199: 
                   2200: =pod
                   2201: 
1.519     raeburn  2202: =head1 Routines for form select boxes
                   2203: 
                   2204: =over 4
                   2205: 
1.648     raeburn  2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2207: 
                   2208: Returns a string containing a <select> element int multiple mode
                   2209: 
                   2210: 
                   2211: Args:
                   2212:   $name - name of the <select> element
1.506     raeburn  2213:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2214:   $size - number of rows long the select element is
1.283     albertel 2215:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2216:           (shown text should already have been &mt())
1.506     raeburn  2217:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2218: 
1.282     albertel 2219: =cut
                   2220: 
                   2221: #-------------------------------------------
1.169     www      2222: sub multiple_select_form {
1.284     albertel 2223:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2224:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2225:     my $output='';
1.191     matthew  2226:     if (! defined($size)) {
                   2227:         $size = 4;
1.283     albertel 2228:         if (scalar(keys(%$hash))<4) {
                   2229:             $size = scalar(keys(%$hash));
1.191     matthew  2230:         }
                   2231:     }
1.734     bisitz   2232:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2233:     my @order;
1.506     raeburn  2234:     if (ref($order) eq 'ARRAY')  {
                   2235:         @order = @{$order};
                   2236:     } else {
                   2237:         @order = sort(keys(%$hash));
1.501     banghart 2238:     }
                   2239:     if (exists($$hash{'select_form_order'})) {
                   2240:         @order = @{$$hash{'select_form_order'}};
                   2241:     }
                   2242:         
1.284     albertel 2243:     foreach my $key (@order) {
1.356     albertel 2244:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2245:         $output.='selected="selected" ' if ($selected{$key});
                   2246:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2247:     }
                   2248:     $output.="</select>\n";
                   2249:     return $output;
                   2250: }
                   2251: 
1.88      www      2252: #-------------------------------------------
                   2253: 
                   2254: =pod
                   2255: 
1.1075.2.115  raeburn  2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2257: 
                   2258: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2259: allow a user to select options from a ref to a hash containing:
                   2260: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2261: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2262: An optional arg -- $readonly -- if true will cause the select form
                   2263: to be disabled, e.g., for the case where an instructor has a section-
                   2264: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2265: 
1.88      www      2266: See lonrights.pm for an example invocation and use.
                   2267: 
                   2268: =cut
                   2269: 
                   2270: #-------------------------------------------
                   2271: sub select_form {
1.1075.2.115  raeburn  2272:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2273:     return unless (ref($hashref) eq 'HASH');
                   2274:     if ($onchange) {
                   2275:         $onchange = ' onchange="'.$onchange.'"';
                   2276:     }
1.1075.2.129  raeburn  2277:     my $disabled;
                   2278:     if ($readonly) {
                   2279:         $disabled = ' disabled="disabled"';
                   2280:     }
                   2281:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2282:     my @keys;
1.970     raeburn  2283:     if (exists($hashref->{'select_form_order'})) {
                   2284: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2285:     } else {
1.970     raeburn  2286: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2287:     }
1.356     albertel 2288:     foreach my $key (@keys) {
                   2289:         $selectform.=
                   2290: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2291:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2292:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2293:     }
                   2294:     $selectform.="</select>";
                   2295:     return $selectform;
                   2296: }
                   2297: 
1.475     www      2298: # For display filters
                   2299: 
                   2300: sub display_filter {
1.1074    raeburn  2301:     my ($context) = @_;
1.475     www      2302:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2303:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2304:     my $phraseinput = 'hidden';
                   2305:     my $includeinput = 'hidden';
                   2306:     my ($checked,$includetypestext);
                   2307:     if ($env{'form.displayfilter'} eq 'containing') {
                   2308:         $phraseinput = 'text'; 
                   2309:         if ($context eq 'parmslog') {
                   2310:             $includeinput = 'checkbox';
                   2311:             if ($env{'form.includetypes'}) {
                   2312:                 $checked = ' checked="checked"';
                   2313:             }
                   2314:             $includetypestext = &mt('Include parameter types');
                   2315:         }
                   2316:     } else {
                   2317:         $includetypestext = '&nbsp;';
                   2318:     }
                   2319:     my ($additional,$secondid,$thirdid);
                   2320:     if ($context eq 'parmslog') {
                   2321:         $additional = 
                   2322:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2323:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2324:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2325:             '</label>';
                   2326:         $secondid = 'includetypes';
                   2327:         $thirdid = 'includetypestext';
                   2328:     }
                   2329:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2330:                                                     '$secondid','$thirdid')";
                   2331:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2332: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2333: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2334: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2335:            &mt('Filter: [_1]',
1.477     www      2336: 	   &select_form($env{'form.displayfilter'},
                   2337: 			'displayfilter',
1.970     raeburn  2338: 			{'currentfolder' => 'Current folder/page',
1.477     www      2339: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2340: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2341: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2342:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2343:                          '" />'.$additional;
                   2344: }
                   2345: 
                   2346: sub display_filter_js {
                   2347:     my $includetext = &mt('Include parameter types');
                   2348:     return <<"ENDJS";
                   2349:   
                   2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2351:     var firstType = 'hidden';
                   2352:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2353:         firstType = 'text';
                   2354:     }
                   2355:     firstObject = document.getElementById(firstid);
                   2356:     if (typeof(firstObject) == 'object') {
                   2357:         if (firstObject.type != firstType) {
                   2358:             changeInputType(firstObject,firstType);
                   2359:         }
                   2360:     }
                   2361:     if (context == 'parmslog') {
                   2362:         var secondType = 'hidden';
                   2363:         if (firstType == 'text') {
                   2364:             secondType = 'checkbox';
                   2365:         }
                   2366:         secondObject = document.getElementById(secondid);  
                   2367:         if (typeof(secondObject) == 'object') {
                   2368:             if (secondObject.type != secondType) {
                   2369:                 changeInputType(secondObject,secondType);
                   2370:             }
                   2371:         }
                   2372:         var textItem = document.getElementById(thirdid);
                   2373:         var currtext = textItem.innerHTML;
                   2374:         var newtext;
                   2375:         if (firstType == 'text') {
                   2376:             newtext = '$includetext';
                   2377:         } else {
                   2378:             newtext = '&nbsp;';
                   2379:         }
                   2380:         if (currtext != newtext) {
                   2381:             textItem.innerHTML = newtext;
                   2382:         }
                   2383:     }
                   2384:     return;
                   2385: }
                   2386: 
                   2387: function changeInputType(oldObject,newType) {
                   2388:     var newObject = document.createElement('input');
                   2389:     newObject.type = newType;
                   2390:     if (oldObject.size) {
                   2391:         newObject.size = oldObject.size;
                   2392:     }
                   2393:     if (oldObject.value) {
                   2394:         newObject.value = oldObject.value;
                   2395:     }
                   2396:     if (oldObject.name) {
                   2397:         newObject.name = oldObject.name;
                   2398:     }
                   2399:     if (oldObject.id) {
                   2400:         newObject.id = oldObject.id;
                   2401:     }
                   2402:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2403:     return;
                   2404: }
                   2405: 
                   2406: ENDJS
1.475     www      2407: }
                   2408: 
1.167     www      2409: sub gradeleveldescription {
                   2410:     my $gradelevel=shift;
                   2411:     my %gradelevels=(0 => 'Not specified',
                   2412: 		     1 => 'Grade 1',
                   2413: 		     2 => 'Grade 2',
                   2414: 		     3 => 'Grade 3',
                   2415: 		     4 => 'Grade 4',
                   2416: 		     5 => 'Grade 5',
                   2417: 		     6 => 'Grade 6',
                   2418: 		     7 => 'Grade 7',
                   2419: 		     8 => 'Grade 8',
                   2420: 		     9 => 'Grade 9',
                   2421: 		     10 => 'Grade 10',
                   2422: 		     11 => 'Grade 11',
                   2423: 		     12 => 'Grade 12',
                   2424: 		     13 => 'Grade 13',
                   2425: 		     14 => '100 Level',
                   2426: 		     15 => '200 Level',
                   2427: 		     16 => '300 Level',
                   2428: 		     17 => '400 Level',
                   2429: 		     18 => 'Graduate Level');
                   2430:     return &mt($gradelevels{$gradelevel});
                   2431: }
                   2432: 
1.163     www      2433: sub select_level_form {
                   2434:     my ($deflevel,$name)=@_;
                   2435:     unless ($deflevel) { $deflevel=0; }
1.167     www      2436:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2437:     for (my $i=0; $i<=18; $i++) {
                   2438:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2439:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2440:                 ">".&gradeleveldescription($i)."</option>\n";
                   2441:     }
                   2442:     $selectform.="</select>";
                   2443:     return $selectform;
1.163     www      2444: }
1.167     www      2445: 
1.35      matthew  2446: #-------------------------------------------
                   2447: 
1.45      matthew  2448: =pod
                   2449: 
1.1075.2.115  raeburn  2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2451: 
                   2452: Returns a string containing a <select name='$name' size='1'> form to 
                   2453: allow a user to select the domain to preform an operation in.  
                   2454: See loncreateuser.pm for an example invocation and use.
                   2455: 
1.90      www      2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2457: selected");
                   2458: 
1.743     raeburn  2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2460: 
1.910     raeburn  2461: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2462: 
1.1075.2.36  raeburn  2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2464: 
1.1075.2.115  raeburn  2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2466: 
                   2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2468: 
1.35      matthew  2469: =cut
                   2470: 
                   2471: #-------------------------------------------
1.34      matthew  2472: sub select_dom_form {
1.1075.2.115  raeburn  2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2474:     if ($onchange) {
1.874     raeburn  2475:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2476:     }
1.1075.2.115  raeburn  2477:     if ($disabled) {
                   2478:         $disabled = ' disabled="disabled"';
                   2479:     }
1.1075.2.36  raeburn  2480:     my (@domains,%exclude);
1.910     raeburn  2481:     if (ref($incdoms) eq 'ARRAY') {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2483:     } else {
                   2484:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2485:     }
1.90      www      2486:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2487:     if (ref($excdoms) eq 'ARRAY') {
                   2488:         map { $exclude{$_} = 1; } @{$excdoms};
                   2489:     }
1.1075.2.115  raeburn  2490:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2491:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2492:         next if ($exclude{$dom});
1.356     albertel 2493:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2494:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2495:         if ($showdomdesc) {
                   2496:             if ($dom ne '') {
                   2497:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2498:                 if ($domdesc ne '') {
                   2499:                     $selectdomain .= ' ('.$domdesc.')';
                   2500:                 }
                   2501:             } 
                   2502:         }
                   2503:         $selectdomain .= "</option>\n";
1.34      matthew  2504:     }
                   2505:     $selectdomain.="</select>";
                   2506:     return $selectdomain;
                   2507: }
                   2508: 
1.35      matthew  2509: #-------------------------------------------
                   2510: 
1.45      matthew  2511: =pod
                   2512: 
1.648     raeburn  2513: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2514: 
1.586     raeburn  2515: input: 4 arguments (two required, two optional) - 
                   2516:     $domain - domain of new user
                   2517:     $name - name of form element
                   2518:     $default - Value of 'default' causes a default item to be first 
                   2519:                             option, and selected by default. 
                   2520:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2521:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2522: output: returns 2 items: 
1.586     raeburn  2523: (a) form element which contains either:
                   2524:    (i) <select name="$name">
                   2525:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2526:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2527:        </select>
                   2528:        form item if there are multiple library servers in $domain, or
                   2529:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2530:        if there is only one library server in $domain.
                   2531: 
                   2532: (b) number of library servers found.
                   2533: 
                   2534: See loncreateuser.pm for example of use.
1.35      matthew  2535: 
                   2536: =cut
                   2537: 
                   2538: #-------------------------------------------
1.586     raeburn  2539: sub home_server_form_item {
                   2540:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2541:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2542:     my $result;
                   2543:     my $numlib = keys(%servers);
                   2544:     if ($numlib > 1) {
                   2545:         $result .= '<select name="'.$name.'" />'."\n";
                   2546:         if ($default) {
1.804     bisitz   2547:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2548:                        '</option>'."\n";
                   2549:         }
                   2550:         foreach my $hostid (sort(keys(%servers))) {
                   2551:             $result.= '<option value="'.$hostid.'">'.
                   2552: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2553:         }
                   2554:         $result .= '</select>'."\n";
                   2555:     } elsif ($numlib == 1) {
                   2556:         my $hostid;
                   2557:         foreach my $item (keys(%servers)) {
                   2558:             $hostid = $item;
                   2559:         }
                   2560:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2561:                    $hostid.'" />';
                   2562:                    if (!$hide) {
                   2563:                        $result .= $hostid.' '.$servers{$hostid};
                   2564:                    }
                   2565:                    $result .= "\n";
                   2566:     } elsif ($default) {
                   2567:         $result .= '<input type="hidden" name="'.$name.
                   2568:                    '" value="default" />';
                   2569:                    if (!$hide) {
                   2570:                        $result .= &mt('default');
                   2571:                    }
                   2572:                    $result .= "\n";
1.33      matthew  2573:     }
1.586     raeburn  2574:     return ($result,$numlib);
1.33      matthew  2575: }
1.112     bowersj2 2576: 
                   2577: =pod
                   2578: 
1.534     albertel 2579: =back 
                   2580: 
1.112     bowersj2 2581: =cut
1.87      matthew  2582: 
                   2583: ###############################################################
1.112     bowersj2 2584: ##                  Decoding User Agent                      ##
1.87      matthew  2585: ###############################################################
                   2586: 
                   2587: =pod
                   2588: 
1.112     bowersj2 2589: =head1 Decoding the User Agent
                   2590: 
                   2591: =over 4
                   2592: 
                   2593: =item * &decode_user_agent()
1.87      matthew  2594: 
                   2595: Inputs: $r
                   2596: 
                   2597: Outputs:
                   2598: 
                   2599: =over 4
                   2600: 
1.112     bowersj2 2601: =item * $httpbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientbrowser
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientversion
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientmathml
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientunicode
1.87      matthew  2610: 
1.112     bowersj2 2611: =item * $clientos
1.87      matthew  2612: 
1.1075.2.42  raeburn  2613: =item * $clientmobile
                   2614: 
                   2615: =item * $clientinfo
                   2616: 
1.1075.2.77  raeburn  2617: =item * $clientosversion
                   2618: 
1.87      matthew  2619: =back
                   2620: 
1.157     matthew  2621: =back 
                   2622: 
1.87      matthew  2623: =cut
                   2624: 
                   2625: ###############################################################
                   2626: ###############################################################
                   2627: sub decode_user_agent {
1.247     albertel 2628:     my ($r)=@_;
1.87      matthew  2629:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2630:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2631:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2632:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2633:     my $clientbrowser='unknown';
                   2634:     my $clientversion='0';
                   2635:     my $clientmathml='';
                   2636:     my $clientunicode='0';
1.1075.2.42  raeburn  2637:     my $clientmobile=0;
1.1075.2.77  raeburn  2638:     my $clientosversion='';
1.87      matthew  2639:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2640:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2641: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2642: 	    $clientbrowser=$bname;
                   2643:             $httpbrowser=~/$vreg/i;
                   2644: 	    $clientversion=$1;
                   2645:             $clientmathml=($clientversion>=$minv);
                   2646:             $clientunicode=($clientversion>=$univ);
                   2647: 	}
                   2648:     }
                   2649:     my $clientos='unknown';
1.1075.2.42  raeburn  2650:     my $clientinfo;
1.87      matthew  2651:     if (($httpbrowser=~/linux/i) ||
                   2652:         ($httpbrowser=~/unix/i) ||
                   2653:         ($httpbrowser=~/ux/i) ||
                   2654:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2655:     if (($httpbrowser=~/vax/i) ||
                   2656:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2657:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2658:     if (($httpbrowser=~/mac/i) ||
                   2659:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2660:     if ($httpbrowser=~/win/i) {
                   2661:         $clientos='win';
                   2662:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2663:             $clientosversion = $1;
                   2664:         }
                   2665:     }
1.87      matthew  2666:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2667:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2668:         $clientmobile=lc($1);
                   2669:     }
                   2670:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2671:         $clientinfo = 'firefox-'.$1;
                   2672:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2673:         $clientinfo = 'chromeframe-'.$1;
                   2674:     }
1.87      matthew  2675:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2676:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2677:             $clientosversion);
1.87      matthew  2678: }
                   2679: 
1.32      matthew  2680: ###############################################################
                   2681: ##    Authentication changing form generation subroutines    ##
                   2682: ###############################################################
                   2683: ##
                   2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2685: ## hash, and have reasonable default values.
                   2686: ##
                   2687: ##    formname = the name given in the <form> tag.
1.35      matthew  2688: #-------------------------------------------
                   2689: 
1.45      matthew  2690: =pod
                   2691: 
1.112     bowersj2 2692: =head1 Authentication Routines
                   2693: 
                   2694: =over 4
                   2695: 
1.648     raeburn  2696: =item * &authform_xxxxxx()
1.35      matthew  2697: 
                   2698: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2699: handle some of the conveniences required for authentication forms.  
                   2700: This is not an optimal method, but it works.  
                   2701: 
                   2702: =over 4
                   2703: 
1.112     bowersj2 2704: =item * authform_header
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_authorwarning
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_nochange
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_kerberos
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_internal
1.35      matthew  2713: 
1.112     bowersj2 2714: =item * authform_filesystem
1.35      matthew  2715: 
                   2716: =back
                   2717: 
1.648     raeburn  2718: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2719: 
1.35      matthew  2720: =cut
                   2721: 
                   2722: #-------------------------------------------
1.32      matthew  2723: sub authform_header{  
                   2724:     my %in = (
                   2725:         formname => 'cu',
1.80      albertel 2726:         kerb_def_dom => '',
1.32      matthew  2727:         @_,
                   2728:     );
                   2729:     $in{'formname'} = 'document.' . $in{'formname'};
                   2730:     my $result='';
1.80      albertel 2731: 
                   2732: #---------------------------------------------- Code for upper case translation
                   2733:     my $Javascript_toUpperCase;
                   2734:     unless ($in{kerb_def_dom}) {
                   2735:         $Javascript_toUpperCase =<<"END";
                   2736:         switch (choice) {
                   2737:            case 'krb': currentform.elements[choicearg].value =
                   2738:                currentform.elements[choicearg].value.toUpperCase();
                   2739:                break;
                   2740:            default:
                   2741:         }
                   2742: END
                   2743:     } else {
                   2744:         $Javascript_toUpperCase = "";
                   2745:     }
                   2746: 
1.165     raeburn  2747:     my $radioval = "'nochange'";
1.591     raeburn  2748:     if (defined($in{'curr_authtype'})) {
                   2749:         if ($in{'curr_authtype'} ne '') {
                   2750:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2751:         }
1.174     matthew  2752:     }
1.165     raeburn  2753:     my $argfield = 'null';
1.591     raeburn  2754:     if (defined($in{'mode'})) {
1.165     raeburn  2755:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2756:             if (defined($in{'curr_autharg'})) {
                   2757:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2758:                     $argfield = "'$in{'curr_autharg'}'";
                   2759:                 }
                   2760:             }
                   2761:         }
                   2762:     }
                   2763: 
1.32      matthew  2764:     $result.=<<"END";
                   2765: var current = new Object();
1.165     raeburn  2766: current.radiovalue = $radioval;
                   2767: current.argfield = $argfield;
1.32      matthew  2768: 
                   2769: function changed_radio(choice,currentform) {
                   2770:     var choicearg = choice + 'arg';
                   2771:     // If a radio button in changed, we need to change the argfield
                   2772:     if (current.radiovalue != choice) {
                   2773:         current.radiovalue = choice;
                   2774:         if (current.argfield != null) {
                   2775:             currentform.elements[current.argfield].value = '';
                   2776:         }
                   2777:         if (choice == 'nochange') {
                   2778:             current.argfield = null;
                   2779:         } else {
                   2780:             current.argfield = choicearg;
                   2781:             switch(choice) {
                   2782:                 case 'krb': 
                   2783:                     currentform.elements[current.argfield].value = 
                   2784:                         "$in{'kerb_def_dom'}";
                   2785:                 break;
                   2786:               default:
                   2787:                 break;
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return;
                   2792: }
1.22      www      2793: 
1.32      matthew  2794: function changed_text(choice,currentform) {
                   2795:     var choicearg = choice + 'arg';
                   2796:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2797:         $Javascript_toUpperCase
1.32      matthew  2798:         // clear old field
                   2799:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2800:             currentform.elements[current.argfield].value = '';
                   2801:         }
                   2802:         current.argfield = choicearg;
                   2803:     }
                   2804:     set_auth_radio_buttons(choice,currentform);
                   2805:     return;
1.20      www      2806: }
1.32      matthew  2807: 
                   2808: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2809:     var numauthchoices = currentform.login.length;
                   2810:     if (typeof numauthchoices  == "undefined") {
                   2811:         return;
                   2812:     } 
1.32      matthew  2813:     var i=0;
1.986     raeburn  2814:     while (i < numauthchoices) {
1.32      matthew  2815:         if (currentform.login[i].value == newvalue) { break; }
                   2816:         i++;
                   2817:     }
1.986     raeburn  2818:     if (i == numauthchoices) {
1.32      matthew  2819:         return;
                   2820:     }
                   2821:     current.radiovalue = newvalue;
                   2822:     currentform.login[i].checked = true;
                   2823:     return;
                   2824: }
                   2825: END
                   2826:     return $result;
                   2827: }
                   2828: 
1.1075.2.20  raeburn  2829: sub authform_authorwarning {
1.32      matthew  2830:     my $result='';
1.144     matthew  2831:     $result='<i>'.
                   2832:         &mt('As a general rule, only authors or co-authors should be '.
                   2833:             'filesystem authenticated '.
                   2834:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2835:     return $result;
                   2836: }
                   2837: 
1.1075.2.20  raeburn  2838: sub authform_nochange {
1.32      matthew  2839:     my %in = (
                   2840:               formname => 'document.cu',
                   2841:               kerb_def_dom => 'MSU.EDU',
                   2842:               @_,
                   2843:           );
1.1075.2.20  raeburn  2844:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2845:     my $result;
1.1075.2.20  raeburn  2846:     if (!$authnum) {
                   2847:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2848:     } else {
                   2849:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2850:                   '<input type="radio" name="login" value="nochange" '.
                   2851:                   'checked="checked" onclick="'.
1.281     albertel 2852:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2853: 	    '</label>';
1.586     raeburn  2854:     }
1.32      matthew  2855:     return $result;
                   2856: }
                   2857: 
1.591     raeburn  2858: sub authform_kerberos {
1.32      matthew  2859:     my %in = (
                   2860:               formname => 'document.cu',
                   2861:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2862:               kerb_def_auth => 'krb4',
1.32      matthew  2863:               @_,
                   2864:               );
1.586     raeburn  2865:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2866:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2867:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2868:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2869:        $check5 = ' checked="checked"';
1.80      albertel 2870:     } else {
1.772     bisitz   2871:        $check4 = ' checked="checked"';
1.80      albertel 2872:     }
1.1075.2.117  raeburn  2873:     if ($in{'readonly'}) {
                   2874:         $disabled = ' disabled="disabled"';
                   2875:     }
1.165     raeburn  2876:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2877:     if (defined($in{'curr_authtype'})) {
                   2878:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2879:             $krbcheck = ' checked="checked"';
1.623     raeburn  2880:             if (defined($in{'mode'})) {
                   2881:                 if ($in{'mode'} eq 'modifyuser') {
                   2882:                     $krbcheck = '';
                   2883:                 }
                   2884:             }
1.591     raeburn  2885:             if (defined($in{'curr_kerb_ver'})) {
                   2886:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2887:                     $check5 = ' checked="checked"';
1.591     raeburn  2888:                     $check4 = '';
                   2889:                 } else {
1.772     bisitz   2890:                     $check4 = ' checked="checked"';
1.591     raeburn  2891:                     $check5 = '';
                   2892:                 }
1.586     raeburn  2893:             }
1.591     raeburn  2894:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2895:                 $krbarg = $in{'curr_autharg'};
                   2896:             }
1.586     raeburn  2897:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2898:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2899:                     $result = 
                   2900:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2901:         $in{'curr_autharg'},$krbver);
                   2902:                 } else {
                   2903:                     $result =
                   2904:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2905:                 }
                   2906:                 return $result; 
                   2907:             }
                   2908:         }
                   2909:     } else {
                   2910:         if ($authnum == 1) {
1.784     bisitz   2911:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2912:         }
                   2913:     }
1.586     raeburn  2914:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2915:         return;
1.587     raeburn  2916:     } elsif ($authtype eq '') {
1.591     raeburn  2917:         if (defined($in{'mode'})) {
1.587     raeburn  2918:             if ($in{'mode'} eq 'modifycourse') {
                   2919:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2920:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2921:                 }
                   2922:             }
                   2923:         }
1.586     raeburn  2924:     }
                   2925:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2926:     if ($authtype eq '') {
                   2927:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2928:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2929:                     $krbcheck.$disabled.' />';
1.586     raeburn  2930:     }
                   2931:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2932:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2934:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2935:          $in{'curr_authtype'} eq 'krb4')) {
                   2936:         $result .= &mt
1.144     matthew  2937:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2938:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2939:          '<label>'.$authtype,
1.281     albertel 2940:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2941:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2942:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2943:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2944:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2945: 	 '</label>');
1.586     raeburn  2946:     } elsif ($can_assign{'krb4'}) {
                   2947:         $result .= &mt
                   2948:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2949:          '[_3] Version 4 [_4]',
                   2950:          '<label>'.$authtype,
                   2951:          '</label><input type="text" size="10" name="krbarg" '.
                   2952:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2953:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2954:          '<label><input type="hidden" name="krbver" value="4" />',
                   2955:          '</label>');
                   2956:     } elsif ($can_assign{'krb5'}) {
                   2957:         $result .= &mt
                   2958:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2959:          '[_3] Version 5 [_4]',
                   2960:          '<label>'.$authtype,
                   2961:          '</label><input type="text" size="10" name="krbarg" '.
                   2962:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2963:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2964:          '<label><input type="hidden" name="krbver" value="5" />',
                   2965:          '</label>');
                   2966:     }
1.32      matthew  2967:     return $result;
                   2968: }
                   2969: 
1.1075.2.20  raeburn  2970: sub authform_internal {
1.586     raeburn  2971:     my %in = (
1.32      matthew  2972:                 formname => 'document.cu',
                   2973:                 kerb_def_dom => 'MSU.EDU',
                   2974:                 @_,
                   2975:                 );
1.1075.2.117  raeburn  2976:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2977:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2978:     if ($in{'readonly'}) {
                   2979:         $disabled = ' disabled="disabled"';
                   2980:     }
1.591     raeburn  2981:     if (defined($in{'curr_authtype'})) {
                   2982:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2983:             if ($can_assign{'int'}) {
1.772     bisitz   2984:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2985:                 if (defined($in{'mode'})) {
                   2986:                     if ($in{'mode'} eq 'modifyuser') {
                   2987:                         $intcheck = '';
                   2988:                     }
                   2989:                 }
1.591     raeburn  2990:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2991:                     $intarg = $in{'curr_autharg'};
                   2992:                 }
                   2993:             } else {
                   2994:                 $result = &mt('Currently internally authenticated.');
                   2995:                 return $result;
1.165     raeburn  2996:             }
                   2997:         }
1.586     raeburn  2998:     } else {
                   2999:         if ($authnum == 1) {
1.784     bisitz   3000:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3001:         }
                   3002:     }
                   3003:     if (!$can_assign{'int'}) {
                   3004:         return;
1.587     raeburn  3005:     } elsif ($authtype eq '') {
1.591     raeburn  3006:         if (defined($in{'mode'})) {
1.587     raeburn  3007:             if ($in{'mode'} eq 'modifycourse') {
                   3008:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3009:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3010:                 }
                   3011:             }
                   3012:         }
1.165     raeburn  3013:     }
1.586     raeburn  3014:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3015:     if ($authtype eq '') {
                   3016:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3017:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3018:     }
1.605     bisitz   3019:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3020:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3021:     $result = &mt
1.144     matthew  3022:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3023:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3024:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3025:     return $result;
                   3026: }
                   3027: 
1.1075.2.20  raeburn  3028: sub authform_local {
1.32      matthew  3029:     my %in = (
                   3030:               formname => 'document.cu',
                   3031:               kerb_def_dom => 'MSU.EDU',
                   3032:               @_,
                   3033:               );
1.1075.2.117  raeburn  3034:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3035:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3036:     if ($in{'readonly'}) {
                   3037:         $disabled = ' disabled="disabled"';
                   3038:     }
1.591     raeburn  3039:     if (defined($in{'curr_authtype'})) {
                   3040:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3041:             if ($can_assign{'loc'}) {
1.772     bisitz   3042:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3043:                 if (defined($in{'mode'})) {
                   3044:                     if ($in{'mode'} eq 'modifyuser') {
                   3045:                         $loccheck = '';
                   3046:                     }
                   3047:                 }
1.591     raeburn  3048:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3049:                     $locarg = $in{'curr_autharg'};
                   3050:                 }
                   3051:             } else {
                   3052:                 $result = &mt('Currently using local (institutional) authentication.');
                   3053:                 return $result;
1.165     raeburn  3054:             }
                   3055:         }
1.586     raeburn  3056:     } else {
                   3057:         if ($authnum == 1) {
1.784     bisitz   3058:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3059:         }
                   3060:     }
                   3061:     if (!$can_assign{'loc'}) {
                   3062:         return;
1.587     raeburn  3063:     } elsif ($authtype eq '') {
1.591     raeburn  3064:         if (defined($in{'mode'})) {
1.587     raeburn  3065:             if ($in{'mode'} eq 'modifycourse') {
                   3066:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3067:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3068:                 }
                   3069:             }
                   3070:         }
1.165     raeburn  3071:     }
1.586     raeburn  3072:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3073:     if ($authtype eq '') {
                   3074:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3075:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3076:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3077:     }
                   3078:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3079:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3080:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3081:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3082:     return $result;
                   3083: }
                   3084: 
1.1075.2.20  raeburn  3085: sub authform_filesystem {
1.32      matthew  3086:     my %in = (
                   3087:               formname => 'document.cu',
                   3088:               kerb_def_dom => 'MSU.EDU',
                   3089:               @_,
                   3090:               );
1.1075.2.117  raeburn  3091:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3092:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3093:     if ($in{'readonly'}) {
                   3094:         $disabled = ' disabled="disabled"';
                   3095:     }
1.591     raeburn  3096:     if (defined($in{'curr_authtype'})) {
                   3097:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3098:             if ($can_assign{'fsys'}) {
1.772     bisitz   3099:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3100:                 if (defined($in{'mode'})) {
                   3101:                     if ($in{'mode'} eq 'modifyuser') {
                   3102:                         $fsyscheck = '';
                   3103:                     }
                   3104:                 }
1.586     raeburn  3105:             } else {
                   3106:                 $result = &mt('Currently Filesystem Authenticated.');
                   3107:                 return $result;
                   3108:             }           
                   3109:         }
                   3110:     } else {
                   3111:         if ($authnum == 1) {
1.784     bisitz   3112:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3113:         }
                   3114:     }
                   3115:     if (!$can_assign{'fsys'}) {
                   3116:         return;
1.587     raeburn  3117:     } elsif ($authtype eq '') {
1.591     raeburn  3118:         if (defined($in{'mode'})) {
1.587     raeburn  3119:             if ($in{'mode'} eq 'modifycourse') {
                   3120:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3121:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3122:                 }
                   3123:             }
                   3124:         }
1.586     raeburn  3125:     }
                   3126:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3127:     if ($authtype eq '') {
                   3128:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3129:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3130:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3131:     }
                   3132:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3133:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3134:     $result = &mt
1.144     matthew  3135:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3136:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3137:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3138:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3139:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3140:     return $result;
                   3141: }
                   3142: 
1.586     raeburn  3143: sub get_assignable_auth {
                   3144:     my ($dom) = @_;
                   3145:     if ($dom eq '') {
                   3146:         $dom = $env{'request.role.domain'};
                   3147:     }
                   3148:     my %can_assign = (
                   3149:                           krb4 => 1,
                   3150:                           krb5 => 1,
                   3151:                           int  => 1,
                   3152:                           loc  => 1,
                   3153:                      );
                   3154:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3155:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3156:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3157:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3158:             my $context;
                   3159:             if ($env{'request.role'} =~ /^au/) {
                   3160:                 $context = 'author';
1.1075.2.117  raeburn  3161:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3162:                 $context = 'domain';
                   3163:             } elsif ($env{'request.course.id'}) {
                   3164:                 $context = 'course';
                   3165:             }
                   3166:             if ($context) {
                   3167:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3168:                    %can_assign = %{$authhash->{$context}}; 
                   3169:                 }
                   3170:             }
                   3171:         }
                   3172:     }
                   3173:     my $authnum = 0;
                   3174:     foreach my $key (keys(%can_assign)) {
                   3175:         if ($can_assign{$key}) {
                   3176:             $authnum ++;
                   3177:         }
                   3178:     }
                   3179:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3180:         $authnum --;
                   3181:     }
                   3182:     return ($authnum,%can_assign);
                   3183: }
                   3184: 
1.1075.2.137  raeburn  3185: sub check_passwd_rules {
                   3186:     my ($domain,$plainpass) = @_;
                   3187:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3188:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3189:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3190:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3191:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3192:             if ($passwdconf{'min'} > $min) {
                   3193:                 $min = $passwdconf{'min'};
                   3194:             }
1.1075.2.137  raeburn  3195:         }
                   3196:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3197:             $max = $passwdconf{'max'};
                   3198:         }
                   3199:         @chars = @{$passwdconf{'chars'}};
                   3200:     }
                   3201:     if (($min) && (length($plainpass) < $min)) {
                   3202:         push(@brokerule,'min');
                   3203:     }
                   3204:     if (($max) && (length($plainpass) > $max)) {
                   3205:         push(@brokerule,'max');
                   3206:     }
                   3207:     if (@chars) {
                   3208:         my %rules;
                   3209:         map { $rules{$_} = 1; } @chars;
                   3210:         if ($rules{'uc'}) {
                   3211:             unless ($plainpass =~ /[A-Z]/) {
                   3212:                 push(@brokerule,'uc');
                   3213:             }
                   3214:         }
                   3215:         if ($rules{'lc'}) {
                   3216:             unless ($plainpass =~ /[a-z]/) {
                   3217:                 push(@brokerule,'lc');
                   3218:             }
                   3219:         }
                   3220:         if ($rules{'num'}) {
                   3221:             unless ($plainpass =~ /\d/) {
                   3222:                 push(@brokerule,'num');
                   3223:             }
                   3224:         }
                   3225:         if ($rules{'spec'}) {
                   3226:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3227:                 push(@brokerule,'spec');
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     if (@brokerule) {
                   3232:         my %rulenames = &Apache::lonlocal::texthash(
                   3233:             uc   => 'At least one upper case letter',
                   3234:             lc   => 'At least one lower case letter',
                   3235:             num  => 'At least one number',
                   3236:             spec => 'At least one non-alphanumeric',
                   3237:         );
                   3238:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3239:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3240:         $rulenames{'num'} .= ': 0123456789';
                   3241:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3242:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3243:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3244:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.141.  .3(raebu 3245:20):         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3246:             if (grep(/^$rule$/,@brokerule)) {
                   3247:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3248:             }
                   3249:         }
                   3250:         $warning .= '</ul>';
                   3251:     }
                   3252:     if (wantarray) {
                   3253:         return @brokerule;
                   3254:     }
                   3255:     return $warning;
                   3256: }
                   3257: 
1.80      albertel 3258: ###############################################################
                   3259: ##    Get Kerberos Defaults for Domain                 ##
                   3260: ###############################################################
                   3261: ##
                   3262: ## Returns default kerberos version and an associated argument
                   3263: ## as listed in file domain.tab. If not listed, provides
                   3264: ## appropriate default domain and kerberos version.
                   3265: ##
                   3266: #-------------------------------------------
                   3267: 
                   3268: =pod
                   3269: 
1.648     raeburn  3270: =item * &get_kerberos_defaults()
1.80      albertel 3271: 
                   3272: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3273: version and domain. If not found, it defaults to version 4 and the 
                   3274: domain of the server.
1.80      albertel 3275: 
1.648     raeburn  3276: =over 4
                   3277: 
1.80      albertel 3278: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3279: 
1.648     raeburn  3280: =back
                   3281: 
                   3282: =back
                   3283: 
1.80      albertel 3284: =cut
                   3285: 
                   3286: #-------------------------------------------
                   3287: sub get_kerberos_defaults {
                   3288:     my $domain=shift;
1.641     raeburn  3289:     my ($krbdef,$krbdefdom);
                   3290:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3291:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3292:         $krbdef = $domdefaults{'auth_def'};
                   3293:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3294:     } else {
1.80      albertel 3295:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3296:         my $krbdefdom=$1;
                   3297:         $krbdefdom=~tr/a-z/A-Z/;
                   3298:         $krbdef = "krb4";
                   3299:     }
                   3300:     return ($krbdef,$krbdefdom);
                   3301: }
1.112     bowersj2 3302: 
1.32      matthew  3303: 
1.46      matthew  3304: ###############################################################
                   3305: ##                Thesaurus Functions                        ##
                   3306: ###############################################################
1.20      www      3307: 
1.46      matthew  3308: =pod
1.20      www      3309: 
1.112     bowersj2 3310: =head1 Thesaurus Functions
                   3311: 
                   3312: =over 4
                   3313: 
1.648     raeburn  3314: =item * &initialize_keywords()
1.46      matthew  3315: 
                   3316: Initializes the package variable %Keywords if it is empty.  Uses the
                   3317: package variable $thesaurus_db_file.
                   3318: 
                   3319: =cut
                   3320: 
                   3321: ###################################################
                   3322: 
                   3323: sub initialize_keywords {
                   3324:     return 1 if (scalar keys(%Keywords));
                   3325:     # If we are here, %Keywords is empty, so fill it up
                   3326:     #   Make sure the file we need exists...
                   3327:     if (! -e $thesaurus_db_file) {
                   3328:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3329:                                  " failed because it does not exist");
                   3330:         return 0;
                   3331:     }
                   3332:     #   Set up the hash as a database
                   3333:     my %thesaurus_db;
                   3334:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3335:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3336:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3337:                                  $thesaurus_db_file);
                   3338:         return 0;
                   3339:     } 
                   3340:     #  Get the average number of appearances of a word.
                   3341:     my $avecount = $thesaurus_db{'average.count'};
                   3342:     #  Put keywords (those that appear > average) into %Keywords
                   3343:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3344:         my ($count,undef) = split /:/,$data;
                   3345:         $Keywords{$word}++ if ($count > $avecount);
                   3346:     }
                   3347:     untie %thesaurus_db;
                   3348:     # Remove special values from %Keywords.
1.356     albertel 3349:     foreach my $value ('total.count','average.count') {
                   3350:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3351:   }
1.46      matthew  3352:     return 1;
                   3353: }
                   3354: 
                   3355: ###################################################
                   3356: 
                   3357: =pod
                   3358: 
1.648     raeburn  3359: =item * &keyword($word)
1.46      matthew  3360: 
                   3361: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3362: than the average number of times in the thesaurus database.  Calls 
                   3363: &initialize_keywords
                   3364: 
                   3365: =cut
                   3366: 
                   3367: ###################################################
1.20      www      3368: 
                   3369: sub keyword {
1.46      matthew  3370:     return if (!&initialize_keywords());
                   3371:     my $word=lc(shift());
                   3372:     $word=~s/\W//g;
                   3373:     return exists($Keywords{$word});
1.20      www      3374: }
1.46      matthew  3375: 
                   3376: ###############################################################
                   3377: 
                   3378: =pod 
1.20      www      3379: 
1.648     raeburn  3380: =item * &get_related_words()
1.46      matthew  3381: 
1.160     matthew  3382: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3383: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3384: will be returned.  The order of the words returned is determined by the
                   3385: database which holds them.
                   3386: 
                   3387: Uses global $thesaurus_db_file.
                   3388: 
1.1057    foxr     3389: 
1.46      matthew  3390: =cut
                   3391: 
                   3392: ###############################################################
                   3393: sub get_related_words {
                   3394:     my $keyword = shift;
                   3395:     my %thesaurus_db;
                   3396:     if (! -e $thesaurus_db_file) {
                   3397:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3398:                                  "failed because the file does not exist");
                   3399:         return ();
                   3400:     }
                   3401:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3402:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3403:         return ();
                   3404:     } 
                   3405:     my @Words=();
1.429     www      3406:     my $count=0;
1.46      matthew  3407:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3408: 	# The first element is the number of times
                   3409: 	# the word appears.  We do not need it now.
1.429     www      3410: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3411: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3412: 	my $threshold=$mostfrequentcount/10;
                   3413:         foreach my $possibleword (@RelatedWords) {
                   3414:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3415:             if ($wordcount>$threshold) {
                   3416: 		push(@Words,$word);
                   3417:                 $count++;
                   3418:                 if ($count>10) { last; }
                   3419: 	    }
1.20      www      3420:         }
                   3421:     }
1.46      matthew  3422:     untie %thesaurus_db;
                   3423:     return @Words;
1.14      harris41 3424: }
1.46      matthew  3425: 
1.112     bowersj2 3426: =pod
                   3427: 
                   3428: =back
                   3429: 
                   3430: =cut
1.61      www      3431: 
                   3432: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3433: =pod
                   3434: 
1.112     bowersj2 3435: =head1 User Name Functions
                   3436: 
                   3437: =over 4
                   3438: 
1.648     raeburn  3439: =item * &plainname($uname,$udom,$first)
1.81      albertel 3440: 
1.112     bowersj2 3441: Takes a users logon name and returns it as a string in
1.226     albertel 3442: "first middle last generation" form 
                   3443: if $first is set to 'lastname' then it returns it as
                   3444: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3445: 
                   3446: =cut
1.61      www      3447: 
1.295     www      3448: 
1.81      albertel 3449: ###############################################################
1.61      www      3450: sub plainname {
1.226     albertel 3451:     my ($uname,$udom,$first)=@_;
1.537     albertel 3452:     return if (!defined($uname) || !defined($udom));
1.295     www      3453:     my %names=&getnames($uname,$udom);
1.226     albertel 3454:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3455: 					  $names{'middlename'},
                   3456: 					  $names{'lastname'},
                   3457: 					  $names{'generation'},$first);
                   3458:     $name=~s/^\s+//;
1.62      www      3459:     $name=~s/\s+$//;
                   3460:     $name=~s/\s+/ /g;
1.353     albertel 3461:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3462:     return $name;
1.61      www      3463: }
1.66      www      3464: 
                   3465: # -------------------------------------------------------------------- Nickname
1.81      albertel 3466: =pod
                   3467: 
1.648     raeburn  3468: =item * &nickname($uname,$udom)
1.81      albertel 3469: 
                   3470: Gets a users name and returns it as a string as
                   3471: 
                   3472: "&quot;nickname&quot;"
1.66      www      3473: 
1.81      albertel 3474: if the user has a nickname or
                   3475: 
                   3476: "first middle last generation"
                   3477: 
                   3478: if the user does not
                   3479: 
                   3480: =cut
1.66      www      3481: 
                   3482: sub nickname {
                   3483:     my ($uname,$udom)=@_;
1.537     albertel 3484:     return if (!defined($uname) || !defined($udom));
1.295     www      3485:     my %names=&getnames($uname,$udom);
1.68      albertel 3486:     my $name=$names{'nickname'};
1.66      www      3487:     if ($name) {
                   3488:        $name='&quot;'.$name.'&quot;'; 
                   3489:     } else {
                   3490:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3491: 	     $names{'lastname'}.' '.$names{'generation'};
                   3492:        $name=~s/\s+$//;
                   3493:        $name=~s/\s+/ /g;
                   3494:     }
                   3495:     return $name;
                   3496: }
                   3497: 
1.295     www      3498: sub getnames {
                   3499:     my ($uname,$udom)=@_;
1.537     albertel 3500:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3501:     if ($udom eq 'public' && $uname eq 'public') {
                   3502: 	return ('lastname' => &mt('Public'));
                   3503:     }
1.295     www      3504:     my $id=$uname.':'.$udom;
                   3505:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3506:     if ($cached) {
                   3507: 	return %{$names};
                   3508:     } else {
                   3509: 	my %loadnames=&Apache::lonnet::get('environment',
                   3510:                     ['firstname','middlename','lastname','generation','nickname'],
                   3511: 					 $udom,$uname);
                   3512: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3513: 	return %loadnames;
                   3514:     }
                   3515: }
1.61      www      3516: 
1.542     raeburn  3517: # -------------------------------------------------------------------- getemails
1.648     raeburn  3518: 
1.542     raeburn  3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &getemails($uname,$udom)
1.542     raeburn  3522: 
                   3523: Gets a user's email information and returns it as a hash with keys:
                   3524: notification, critnotification, permanentemail
                   3525: 
                   3526: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3527: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3528:  
1.648     raeburn  3529: 
1.542     raeburn  3530: =cut
                   3531: 
1.648     raeburn  3532: 
1.466     albertel 3533: sub getemails {
                   3534:     my ($uname,$udom)=@_;
                   3535:     if ($udom eq 'public' && $uname eq 'public') {
                   3536: 	return;
                   3537:     }
1.467     www      3538:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3540:     my $id=$uname.':'.$udom;
                   3541:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3542:     if ($cached) {
                   3543: 	return %{$names};
                   3544:     } else {
                   3545: 	my %loadnames=&Apache::lonnet::get('environment',
                   3546:                     			   ['notification','critnotification',
                   3547: 					    'permanentemail'],
                   3548: 					   $udom,$uname);
                   3549: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3550: 	return %loadnames;
                   3551:     }
                   3552: }
                   3553: 
1.551     albertel 3554: sub flush_email_cache {
                   3555:     my ($uname,$udom)=@_;
                   3556:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3557:     if (!$uname) { $uname=$env{'user.name'};   }
                   3558:     return if ($udom eq 'public' && $uname eq 'public');
                   3559:     my $id=$uname.':'.$udom;
                   3560:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3561: }
                   3562: 
1.728     raeburn  3563: # -------------------------------------------------------------------- getlangs
                   3564: 
                   3565: =pod
                   3566: 
                   3567: =item * &getlangs($uname,$udom)
                   3568: 
                   3569: Gets a user's language preference and returns it as a hash with key:
                   3570: language.
                   3571: 
                   3572: =cut
                   3573: 
                   3574: 
                   3575: sub getlangs {
                   3576:     my ($uname,$udom) = @_;
                   3577:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3578:     if (!$uname) { $uname=$env{'user.name'};   }
                   3579:     my $id=$uname.':'.$udom;
                   3580:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3581:     if ($cached) {
                   3582:         return %{$langs};
                   3583:     } else {
                   3584:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3585:                                            $udom,$uname);
                   3586:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3587:         return %loadlangs;
                   3588:     }
                   3589: }
                   3590: 
                   3591: sub flush_langs_cache {
                   3592:     my ($uname,$udom)=@_;
                   3593:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3594:     if (!$uname) { $uname=$env{'user.name'};   }
                   3595:     return if ($udom eq 'public' && $uname eq 'public');
                   3596:     my $id=$uname.':'.$udom;
                   3597:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3598: }
                   3599: 
1.61      www      3600: # ------------------------------------------------------------------ Screenname
1.81      albertel 3601: 
                   3602: =pod
                   3603: 
1.648     raeburn  3604: =item * &screenname($uname,$udom)
1.81      albertel 3605: 
                   3606: Gets a users screenname and returns it as a string
                   3607: 
                   3608: =cut
1.61      www      3609: 
                   3610: sub screenname {
                   3611:     my ($uname,$udom)=@_;
1.258     albertel 3612:     if ($uname eq $env{'user.name'} &&
                   3613: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3614:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3615:     return $names{'screenname'};
1.62      www      3616: }
                   3617: 
1.212     albertel 3618: 
1.802     bisitz   3619: # ------------------------------------------------------------- Confirm Wrapper
                   3620: =pod
                   3621: 
1.1075.2.42  raeburn  3622: =item * &confirmwrapper($message)
1.802     bisitz   3623: 
                   3624: Wrap messages about completion of operation in box
                   3625: 
                   3626: =cut
                   3627: 
                   3628: sub confirmwrapper {
                   3629:     my ($message)=@_;
                   3630:     if ($message) {
                   3631:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3632:                .$message."\n"
                   3633:                .'</div>'."\n";
                   3634:     } else {
                   3635:         return $message;
                   3636:     }
                   3637: }
                   3638: 
1.62      www      3639: # ------------------------------------------------------------- Message Wrapper
                   3640: 
                   3641: sub messagewrapper {
1.369     www      3642:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3643:     return 
1.441     albertel 3644:         '<a href="/adm/email?compose=individual&amp;'.
                   3645:         'recname='.$username.'&amp;recdom='.$domain.
                   3646: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3647:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3648: }
1.802     bisitz   3649: 
1.74      www      3650: # --------------------------------------------------------------- Notes Wrapper
                   3651: 
                   3652: sub noteswrapper {
                   3653:     my ($link,$un,$do)=@_;
                   3654:     return 
1.896     amueller 3655: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3656: }
1.802     bisitz   3657: 
1.62      www      3658: # ------------------------------------------------------------- Aboutme Wrapper
                   3659: 
                   3660: sub aboutmewrapper {
1.1070    raeburn  3661:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3662:     if (!defined($username)  && !defined($domain)) {
                   3663:         return;
                   3664:     }
1.1075.2.15  raeburn  3665:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3666: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3667: }
                   3668: 
                   3669: # ------------------------------------------------------------ Syllabus Wrapper
                   3670: 
                   3671: sub syllabuswrapper {
1.707     bisitz   3672:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3673:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3674: }
1.14      harris41 3675: 
1.802     bisitz   3676: # -----------------------------------------------------------------------------
                   3677: 
1.208     matthew  3678: sub track_student_link {
1.887     raeburn  3679:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3680:     my $link ="/adm/trackstudent?";
1.208     matthew  3681:     my $title = 'View recent activity';
                   3682:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3683:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3684:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3685:         $title .= ' of this student';
1.268     albertel 3686:     } 
1.208     matthew  3687:     if (defined($target) && $target !~ /^\s*$/) {
                   3688:         $target = qq{target="$target"};
                   3689:     } else {
                   3690:         $target = '';
                   3691:     }
1.268     albertel 3692:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3693:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3694:     $title = &mt($title);
                   3695:     $linktext = &mt($linktext);
1.448     albertel 3696:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3697: 	&help_open_topic('View_recent_activity');
1.208     matthew  3698: }
                   3699: 
1.781     raeburn  3700: sub slot_reservations_link {
                   3701:     my ($linktext,$sname,$sdom,$target) = @_;
                   3702:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3703:     my $title = 'View slot reservation history';
                   3704:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3705:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3706:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3707:         $title .= ' of this student';
                   3708:     }
                   3709:     if (defined($target) && $target !~ /^\s*$/) {
                   3710:         $target = qq{target="$target"};
                   3711:     } else {
                   3712:         $target = '';
                   3713:     }
                   3714:     $title = &mt($title);
                   3715:     $linktext = &mt($linktext);
                   3716:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3717: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3718: 
                   3719: }
                   3720: 
1.508     www      3721: # ===================================================== Display a student photo
                   3722: 
                   3723: 
1.509     albertel 3724: sub student_image_tag {
1.508     www      3725:     my ($domain,$user)=@_;
                   3726:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3727:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3728: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3729:     } else {
                   3730: 	return '';
                   3731:     }
                   3732: }
                   3733: 
1.112     bowersj2 3734: =pod
                   3735: 
                   3736: =back
                   3737: 
                   3738: =head1 Access .tab File Data
                   3739: 
                   3740: =over 4
                   3741: 
1.648     raeburn  3742: =item * &languageids() 
1.112     bowersj2 3743: 
                   3744: returns list of all language ids
                   3745: 
                   3746: =cut
                   3747: 
1.14      harris41 3748: sub languageids {
1.16      harris41 3749:     return sort(keys(%language));
1.14      harris41 3750: }
                   3751: 
1.112     bowersj2 3752: =pod
                   3753: 
1.648     raeburn  3754: =item * &languagedescription() 
1.112     bowersj2 3755: 
                   3756: returns description of a specified language id
                   3757: 
                   3758: =cut
                   3759: 
1.14      harris41 3760: sub languagedescription {
1.125     www      3761:     my $code=shift;
                   3762:     return  ($supported_language{$code}?'* ':'').
                   3763:             $language{$code}.
1.126     www      3764: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3765: }
                   3766: 
1.1048    foxr     3767: =pod
                   3768: 
                   3769: =item * &plainlanguagedescription
                   3770: 
                   3771: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3772: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3773: 
                   3774: =cut
                   3775: 
1.145     www      3776: sub plainlanguagedescription {
                   3777:     my $code=shift;
                   3778:     return $language{$code};
                   3779: }
                   3780: 
1.1048    foxr     3781: =pod
                   3782: 
                   3783: =item * &supportedlanguagecode
                   3784: 
                   3785: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3786: code.
                   3787: 
                   3788: =cut
                   3789: 
1.145     www      3790: sub supportedlanguagecode {
                   3791:     my $code=shift;
                   3792:     return $supported_language{$code};
1.97      www      3793: }
                   3794: 
1.112     bowersj2 3795: =pod
                   3796: 
1.1048    foxr     3797: =item * &latexlanguage()
                   3798: 
                   3799: Given a language key code returns the correspondnig language to use
                   3800: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3801: is no supported hyphenation for the language code.
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub latexlanguage {
                   3806:     my $code = shift;
                   3807:     return $latex_language{$code};
                   3808: }
                   3809: 
                   3810: =pod
                   3811: 
                   3812: =item * &latexhyphenation()
                   3813: 
                   3814: Same as above but what's supplied is the language as it might be stored
                   3815: in the metadata.
                   3816: 
                   3817: =cut
                   3818: 
                   3819: sub latexhyphenation {
                   3820:     my $key = shift;
                   3821:     return $latex_language_bykey{$key};
                   3822: }
                   3823: 
                   3824: =pod
                   3825: 
1.648     raeburn  3826: =item * &copyrightids() 
1.112     bowersj2 3827: 
                   3828: returns list of all copyrights
                   3829: 
                   3830: =cut
                   3831: 
                   3832: sub copyrightids {
                   3833:     return sort(keys(%cprtag));
                   3834: }
                   3835: 
                   3836: =pod
                   3837: 
1.648     raeburn  3838: =item * &copyrightdescription() 
1.112     bowersj2 3839: 
                   3840: returns description of a specified copyright id
                   3841: 
                   3842: =cut
                   3843: 
                   3844: sub copyrightdescription {
1.166     www      3845:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3846: }
1.197     matthew  3847: 
                   3848: =pod
                   3849: 
1.648     raeburn  3850: =item * &source_copyrightids() 
1.192     taceyjo1 3851: 
                   3852: returns list of all source copyrights
                   3853: 
                   3854: =cut
                   3855: 
                   3856: sub source_copyrightids {
                   3857:     return sort(keys(%scprtag));
                   3858: }
                   3859: 
                   3860: =pod
                   3861: 
1.648     raeburn  3862: =item * &source_copyrightdescription() 
1.192     taceyjo1 3863: 
                   3864: returns description of a specified source copyright id
                   3865: 
                   3866: =cut
                   3867: 
                   3868: sub source_copyrightdescription {
                   3869:     return &mt($scprtag{shift(@_)});
                   3870: }
1.112     bowersj2 3871: 
                   3872: =pod
                   3873: 
1.648     raeburn  3874: =item * &filecategories() 
1.112     bowersj2 3875: 
                   3876: returns list of all file categories
                   3877: 
                   3878: =cut
                   3879: 
                   3880: sub filecategories {
                   3881:     return sort(keys(%category_extensions));
                   3882: }
                   3883: 
                   3884: =pod
                   3885: 
1.648     raeburn  3886: =item * &filecategorytypes() 
1.112     bowersj2 3887: 
                   3888: returns list of file types belonging to a given file
                   3889: category
                   3890: 
                   3891: =cut
                   3892: 
                   3893: sub filecategorytypes {
1.356     albertel 3894:     my ($cat) = @_;
                   3895:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3896: }
                   3897: 
                   3898: =pod
                   3899: 
1.648     raeburn  3900: =item * &fileembstyle() 
1.112     bowersj2 3901: 
                   3902: returns embedding style for a specified file type
                   3903: 
                   3904: =cut
                   3905: 
                   3906: sub fileembstyle {
                   3907:     return $fe{lc(shift(@_))};
1.169     www      3908: }
                   3909: 
1.351     www      3910: sub filemimetype {
                   3911:     return $fm{lc(shift(@_))};
                   3912: }
                   3913: 
1.169     www      3914: 
                   3915: sub filecategoryselect {
                   3916:     my ($name,$value)=@_;
1.189     matthew  3917:     return &select_form($value,$name,
1.970     raeburn  3918:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3919: }
                   3920: 
                   3921: =pod
                   3922: 
1.648     raeburn  3923: =item * &filedescription() 
1.112     bowersj2 3924: 
                   3925: returns description for a specified file type
                   3926: 
                   3927: =cut
                   3928: 
                   3929: sub filedescription {
1.188     matthew  3930:     my $file_description = $fd{lc(shift())};
                   3931:     $file_description =~ s:([\[\]]):~$1:g;
                   3932:     return &mt($file_description);
1.112     bowersj2 3933: }
                   3934: 
                   3935: =pod
                   3936: 
1.648     raeburn  3937: =item * &filedescriptionex() 
1.112     bowersj2 3938: 
                   3939: returns description for a specified file type with
                   3940: extra formatting
                   3941: 
                   3942: =cut
                   3943: 
                   3944: sub filedescriptionex {
                   3945:     my $ex=shift;
1.188     matthew  3946:     my $file_description = $fd{lc($ex)};
                   3947:     $file_description =~ s:([\[\]]):~$1:g;
                   3948:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3949: }
                   3950: 
                   3951: # End of .tab access
                   3952: =pod
                   3953: 
                   3954: =back
                   3955: 
                   3956: =cut
                   3957: 
                   3958: # ------------------------------------------------------------------ File Types
                   3959: sub fileextensions {
                   3960:     return sort(keys(%fe));
                   3961: }
                   3962: 
1.97      www      3963: # ----------------------------------------------------------- Display Languages
                   3964: # returns a hash with all desired display languages
                   3965: #
                   3966: 
                   3967: sub display_languages {
                   3968:     my %languages=();
1.695     raeburn  3969:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3970: 	$languages{$lang}=1;
1.97      www      3971:     }
                   3972:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3973:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3974: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3975: 	    $languages{$lang}=1;
1.97      www      3976:         }
                   3977:     }
                   3978:     return %languages;
1.14      harris41 3979: }
                   3980: 
1.582     albertel 3981: sub languages {
                   3982:     my ($possible_langs) = @_;
1.695     raeburn  3983:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3984:     if (!ref($possible_langs)) {
                   3985: 	if( wantarray ) {
                   3986: 	    return @preferred_langs;
                   3987: 	} else {
                   3988: 	    return $preferred_langs[0];
                   3989: 	}
                   3990:     }
                   3991:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3992:     my @preferred_possibilities;
                   3993:     foreach my $preferred_lang (@preferred_langs) {
                   3994: 	if (exists($possibilities{$preferred_lang})) {
                   3995: 	    push(@preferred_possibilities, $preferred_lang);
                   3996: 	}
                   3997:     }
                   3998:     if( wantarray ) {
                   3999: 	return @preferred_possibilities;
                   4000:     }
                   4001:     return $preferred_possibilities[0];
                   4002: }
                   4003: 
1.742     raeburn  4004: sub user_lang {
                   4005:     my ($touname,$toudom,$fromcid) = @_;
                   4006:     my @userlangs;
                   4007:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4008:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4009:                     $env{'course.'.$fromcid.'.languages'}));
                   4010:     } else {
                   4011:         my %langhash = &getlangs($touname,$toudom);
                   4012:         if ($langhash{'languages'} ne '') {
                   4013:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4014:         } else {
                   4015:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4016:             if ($domdefs{'lang_def'} ne '') {
                   4017:                 @userlangs = ($domdefs{'lang_def'});
                   4018:             }
                   4019:         }
                   4020:     }
                   4021:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4022:     my $user_lh = Apache::localize->get_handle(@languages);
                   4023:     return $user_lh;
                   4024: }
                   4025: 
                   4026: 
1.112     bowersj2 4027: ###############################################################
                   4028: ##               Student Answer Attempts                     ##
                   4029: ###############################################################
                   4030: 
                   4031: =pod
                   4032: 
                   4033: =head1 Alternate Problem Views
                   4034: 
                   4035: =over 4
                   4036: 
1.648     raeburn  4037: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4038:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4039: 
                   4040: Return string with previous attempt on problem. Arguments:
                   4041: 
                   4042: =over 4
                   4043: 
                   4044: =item * $symb: Problem, including path
                   4045: 
                   4046: =item * $username: username of the desired student
                   4047: 
                   4048: =item * $domain: domain of the desired student
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $course: Course ID
1.14      harris41 4051: 
1.112     bowersj2 4052: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4053:     something
1.14      harris41 4054: 
1.112     bowersj2 4055: =item * $regexp: if string matches this regexp, the string will be
                   4056:     sent to $gradesub
1.14      harris41 4057: 
1.112     bowersj2 4058: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4059: 
1.1075.2.86  raeburn  4060: =item * $usec: section of the desired student
                   4061: 
                   4062: =item * $identifier: counter for student (multiple students one problem) or
                   4063:     problem (one student; whole sequence).
                   4064: 
1.112     bowersj2 4065: =back
1.14      harris41 4066: 
1.112     bowersj2 4067: The output string is a table containing all desired attempts, if any.
1.16      harris41 4068: 
1.112     bowersj2 4069: =cut
1.1       albertel 4070: 
                   4071: sub get_previous_attempt {
1.1075.2.86  raeburn  4072:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4073:   my $prevattempts='';
1.43      ng       4074:   no strict 'refs';
1.1       albertel 4075:   if ($symb) {
1.3       albertel 4076:     my (%returnhash)=
                   4077:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4078:     if ($returnhash{'version'}) {
                   4079:       my %lasthash=();
                   4080:       my $version;
                   4081:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4082:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4083:             if ($key =~ /\.rawrndseed$/) {
                   4084:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4085:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4086:             } else {
                   4087:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4088:             }
1.19      harris41 4089:         }
1.1       albertel 4090:       }
1.596     albertel 4091:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4092:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4093:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4094:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4095:       foreach my $key (sort(keys(%lasthash))) {
                   4096: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4097: 	if ($#parts > 0) {
1.31      albertel 4098: 	  my $data=$parts[-1];
1.989     raeburn  4099:           next if ($data eq 'foilorder');
1.31      albertel 4100: 	  pop(@parts);
1.1010    www      4101:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4102:           if ($data eq 'type') {
                   4103:               unless ($showsurv) {
                   4104:                   my $id = join(',',@parts);
                   4105:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4106:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4107:                       $lasthidden{$ign.'.'.$id} = 1;
                   4108:                   }
1.945     raeburn  4109:               }
1.1075.2.86  raeburn  4110:               if ($identifier ne '') {
                   4111:                   my $id = join(',',@parts);
                   4112:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4113:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4114:                       $hidestatus{$ign.'.'.$id} = 1;
                   4115:                   }
                   4116:               }
                   4117:           } elsif ($data eq 'regrader') {
                   4118:               if (($identifier ne '') && (@parts)) {
                   4119:                   my $id = join(',',@parts);
                   4120:                   $regraded{$ign.'.'.$id} = 1;
                   4121:               }
1.1010    www      4122:           } 
1.31      albertel 4123: 	} else {
1.41      ng       4124: 	  if ($#parts == 0) {
                   4125: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4126: 	  } else {
                   4127: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4128: 	  }
1.31      albertel 4129: 	}
1.16      harris41 4130:       }
1.596     albertel 4131:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4132:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4133:         my (%solved,%resets,%probstatus);
                   4134:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4135:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4136:                 foreach my $id (keys(%regraded)) {
                   4137:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4138:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4139:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4140:                         push(@{$resets{$id}},$version);
                   4141:                     }
                   4142:                 }
                   4143:             }
                   4144:         }
1.40      ng       4145: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4146:             my (@hidden,@unsolved);
1.945     raeburn  4147:             if (%typeparts) {
                   4148:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4149:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4150:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4151:                         push(@hidden,$id);
1.1075.2.86  raeburn  4152:                     } elsif ($identifier ne '') {
                   4153:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4154:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4155:                                 ($hidestatus{$id})) {
                   4156:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4157:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4158:                                 push(@{$solved{$id}},$version);
                   4159:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4160:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4161:                                 my $skip;
                   4162:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4163:                                     foreach my $reset (@{$resets{$id}}) {
                   4164:                                         if ($reset > $solved{$id}[-1]) {
                   4165:                                             $skip=1;
                   4166:                                             last;
                   4167:                                         }
                   4168:                                     }
                   4169:                                 }
                   4170:                                 unless ($skip) {
                   4171:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4172:                                     push(@unsolved,$partslist);
                   4173:                                 }
                   4174:                             }
                   4175:                         }
1.945     raeburn  4176:                     }
                   4177:                 }
                   4178:             }
                   4179:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4180:                            '<td>'.&mt('Transaction [_1]',$version);
                   4181:             if (@unsolved) {
                   4182:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4183:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4184:                                  &mt('Hide').'</label></span>';
                   4185:             }
                   4186:             $prevattempts .= '</td>';
1.945     raeburn  4187:             if (@hidden) {
                   4188:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4189:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4190:                     my $hide;
                   4191:                     foreach my $id (@hidden) {
                   4192:                         if ($key =~ /^\Q$id\E/) {
                   4193:                             $hide = 1;
                   4194:                             last;
                   4195:                         }
                   4196:                     }
                   4197:                     if ($hide) {
                   4198:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4199:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4200:                             my $value = &format_previous_attempt_value($key,
                   4201:                                              $returnhash{$version.':'.$key});
                   4202:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4203:                         } else {
                   4204:                             $prevattempts.='<td>&nbsp;</td>';
                   4205:                         }
                   4206:                     } else {
                   4207:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4208:                             my $value = $returnhash{$version.':'.$key};
                   4209:                             if ($key =~ /\.rndseed$/) {
                   4210:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4211:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4212:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4213:                                 }
                   4214:                             }
                   4215:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4216:                                            '&nbsp;</td>';
1.945     raeburn  4217:                         } else {
                   4218:                             $prevattempts.='<td>&nbsp;</td>';
                   4219:                         }
                   4220:                     }
                   4221:                 }
                   4222:             } else {
                   4223: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4224:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4225:                     my $value = $returnhash{$version.':'.$key};
                   4226:                     if ($key =~ /\.rndseed$/) {
                   4227:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4228:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4229:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4230:                         }
                   4231:                     }
                   4232:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4233:                                    '&nbsp;</td>';
1.945     raeburn  4234: 	        }
                   4235:             }
                   4236: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4237: 	 }
1.1       albertel 4238:       }
1.945     raeburn  4239:       my @currhidden = keys(%lasthidden);
1.596     albertel 4240:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4241:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4242:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4243:           if (%typeparts) {
                   4244:               my $hidden;
                   4245:               foreach my $id (@currhidden) {
                   4246:                   if ($key =~ /^\Q$id\E/) {
                   4247:                       $hidden = 1;
                   4248:                       last;
                   4249:                   }
                   4250:               }
                   4251:               if ($hidden) {
                   4252:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4253:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4254:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4255:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4256:                           $value = &$gradesub($value);
                   4257:                       }
                   4258:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4259:                   } else {
                   4260:                       $prevattempts.='<td>&nbsp;</td>';
                   4261:                   }
                   4262:               } else {
                   4263:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4264:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4265:                       $value = &$gradesub($value);
                   4266:                   }
                   4267:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4268:               }
                   4269:           } else {
                   4270: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4271: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4272:                   $value = &$gradesub($value);
                   4273:               }
                   4274: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4275:           }
1.16      harris41 4276:       }
1.596     albertel 4277:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4278:     } else {
1.596     albertel 4279:       $prevattempts=
                   4280: 	  &start_data_table().&start_data_table_row().
                   4281: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4282: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4283:     }
                   4284:   } else {
1.596     albertel 4285:     $prevattempts=
                   4286: 	  &start_data_table().&start_data_table_row().
                   4287: 	  '<td>'.&mt('No data.').'</td>'.
                   4288: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4289:   }
1.10      albertel 4290: }
                   4291: 
1.581     albertel 4292: sub format_previous_attempt_value {
                   4293:     my ($key,$value) = @_;
1.1011    www      4294:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4295: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4296:     } elsif (ref($value) eq 'ARRAY') {
                   4297: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4298:     } elsif ($key =~ /answerstring$/) {
                   4299:         my %answers = &Apache::lonnet::str2hash($value);
                   4300:         my @anskeys = sort(keys(%answers));
                   4301:         if (@anskeys == 1) {
                   4302:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4303:             if ($answer =~ m{\0}) {
                   4304:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4305:             }
                   4306:             my $tag_internal_answer_name = 'INTERNAL';
                   4307:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4308:                 $value = $answer; 
                   4309:             } else {
                   4310:                 $value = $anskeys[0].'='.$answer;
                   4311:             }
                   4312:         } else {
                   4313:             foreach my $ans (@anskeys) {
                   4314:                 my $answer = $answers{$ans};
1.1001    raeburn  4315:                 if ($answer =~ m{\0}) {
                   4316:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4317:                 }
                   4318:                 $value .=  $ans.'='.$answer.'<br />';;
                   4319:             } 
                   4320:         }
1.581     albertel 4321:     } else {
                   4322: 	$value = &unescape($value);
                   4323:     }
                   4324:     return $value;
                   4325: }
                   4326: 
                   4327: 
1.107     albertel 4328: sub relative_to_absolute {
                   4329:     my ($url,$output)=@_;
                   4330:     my $parser=HTML::TokeParser->new(\$output);
                   4331:     my $token;
                   4332:     my $thisdir=$url;
                   4333:     my @rlinks=();
                   4334:     while ($token=$parser->get_token) {
                   4335: 	if ($token->[0] eq 'S') {
                   4336: 	    if ($token->[1] eq 'a') {
                   4337: 		if ($token->[2]->{'href'}) {
                   4338: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4339: 		}
                   4340: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4341: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4342: 	    } elsif ($token->[1] eq 'base') {
                   4343: 		$thisdir=$token->[2]->{'href'};
                   4344: 	    }
                   4345: 	}
                   4346:     }
                   4347:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4348:     foreach my $link (@rlinks) {
1.726     raeburn  4349: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4350: 		($link=~/^\//) ||
                   4351: 		($link=~/^javascript:/i) ||
                   4352: 		($link=~/^mailto:/i) ||
                   4353: 		($link=~/^\#/)) {
                   4354: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4355: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4356: 	}
                   4357:     }
                   4358: # -------------------------------------------------- Deal with Applet codebases
                   4359:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4360:     return $output;
                   4361: }
                   4362: 
1.112     bowersj2 4363: =pod
                   4364: 
1.648     raeburn  4365: =item * &get_student_view()
1.112     bowersj2 4366: 
                   4367: show a snapshot of what student was looking at
                   4368: 
                   4369: =cut
                   4370: 
1.10      albertel 4371: sub get_student_view {
1.186     albertel 4372:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4373:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4374:   my (%form);
1.10      albertel 4375:   my @elements=('symb','courseid','domain','username');
                   4376:   foreach my $element (@elements) {
1.186     albertel 4377:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4378:   }
1.186     albertel 4379:   if (defined($moreenv)) {
                   4380:       %form=(%form,%{$moreenv});
                   4381:   }
1.236     albertel 4382:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4383:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4384:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4385:   $userview=~s/\<body[^\>]*\>//gi;
                   4386:   $userview=~s/\<\/body\>//gi;
                   4387:   $userview=~s/\<html\>//gi;
                   4388:   $userview=~s/\<\/html\>//gi;
                   4389:   $userview=~s/\<head\>//gi;
                   4390:   $userview=~s/\<\/head\>//gi;
                   4391:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4392:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4393:   if (wantarray) {
                   4394:      return ($userview,$response);
                   4395:   } else {
                   4396:      return $userview;
                   4397:   }
                   4398: }
                   4399: 
                   4400: sub get_student_view_with_retries {
                   4401:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4402: 
                   4403:     my $ok = 0;                 # True if we got a good response.
                   4404:     my $content;
                   4405:     my $response;
                   4406: 
                   4407:     # Try to get the student_view done. within the retries count:
                   4408:     
                   4409:     do {
                   4410:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4411:          $ok      = $response->is_success;
                   4412:          if (!$ok) {
                   4413:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4414:          }
                   4415:          $retries--;
                   4416:     } while (!$ok && ($retries > 0));
                   4417:     
                   4418:     if (!$ok) {
                   4419:        $content = '';          # On error return an empty content.
                   4420:     }
1.651     www      4421:     if (wantarray) {
                   4422:        return ($content, $response);
                   4423:     } else {
                   4424:        return $content;
                   4425:     }
1.11      albertel 4426: }
                   4427: 
1.112     bowersj2 4428: =pod
                   4429: 
1.648     raeburn  4430: =item * &get_student_answers() 
1.112     bowersj2 4431: 
                   4432: show a snapshot of how student was answering problem
                   4433: 
                   4434: =cut
                   4435: 
1.11      albertel 4436: sub get_student_answers {
1.100     sakharuk 4437:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4438:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4439:   my (%moreenv);
1.11      albertel 4440:   my @elements=('symb','courseid','domain','username');
                   4441:   foreach my $element (@elements) {
1.186     albertel 4442:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4443:   }
1.186     albertel 4444:   $moreenv{'grade_target'}='answer';
                   4445:   %moreenv=(%form,%moreenv);
1.497     raeburn  4446:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4447:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4448:   return $userview;
1.1       albertel 4449: }
1.116     albertel 4450: 
                   4451: =pod
                   4452: 
                   4453: =item * &submlink()
                   4454: 
1.242     albertel 4455: Inputs: $text $uname $udom $symb $target
1.116     albertel 4456: 
                   4457: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4458: 
                   4459: =cut
                   4460: 
                   4461: ###############################################
                   4462: sub submlink {
1.242     albertel 4463:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4464:     if (!($uname && $udom)) {
                   4465: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4466: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4467: 	if (!$symb) { $symb=$cursymb; }
                   4468:     }
1.254     matthew  4469:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4470:     $symb=&escape($symb);
1.960     bisitz   4471:     if ($target) { $target=" target=\"$target\""; }
                   4472:     return
                   4473:         '<a href="/adm/grades?command=submission'.
                   4474:         '&amp;symb='.$symb.
                   4475:         '&amp;student='.$uname.
                   4476:         '&amp;userdom='.$udom.'"'.
                   4477:         $target.'>'.$text.'</a>';
1.242     albertel 4478: }
                   4479: ##############################################
                   4480: 
                   4481: =pod
                   4482: 
                   4483: =item * &pgrdlink()
                   4484: 
                   4485: Inputs: $text $uname $udom $symb $target
                   4486: 
                   4487: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4488: 
                   4489: =cut
                   4490: 
                   4491: ###############################################
                   4492: sub pgrdlink {
                   4493:     my $link=&submlink(@_);
                   4494:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4495:     return $link;
                   4496: }
                   4497: ##############################################
                   4498: 
                   4499: =pod
                   4500: 
                   4501: =item * &pprmlink()
                   4502: 
                   4503: Inputs: $text $uname $udom $symb $target
                   4504: 
                   4505: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4506: student and a specific resource
1.242     albertel 4507: 
                   4508: =cut
                   4509: 
                   4510: ###############################################
                   4511: sub pprmlink {
                   4512:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4513:     if (!($uname && $udom)) {
                   4514: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4515: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4516: 	if (!$symb) { $symb=$cursymb; }
                   4517:     }
1.254     matthew  4518:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4519:     $symb=&escape($symb);
1.242     albertel 4520:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4521:     return '<a href="/adm/parmset?command=set&amp;'.
                   4522: 	'symb='.$symb.'&amp;uname='.$uname.
                   4523: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4524: }
                   4525: ##############################################
1.37      matthew  4526: 
1.112     bowersj2 4527: =pod
                   4528: 
                   4529: =back
                   4530: 
                   4531: =cut
                   4532: 
1.37      matthew  4533: ###############################################
1.51      www      4534: 
                   4535: 
                   4536: sub timehash {
1.687     raeburn  4537:     my ($thistime) = @_;
                   4538:     my $timezone = &Apache::lonlocal::gettimezone();
                   4539:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4540:                      ->set_time_zone($timezone);
                   4541:     my $wday = $dt->day_of_week();
                   4542:     if ($wday == 7) { $wday = 0; }
                   4543:     return ( 'second' => $dt->second(),
                   4544:              'minute' => $dt->minute(),
                   4545:              'hour'   => $dt->hour(),
                   4546:              'day'     => $dt->day_of_month(),
                   4547:              'month'   => $dt->month(),
                   4548:              'year'    => $dt->year(),
                   4549:              'weekday' => $wday,
                   4550:              'dayyear' => $dt->day_of_year(),
                   4551:              'dlsav'   => $dt->is_dst() );
1.51      www      4552: }
                   4553: 
1.370     www      4554: sub utc_string {
                   4555:     my ($date)=@_;
1.371     www      4556:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4557: }
                   4558: 
1.51      www      4559: sub maketime {
                   4560:     my %th=@_;
1.687     raeburn  4561:     my ($epoch_time,$timezone,$dt);
                   4562:     $timezone = &Apache::lonlocal::gettimezone();
                   4563:     eval {
                   4564:         $dt = DateTime->new( year   => $th{'year'},
                   4565:                              month  => $th{'month'},
                   4566:                              day    => $th{'day'},
                   4567:                              hour   => $th{'hour'},
                   4568:                              minute => $th{'minute'},
                   4569:                              second => $th{'second'},
                   4570:                              time_zone => $timezone,
                   4571:                          );
                   4572:     };
                   4573:     if (!$@) {
                   4574:         $epoch_time = $dt->epoch;
                   4575:         if ($epoch_time) {
                   4576:             return $epoch_time;
                   4577:         }
                   4578:     }
1.51      www      4579:     return POSIX::mktime(
                   4580:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4581:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4582: }
                   4583: 
                   4584: #########################################
1.51      www      4585: 
                   4586: sub findallcourses {
1.482     raeburn  4587:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4588:     my %roles;
                   4589:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4590:     my %courses;
1.51      www      4591:     my $now=time;
1.482     raeburn  4592:     if (!defined($uname)) {
                   4593:         $uname = $env{'user.name'};
                   4594:     }
                   4595:     if (!defined($udom)) {
                   4596:         $udom = $env{'user.domain'};
                   4597:     }
                   4598:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4599:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4600:         if (!%roles) {
                   4601:             %roles = (
                   4602:                        cc => 1,
1.907     raeburn  4603:                        co => 1,
1.482     raeburn  4604:                        in => 1,
                   4605:                        ep => 1,
                   4606:                        ta => 1,
                   4607:                        cr => 1,
                   4608:                        st => 1,
                   4609:              );
                   4610:         }
                   4611:         foreach my $entry (keys(%roleshash)) {
                   4612:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4613:             if ($trole =~ /^cr/) { 
                   4614:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4615:             } else {
                   4616:                 next if (!exists($roles{$trole}));
                   4617:             }
                   4618:             if ($tend) {
                   4619:                 next if ($tend < $now);
                   4620:             }
                   4621:             if ($tstart) {
                   4622:                 next if ($tstart > $now);
                   4623:             }
1.1058    raeburn  4624:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4625:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4626:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4627:             if ($secpart eq '') {
                   4628:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4629:                 $sec = 'none';
1.1058    raeburn  4630:                 $value .= $cnum.'/';
1.482     raeburn  4631:             } else {
                   4632:                 $cnum = $cnumpart;
                   4633:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4634:                 $value .= $cnum.'/'.$sec;
                   4635:             }
                   4636:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4637:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4638:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4639:                 }
                   4640:             } else {
                   4641:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4642:             }
1.482     raeburn  4643:         }
                   4644:     } else {
                   4645:         foreach my $key (keys(%env)) {
1.483     albertel 4646: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4647:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4648: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4649: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4650: 	        next if (%roles && !exists($roles{$role}));
                   4651: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4652:                 my $active=1;
                   4653:                 if ($starttime) {
                   4654: 		    if ($now<$starttime) { $active=0; }
                   4655:                 }
                   4656:                 if ($endtime) {
                   4657:                     if ($now>$endtime) { $active=0; }
                   4658:                 }
                   4659:                 if ($active) {
1.1058    raeburn  4660:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4661:                     if ($sec eq '') {
                   4662:                         $sec = 'none';
1.1058    raeburn  4663:                     } else {
                   4664:                         $value .= $sec;
                   4665:                     }
                   4666:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4667:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4668:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4669:                         }
                   4670:                     } else {
                   4671:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4672:                     }
1.474     raeburn  4673:                 }
                   4674:             }
1.51      www      4675:         }
                   4676:     }
1.474     raeburn  4677:     return %courses;
1.51      www      4678: }
1.37      matthew  4679: 
1.54      www      4680: ###############################################
1.474     raeburn  4681: 
                   4682: sub blockcheck {
1.1075.2.73  raeburn  4683:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4684: 
1.1075.2.73  raeburn  4685:     if (defined($udom) && defined($uname)) {
                   4686:         # If uname and udom are for a course, check for blocks in the course.
                   4687:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4688:             my ($startblock,$endblock,$triggerblock) =
                   4689:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4690:             return ($startblock,$endblock,$triggerblock);
                   4691:         }
                   4692:     } else {
1.490     raeburn  4693:         $udom = $env{'user.domain'};
                   4694:         $uname = $env{'user.name'};
                   4695:     }
                   4696: 
1.502     raeburn  4697:     my $startblock = 0;
                   4698:     my $endblock = 0;
1.1062    raeburn  4699:     my $triggerblock = '';
1.482     raeburn  4700:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4701: 
1.490     raeburn  4702:     # If uname is for a user, and activity is course-specific, i.e.,
                   4703:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4704: 
1.490     raeburn  4705:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4706:          $activity eq 'groups' || $activity eq 'printout') &&
                   4707:         ($env{'request.course.id'})) {
1.490     raeburn  4708:         foreach my $key (keys(%live_courses)) {
                   4709:             if ($key ne $env{'request.course.id'}) {
                   4710:                 delete($live_courses{$key});
                   4711:             }
                   4712:         }
                   4713:     }
                   4714: 
                   4715:     my $otheruser = 0;
                   4716:     my %own_courses;
                   4717:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4718:         # Resource belongs to user other than current user.
                   4719:         $otheruser = 1;
                   4720:         # Gather courses for current user
                   4721:         %own_courses = 
                   4722:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4723:     }
                   4724: 
                   4725:     # Gather active course roles - course coordinator, instructor, 
                   4726:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4727: 
                   4728:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4729:         my ($cdom,$cnum);
                   4730:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4731:             $cdom = $env{'course.'.$course.'.domain'};
                   4732:             $cnum = $env{'course.'.$course.'.num'};
                   4733:         } else {
1.490     raeburn  4734:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4735:         }
                   4736:         my $no_ownblock = 0;
                   4737:         my $no_userblock = 0;
1.533     raeburn  4738:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4739:             # Check if current user has 'evb' priv for this
                   4740:             if (defined($own_courses{$course})) {
                   4741:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4742:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4743:                     if ($sec ne 'none') {
                   4744:                         $checkrole .= '/'.$sec;
                   4745:                     }
                   4746:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4747:                         $no_ownblock = 1;
                   4748:                         last;
                   4749:                     }
                   4750:                 }
                   4751:             }
                   4752:             # if they have 'evb' priv and are currently not playing student
                   4753:             next if (($no_ownblock) &&
                   4754:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4755:         }
1.474     raeburn  4756:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4757:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4758:             if ($sec ne 'none') {
1.482     raeburn  4759:                 $checkrole .= '/'.$sec;
1.474     raeburn  4760:             }
1.490     raeburn  4761:             if ($otheruser) {
                   4762:                 # Resource belongs to user other than current user.
                   4763:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4764:                 my (%allroles,%userroles);
                   4765:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4766:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4767:                         my ($trole,$tdom,$tnum,$tsec);
                   4768:                         if ($entry =~ /^cr/) {
                   4769:                             ($trole,$tdom,$tnum,$tsec) = 
                   4770:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4771:                         } else {
                   4772:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4773:                         }
                   4774:                         my ($spec,$area,$trest);
                   4775:                         $area = '/'.$tdom.'/'.$tnum;
                   4776:                         $trest = $tnum;
                   4777:                         if ($tsec ne '') {
                   4778:                             $area .= '/'.$tsec;
                   4779:                             $trest .= '/'.$tsec;
                   4780:                         }
                   4781:                         $spec = $trole.'.'.$area;
                   4782:                         if ($trole =~ /^cr/) {
                   4783:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4784:                                                               $tdom,$spec,$trest,$area);
                   4785:                         } else {
                   4786:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4787:                                                                 $tdom,$spec,$trest,$area);
                   4788:                         }
                   4789:                     }
1.1075.2.124  raeburn  4790:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4791:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4792:                         if ($1) {
                   4793:                             $no_userblock = 1;
                   4794:                             last;
                   4795:                         }
1.486     raeburn  4796:                     }
                   4797:                 }
1.490     raeburn  4798:             } else {
                   4799:                 # Resource belongs to current user
                   4800:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4801:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4802:                     $no_ownblock = 1;
                   4803:                     last;
                   4804:                 }
1.474     raeburn  4805:             }
                   4806:         }
                   4807:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4808:         next if (($no_ownblock) &&
1.491     albertel 4809:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4810:         next if ($no_userblock);
1.474     raeburn  4811: 
1.1075.2.128  raeburn  4812:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4813:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4814:         
1.1062    raeburn  4815:         my ($start,$end,$trigger) = 
                   4816:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4817:         if (($start != 0) && 
                   4818:             (($startblock == 0) || ($startblock > $start))) {
                   4819:             $startblock = $start;
1.1062    raeburn  4820:             if ($trigger ne '') {
                   4821:                 $triggerblock = $trigger;
                   4822:             }
1.502     raeburn  4823:         }
                   4824:         if (($end != 0)  &&
                   4825:             (($endblock == 0) || ($endblock < $end))) {
                   4826:             $endblock = $end;
1.1062    raeburn  4827:             if ($trigger ne '') {
                   4828:                 $triggerblock = $trigger;
                   4829:             }
1.502     raeburn  4830:         }
1.490     raeburn  4831:     }
1.1062    raeburn  4832:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4833: }
                   4834: 
                   4835: sub get_blocks {
1.1062    raeburn  4836:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4837:     my $startblock = 0;
                   4838:     my $endblock = 0;
1.1062    raeburn  4839:     my $triggerblock = '';
1.490     raeburn  4840:     my $course = $cdom.'_'.$cnum;
                   4841:     $setters->{$course} = {};
                   4842:     $setters->{$course}{'staff'} = [];
                   4843:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4844:     $setters->{$course}{'triggers'} = [];
                   4845:     my (@blockers,%triggered);
                   4846:     my $now = time;
                   4847:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4848:     if ($activity eq 'docs') {
                   4849:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4850:         foreach my $block (@blockers) {
                   4851:             if ($block =~ /^firstaccess____(.+)$/) {
                   4852:                 my $item = $1;
                   4853:                 my $type = 'map';
                   4854:                 my $timersymb = $item;
                   4855:                 if ($item eq 'course') {
                   4856:                     $type = 'course';
                   4857:                 } elsif ($item =~ /___\d+___/) {
                   4858:                     $type = 'resource';
                   4859:                 } else {
                   4860:                     $timersymb = &Apache::lonnet::symbread($item);
                   4861:                 }
                   4862:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4863:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4864:                 $triggered{$block} = {
                   4865:                                        start => $start,
                   4866:                                        end   => $end,
                   4867:                                        type  => $type,
                   4868:                                      };
                   4869:             }
                   4870:         }
                   4871:     } else {
                   4872:         foreach my $block (keys(%commblocks)) {
                   4873:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4874:                 my ($start,$end) = ($1,$2);
                   4875:                 if ($start <= time && $end >= time) {
                   4876:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4877:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4878:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4879:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4880:                                     push(@blockers,$block);
                   4881:                                 }
                   4882:                             }
                   4883:                         }
                   4884:                     }
                   4885:                 }
                   4886:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4887:                 my $item = $1;
                   4888:                 my $timersymb = $item; 
                   4889:                 my $type = 'map';
                   4890:                 if ($item eq 'course') {
                   4891:                     $type = 'course';
                   4892:                 } elsif ($item =~ /___\d+___/) {
                   4893:                     $type = 'resource';
                   4894:                 } else {
                   4895:                     $timersymb = &Apache::lonnet::symbread($item);
                   4896:                 }
                   4897:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4898:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4899:                 if ($start && $end) {
                   4900:                     if (($start <= time) && ($end >= time)) {
                   4901:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4902:                             push(@blockers,$block);
                   4903:                             $triggered{$block} = {
                   4904:                                                    start => $start,
                   4905:                                                    end   => $end,
                   4906:                                                    type  => $type,
                   4907:                                                  };
                   4908:                         }
                   4909:                     }
1.490     raeburn  4910:                 }
1.1062    raeburn  4911:             }
                   4912:         }
                   4913:     }
                   4914:     foreach my $blocker (@blockers) {
                   4915:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4916:             &parse_block_record($commblocks{$blocker});
                   4917:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4918:         my ($start,$end,$triggertype);
                   4919:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4920:             ($start,$end) = ($1,$2);
                   4921:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4922:             $start = $triggered{$blocker}{'start'};
                   4923:             $end = $triggered{$blocker}{'end'};
                   4924:             $triggertype = $triggered{$blocker}{'type'};
                   4925:         }
                   4926:         if ($start) {
                   4927:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4928:             if ($triggertype) {
                   4929:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4930:             } else {
                   4931:                 push(@{$$setters{$course}{'triggers'}},0);
                   4932:             }
                   4933:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4934:                 $startblock = $start;
                   4935:                 if ($triggertype) {
                   4936:                     $triggerblock = $blocker;
1.474     raeburn  4937:                 }
                   4938:             }
1.1062    raeburn  4939:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4940:                $endblock = $end;
                   4941:                if ($triggertype) {
                   4942:                    $triggerblock = $blocker;
                   4943:                }
                   4944:             }
1.474     raeburn  4945:         }
                   4946:     }
1.1062    raeburn  4947:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4948: }
                   4949: 
                   4950: sub parse_block_record {
                   4951:     my ($record) = @_;
                   4952:     my ($setuname,$setudom,$title,$blocks);
                   4953:     if (ref($record) eq 'HASH') {
                   4954:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4955:         $title = &unescape($record->{'event'});
                   4956:         $blocks = $record->{'blocks'};
                   4957:     } else {
                   4958:         my @data = split(/:/,$record,3);
                   4959:         if (scalar(@data) eq 2) {
                   4960:             $title = $data[1];
                   4961:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4962:         } else {
                   4963:             ($setuname,$setudom,$title) = @data;
                   4964:         }
                   4965:         $blocks = { 'com' => 'on' };
                   4966:     }
                   4967:     return ($setuname,$setudom,$title,$blocks);
                   4968: }
                   4969: 
1.854     kalberla 4970: sub blocking_status {
1.1075.2.73  raeburn  4971:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4972:     my %setters;
1.890     droeschl 4973: 
1.1061    raeburn  4974: # check for active blocking
1.1062    raeburn  4975:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4976:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4977:     my $blocked = 0;
                   4978:     if ($startblock && $endblock) {
                   4979:         $blocked = 1;
                   4980:     }
1.890     droeschl 4981: 
1.1061    raeburn  4982: # caller just wants to know whether a block is active
                   4983:     if (!wantarray) { return $blocked; }
                   4984: 
                   4985: # build a link to a popup window containing the details
                   4986:     my $querystring  = "?activity=$activity";
                   4987: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4988:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4989:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4990:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4991:     } elsif ($activity eq 'docs') {
                   4992:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4993:     }
1.1061    raeburn  4994: 
                   4995:     my $output .= <<'END_MYBLOCK';
                   4996: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4997:     var options = "width=" + w + ",height=" + h + ",";
                   4998:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4999:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5000:     var newWin = window.open(url, wdwName, options);
                   5001:     newWin.focus();
                   5002: }
1.890     droeschl 5003: END_MYBLOCK
1.854     kalberla 5004: 
1.1061    raeburn  5005:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5006:   
1.1061    raeburn  5007:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5008:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5009:     my $class = 'LC_comblock';
1.1062    raeburn  5010:     if ($activity eq 'docs') {
                   5011:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5012:         $class = '';
1.1063    raeburn  5013:     } elsif ($activity eq 'printout') {
                   5014:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5015:     } elsif ($activity eq 'passwd') {
                   5016:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5017:     }
1.1061    raeburn  5018:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5019: <div class='$class'>
1.869     kalberla 5020:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5021:   title='$text'>
                   5022:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5023:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5024:   title='$text'>$text</a>
1.867     kalberla 5025: </div>
                   5026: 
                   5027: END_BLOCK
1.474     raeburn  5028: 
1.1061    raeburn  5029:     return ($blocked, $output);
1.854     kalberla 5030: }
1.490     raeburn  5031: 
1.60      matthew  5032: ###############################################
                   5033: 
1.682     raeburn  5034: sub check_ip_acc {
1.1075.2.105  raeburn  5035:     my ($acc,$clientip)=@_;
1.682     raeburn  5036:     &Apache::lonxml::debug("acc is $acc");
                   5037:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5038:         return 1;
                   5039:     }
1.1075.2.141.  .4(raebu 5040:20):     my ($ip,$allowed);
                   5041:20):     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5042:20):         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5043:20):         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5044:20):     } else {
                   5045:20):         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5046:20):     }
1.682     raeburn  5047: 
                   5048:     my $name;
1.1075.2.141.  .1(raebu 5049:20):     my %access = (
                   5050:20):                      allowfrom => 1,
                   5051:20):                      denyfrom  => 0,
                   5052:20):                  );
                   5053:20):     my @allows;
                   5054:20):     my @denies;
                   5055:20):     foreach my $item (split(',',$acc)) {
                   5056:20):         $item =~ s/^\s*//;
                   5057:20):         $item =~ s/\s*$//;
                   5058:20):         if ($item =~ /^\!(.+)$/) {
                   5059:20):             push(@denies,$1);
                   5060:20):         } else {
                   5061:20):             push(@allows,$item);
                   5062:20):         }
                   5063:20):     }
                   5064:20):     my $numdenies = scalar(@denies);
                   5065:20):     my $numallows = scalar(@allows);
                   5066:20):     my $count = 0;
                   5067:20):     foreach my $pattern (@denies,@allows) {
                   5068:20):         $count ++;
                   5069:20):         my $acctype = 'allowfrom';
                   5070:20):         if ($count <= $numdenies) {
                   5071:20):             $acctype = 'denyfrom';
                   5072:20):         }
1.682     raeburn  5073:         if ($pattern =~ /\*$/) {
                   5074:             #35.8.*
                   5075:             $pattern=~s/\*//;
1.1075.2.141.  .1(raebu 5076:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5077:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5078:             #35.8.3.[34-56]
                   5079:             my $low=$2;
                   5080:             my $high=$3;
                   5081:             $pattern=$1;
                   5082:             if ($ip =~ /^\Q$pattern\E/) {
                   5083:                 my $last=(split(/\./,$ip))[3];
1.1075.2.141.  .1(raebu 5084:20):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5085:             }
                   5086:         } elsif ($pattern =~ /^\*/) {
                   5087:             #*.msu.edu
                   5088:             $pattern=~s/\*//;
                   5089:             if (!defined($name)) {
                   5090:                 use Socket;
                   5091:                 my $netaddr=inet_aton($ip);
                   5092:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5093:             }
1.1075.2.141.  .1(raebu 5094:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5095:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5096:             #127.0.0.1
1.1075.2.141.  .1(raebu 5097:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5098:         } else {
                   5099:             #some.name.com
                   5100:             if (!defined($name)) {
                   5101:                 use Socket;
                   5102:                 my $netaddr=inet_aton($ip);
                   5103:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5104:             }
1.1075.2.141.  .1(raebu 5105:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5106:20):         }
                   5107:20):         if ($allowed =~ /^(0|1)$/) { last; }
                   5108:20):     }
                   5109:20):     if ($allowed eq '') {
                   5110:20):         if ($numdenies && !$numallows) {
                   5111:20):             $allowed = 1;
                   5112:20):         } else {
                   5113:20):             $allowed = 0;
1.682     raeburn  5114:         }
                   5115:     }
                   5116:     return $allowed;
                   5117: }
                   5118: 
                   5119: ###############################################
                   5120: 
1.60      matthew  5121: =pod
                   5122: 
1.112     bowersj2 5123: =head1 Domain Template Functions
                   5124: 
                   5125: =over 4
                   5126: 
                   5127: =item * &determinedomain()
1.60      matthew  5128: 
                   5129: Inputs: $domain (usually will be undef)
                   5130: 
1.63      www      5131: Returns: Determines which domain should be used for designs
1.60      matthew  5132: 
                   5133: =cut
1.54      www      5134: 
1.60      matthew  5135: ###############################################
1.63      www      5136: sub determinedomain {
                   5137:     my $domain=shift;
1.531     albertel 5138:     if (! $domain) {
1.60      matthew  5139:         # Determine domain if we have not been given one
1.893     raeburn  5140:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5141:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5142:         if ($env{'request.role.domain'}) { 
                   5143:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5144:         }
                   5145:     }
1.63      www      5146:     return $domain;
                   5147: }
                   5148: ###############################################
1.517     raeburn  5149: 
1.518     albertel 5150: sub devalidate_domconfig_cache {
                   5151:     my ($udom)=@_;
                   5152:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5153: }
                   5154: 
                   5155: # ---------------------- Get domain configuration for a domain
                   5156: sub get_domainconf {
                   5157:     my ($udom) = @_;
                   5158:     my $cachetime=1800;
                   5159:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5160:     if (defined($cached)) { return %{$result}; }
                   5161: 
                   5162:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5163: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5164:     my (%designhash,%legacy);
1.518     albertel 5165:     if (keys(%domconfig) > 0) {
                   5166:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5167:             if (keys(%{$domconfig{'login'}})) {
                   5168:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5169:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5170:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5171:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5172:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5173:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5174:                                         if ($key eq 'loginvia') {
                   5175:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5176:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5177:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5178:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5179:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5180:                                                 } else {
                   5181:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5182:                                                 }
1.948     raeburn  5183:                                             }
1.1075.2.87  raeburn  5184:                                         } elsif ($key eq 'headtag') {
                   5185:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5186:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5187:                                             }
1.946     raeburn  5188:                                         }
1.1075.2.87  raeburn  5189:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5190:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5191:                                         }
1.946     raeburn  5192:                                     }
                   5193:                                 }
                   5194:                             }
                   5195:                         } else {
                   5196:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5197:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5198:                                     $domconfig{'login'}{$key}{$img};
                   5199:                             }
1.699     raeburn  5200:                         }
                   5201:                     } else {
                   5202:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5203:                     }
1.632     raeburn  5204:                 }
                   5205:             } else {
                   5206:                 $legacy{'login'} = 1;
1.518     albertel 5207:             }
1.632     raeburn  5208:         } else {
                   5209:             $legacy{'login'} = 1;
1.518     albertel 5210:         }
                   5211:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5212:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5213:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5214:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5215:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5216:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5217:                         }
1.518     albertel 5218:                     }
                   5219:                 }
1.632     raeburn  5220:             } else {
                   5221:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5222:             }
1.632     raeburn  5223:         } else {
                   5224:             $legacy{'rolecolors'} = 1;
1.518     albertel 5225:         }
1.948     raeburn  5226:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5227:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5228:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5229:             }
                   5230:         }
1.632     raeburn  5231:         if (keys(%legacy) > 0) {
                   5232:             my %legacyhash = &get_legacy_domconf($udom);
                   5233:             foreach my $item (keys(%legacyhash)) {
                   5234:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5235:                     if ($legacy{'login'}) { 
                   5236:                         $designhash{$item} = $legacyhash{$item};
                   5237:                     }
                   5238:                 } else {
                   5239:                     if ($legacy{'rolecolors'}) {
                   5240:                         $designhash{$item} = $legacyhash{$item};
                   5241:                     }
1.518     albertel 5242:                 }
                   5243:             }
                   5244:         }
1.632     raeburn  5245:     } else {
                   5246:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5247:     }
                   5248:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5249: 				  $cachetime);
                   5250:     return %designhash;
                   5251: }
                   5252: 
1.632     raeburn  5253: sub get_legacy_domconf {
                   5254:     my ($udom) = @_;
                   5255:     my %legacyhash;
                   5256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5257:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5258:     if (-e $designfile) {
1.1075.2.128  raeburn  5259:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5260:             while (my $line = <$fh>) {
                   5261:                 next if ($line =~ /^\#/);
                   5262:                 chomp($line);
                   5263:                 my ($key,$val)=(split(/\=/,$line));
                   5264:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5265:             }
                   5266:             close($fh);
                   5267:         }
                   5268:     }
1.1026    raeburn  5269:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5270:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5271:     }
                   5272:     return %legacyhash;
                   5273: }
                   5274: 
1.63      www      5275: =pod
                   5276: 
1.112     bowersj2 5277: =item * &domainlogo()
1.63      www      5278: 
                   5279: Inputs: $domain (usually will be undef)
                   5280: 
                   5281: Returns: A link to a domain logo, if the domain logo exists.
                   5282: If the domain logo does not exist, a description of the domain.
                   5283: 
                   5284: =cut
1.112     bowersj2 5285: 
1.63      www      5286: ###############################################
                   5287: sub domainlogo {
1.517     raeburn  5288:     my $domain = &determinedomain(shift);
1.518     albertel 5289:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5290:     # See if there is a logo
                   5291:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5292:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5293:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5294: 	    if ($imgsrc =~ m{^/res/}) {
                   5295: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5296: 		&Apache::lonnet::repcopy($local_name);
                   5297: 	    }
                   5298: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5299:         } 
                   5300:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5301:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5302:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5303:     } else {
1.60      matthew  5304:         return '';
1.59      www      5305:     }
                   5306: }
1.63      www      5307: ##############################################
                   5308: 
                   5309: =pod
                   5310: 
1.112     bowersj2 5311: =item * &designparm()
1.63      www      5312: 
                   5313: Inputs: $which parameter; $domain (usually will be undef)
                   5314: 
                   5315: Returns: value of designparamter $which
                   5316: 
                   5317: =cut
1.112     bowersj2 5318: 
1.397     albertel 5319: 
1.400     albertel 5320: ##############################################
1.397     albertel 5321: sub designparm {
                   5322:     my ($which,$domain)=@_;
                   5323:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5324:         return $env{'environment.color.'.$which};
1.96      www      5325:     }
1.63      www      5326:     $domain=&determinedomain($domain);
1.1016    raeburn  5327:     my %domdesign;
                   5328:     unless ($domain eq 'public') {
                   5329:         %domdesign = &get_domainconf($domain);
                   5330:     }
1.520     raeburn  5331:     my $output;
1.517     raeburn  5332:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5333:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5334:     } else {
1.520     raeburn  5335:         $output = $defaultdesign{$which};
                   5336:     }
                   5337:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5338:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5339:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5340:             if ($output =~ m{^/res/}) {
                   5341:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5342:                 &Apache::lonnet::repcopy($local_name);
                   5343:             }
1.520     raeburn  5344:             $output = &lonhttpdurl($output);
                   5345:         }
1.63      www      5346:     }
1.520     raeburn  5347:     return $output;
1.63      www      5348: }
1.59      www      5349: 
1.822     bisitz   5350: ##############################################
                   5351: =pod
                   5352: 
1.832     bisitz   5353: =item * &authorspace()
                   5354: 
1.1028    raeburn  5355: Inputs: $url (usually will be undef).
1.832     bisitz   5356: 
1.1075.2.40  raeburn  5357: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5358:          directory being viewed (or for which action is being taken). 
                   5359:          If $url is provided, and begins /priv/<domain>/<uname>
                   5360:          the path will be that portion of the $context argument.
                   5361:          Otherwise the path will be for the author space of the current
                   5362:          user when the current role is author, or for that of the 
                   5363:          co-author/assistant co-author space when the current role 
                   5364:          is co-author or assistant co-author.
1.832     bisitz   5365: 
                   5366: =cut
                   5367: 
                   5368: sub authorspace {
1.1028    raeburn  5369:     my ($url) = @_;
                   5370:     if ($url ne '') {
                   5371:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5372:            return $1;
                   5373:         }
                   5374:     }
1.832     bisitz   5375:     my $caname = '';
1.1024    www      5376:     my $cadom = '';
1.1028    raeburn  5377:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5378:         ($cadom,$caname) =
1.832     bisitz   5379:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5380:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5381:         $caname = $env{'user.name'};
1.1024    www      5382:         $cadom = $env{'user.domain'};
1.832     bisitz   5383:     }
1.1028    raeburn  5384:     if (($caname ne '') && ($cadom ne '')) {
                   5385:         return "/priv/$cadom/$caname/";
                   5386:     }
                   5387:     return;
1.832     bisitz   5388: }
                   5389: 
                   5390: ##############################################
                   5391: =pod
                   5392: 
1.822     bisitz   5393: =item * &head_subbox()
                   5394: 
                   5395: Inputs: $content (contains HTML code with page functions, etc.)
                   5396: 
                   5397: Returns: HTML div with $content
                   5398:          To be included in page header
                   5399: 
                   5400: =cut
                   5401: 
                   5402: sub head_subbox {
                   5403:     my ($content)=@_;
                   5404:     my $output =
1.993     raeburn  5405:         '<div class="LC_head_subbox">'
1.822     bisitz   5406:        .$content
                   5407:        .'</div>'
                   5408: }
                   5409: 
                   5410: ##############################################
                   5411: =pod
                   5412: 
                   5413: =item * &CSTR_pageheader()
                   5414: 
1.1026    raeburn  5415: Input: (optional) filename from which breadcrumb trail is built.
                   5416:        In most cases no input as needed, as $env{'request.filename'}
                   5417:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5418: 
                   5419: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5420:          To be included on Authoring Space pages
1.822     bisitz   5421: 
                   5422: =cut
                   5423: 
                   5424: sub CSTR_pageheader {
1.1026    raeburn  5425:     my ($trailfile) = @_;
                   5426:     if ($trailfile eq '') {
                   5427:         $trailfile = $env{'request.filename'};
                   5428:     }
                   5429: 
                   5430: # this is for resources; directories have customtitle, and crumbs
                   5431: # and select recent are created in lonpubdir.pm
                   5432: 
                   5433:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5434:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5435:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5436:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5437:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5438: 
                   5439:     my $parentpath = '';
                   5440:     my $lastitem = '';
                   5441:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5442:         $parentpath = $1;
                   5443:         $lastitem = $2;
                   5444:     } else {
                   5445:         $lastitem = $thisdisfn;
                   5446:     }
1.921     bisitz   5447: 
                   5448:     my $output =
1.822     bisitz   5449:          '<div>'
                   5450:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5451:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5452:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5453:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5454:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5455: 
                   5456:     if ($lastitem) {
                   5457:         $output .=
                   5458:              '<span class="LC_filename">'
                   5459:             .$lastitem
                   5460:             .'</span>';
                   5461:     }
                   5462:     $output .=
                   5463:          '<br />'
1.822     bisitz   5464:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5465:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5466:         .'</form>'
                   5467:         .&Apache::lonmenu::constspaceform()
                   5468:         .'</div>';
1.921     bisitz   5469: 
                   5470:     return $output;
1.822     bisitz   5471: }
                   5472: 
1.60      matthew  5473: ###############################################
                   5474: ###############################################
                   5475: 
                   5476: =pod
                   5477: 
1.112     bowersj2 5478: =back
                   5479: 
1.549     albertel 5480: =head1 HTML Helpers
1.112     bowersj2 5481: 
                   5482: =over 4
                   5483: 
                   5484: =item * &bodytag()
1.60      matthew  5485: 
                   5486: Returns a uniform header for LON-CAPA web pages.
                   5487: 
                   5488: Inputs: 
                   5489: 
1.112     bowersj2 5490: =over 4
                   5491: 
                   5492: =item * $title, A title to be displayed on the page.
                   5493: 
                   5494: =item * $function, the current role (can be undef).
                   5495: 
                   5496: =item * $addentries, extra parameters for the <body> tag.
                   5497: 
                   5498: =item * $bodyonly, if defined, only return the <body> tag.
                   5499: 
                   5500: =item * $domain, if defined, force a given domain.
                   5501: 
                   5502: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5503:             text interface only)
1.60      matthew  5504: 
1.814     bisitz   5505: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5506:                      navigational links
1.317     albertel 5507: 
1.338     albertel 5508: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5509: 
1.1075.2.12  raeburn  5510: =item * $no_inline_link, if true and in remote mode, don't show the
                   5511:          'Switch To Inline Menu' link
                   5512: 
1.460     albertel 5513: =item * $args, optional argument valid values are
                   5514:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5515:             use_absolute     -> for external resource or syllabus, this will
                   5516:                                 contain https://<hostname> if server uses
                   5517:                                 https (as per hosts.tab), but request is for http
                   5518:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5519: 
1.1075.2.15  raeburn  5520: =item * $advtoolsref, optional argument, ref to an array containing
                   5521:             inlineremote items to be added in "Functions" menu below
                   5522:             breadcrumbs.
                   5523: 
1.112     bowersj2 5524: =back
                   5525: 
1.60      matthew  5526: Returns: A uniform header for LON-CAPA web pages.  
                   5527: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5528: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5529: other decorations will be returned.
                   5530: 
                   5531: =cut
                   5532: 
1.54      www      5533: sub bodytag {
1.831     bisitz   5534:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5535:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5536: 
1.954     raeburn  5537:     my $public;
                   5538:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5539:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5540:         $public = 1;
                   5541:     }
1.460     albertel 5542:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5543:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5544:     my $hostname = $args->{'hostname'};
1.339     albertel 5545: 
1.183     matthew  5546:     $function = &get_users_function() if (!$function);
1.339     albertel 5547:     my $img =    &designparm($function.'.img',$domain);
                   5548:     my $font =   &designparm($function.'.font',$domain);
                   5549:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5550: 
1.803     bisitz   5551:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5552: 		   'bgcolor' => $pgbg,
1.339     albertel 5553: 		   'text'    => $font,
                   5554:                    'alink'   => &designparm($function.'.alink',$domain),
                   5555: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5556: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5557:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5558: 
1.63      www      5559:  # role and realm
1.1075.2.68  raeburn  5560:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5561:     if ($realm) {
                   5562:         $realm = '/'.$realm;
                   5563:     }
1.378     raeburn  5564:     if ($role  eq 'ca') {
1.479     albertel 5565:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5566:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5567:     } 
1.55      www      5568: # realm
1.258     albertel 5569:     if ($env{'request.course.id'}) {
1.378     raeburn  5570:         if ($env{'request.role'} !~ /^cr/) {
                   5571:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5572:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5573:             if ($env{'request.role.desc'}) {
                   5574:                 $role = $env{'request.role.desc'};
                   5575:             } else {
                   5576:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5577:             }
1.1075.2.115  raeburn  5578:         } else {
                   5579:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5580:         }
1.898     raeburn  5581:         if ($env{'request.course.sec'}) {
                   5582:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5583:         }   
1.359     albertel 5584: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5585:     } else {
                   5586:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5587:     }
1.433     albertel 5588: 
1.359     albertel 5589:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5590: 
1.438     albertel 5591:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5592: 
1.101     www      5593: # construct main body tag
1.359     albertel 5594:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5595: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5596: 
1.1075.2.38  raeburn  5597:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5598: 
                   5599:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5600:         return $bodytag;
1.1075.2.38  raeburn  5601:     }
1.359     albertel 5602: 
1.954     raeburn  5603:     if ($public) {
1.433     albertel 5604: 	undef($role);
                   5605:     }
1.359     albertel 5606:     
1.762     bisitz   5607:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5608:     #
                   5609:     # Extra info if you are the DC
                   5610:     my $dc_info = '';
                   5611:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5612:                         $env{'course.'.$env{'request.course.id'}.
                   5613:                                  '.domain'}.'/'})) {
                   5614:         my $cid = $env{'request.course.id'};
1.917     raeburn  5615:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5616:         $dc_info =~ s/\s+$//;
1.359     albertel 5617:     }
                   5618: 
1.1075.2.108  raeburn  5619:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5620: 
1.1075.2.13  raeburn  5621:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5622: 
1.1075.2.38  raeburn  5623: 
                   5624: 
1.1075.2.21  raeburn  5625:     my $funclist;
                   5626:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5627:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5628:                     Apache::lonmenu::serverform();
                   5629:         my $forbodytag;
                   5630:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5631:                                             $forcereg,$args->{'group'},
                   5632:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5633:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5634:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5635:             $funclist = $forbodytag;
                   5636:         }
                   5637:     } else {
1.903     droeschl 5638: 
                   5639:         #    if ($env{'request.state'} eq 'construct') {
                   5640:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5641:         #    }
                   5642: 
1.1075.2.38  raeburn  5643:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5644:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5645: 
1.1075.2.38  raeburn  5646:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5647: 
1.916     droeschl 5648:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5649:             if ($dc_info) {
                   5650:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5651:             }
1.1075.2.38  raeburn  5652:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5653:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5654:             return $bodytag;
                   5655:         }
1.894     droeschl 5656: 
1.927     raeburn  5657:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5658:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5659:         }
1.916     droeschl 5660: 
1.1075.2.38  raeburn  5661:         $bodytag .= $right;
1.852     droeschl 5662: 
1.917     raeburn  5663:         if ($dc_info) {
                   5664:             $dc_info = &dc_courseid_toggle($dc_info);
                   5665:         }
                   5666:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5667: 
1.1075.2.61  raeburn  5668:         #if directed to not display the secondary menu, don't.
                   5669:         if ($args->{'no_secondary_menu'}) {
                   5670:             return $bodytag;
                   5671:         }
1.903     droeschl 5672:         #don't show menus for public users
1.954     raeburn  5673:         if (!$public){
1.1075.2.52  raeburn  5674:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5675:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5676:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5677:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5678:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5679:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5680:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5681:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5682:                                                             $args->{'group'},
1.1075.2.133  raeburn  5683:                                                             $args->{'hide_buttons',
                   5684:                                                             $hostname});
1.1075.2.15  raeburn  5685:             } else {
1.1075.2.21  raeburn  5686:                 my $forbodytag;
                   5687:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5688:                                                     $forcereg,$args->{'group'},
                   5689:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5690:                                                     $advtoolsref,'',$hostname,
                   5691:                                                     \$forbodytag);
1.1075.2.21  raeburn  5692:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5693:                     $bodytag .= $forbodytag;
                   5694:                 }
1.920     raeburn  5695:             }
1.903     droeschl 5696:         }else{
                   5697:             # this is to seperate menu from content when there's no secondary
                   5698:             # menu. Especially needed for public accessible ressources.
                   5699:             $bodytag .= '<hr style="clear:both" />';
                   5700:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5701:         }
1.903     droeschl 5702: 
1.235     raeburn  5703:         return $bodytag;
1.1075.2.12  raeburn  5704:     }
                   5705: 
                   5706: #
                   5707: # Top frame rendering, Remote is up
                   5708: #
                   5709: 
                   5710:     my $imgsrc = $img;
                   5711:     if ($img =~ /^\/adm/) {
                   5712:         $imgsrc = &lonhttpdurl($img);
                   5713:     }
                   5714:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5715: 
1.1075.2.60  raeburn  5716:     my $help=($no_inline_link?''
                   5717:               :&Apache::loncommon::top_nav_help('Help'));
                   5718: 
1.1075.2.12  raeburn  5719:     # Explicit link to get inline menu
                   5720:     my $menu= ($no_inline_link?''
                   5721:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5722: 
                   5723:     if ($dc_info) {
                   5724:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5725:     }
                   5726: 
1.1075.2.38  raeburn  5727:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5728:     unless ($public) {
                   5729:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5730:                                 undef,'LC_menubuttons_link');
                   5731:     }
                   5732: 
1.1075.2.12  raeburn  5733:     unless ($env{'form.inhibitmenu'}) {
                   5734:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5735:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5736:                        <li>$help</li>
1.1075.2.12  raeburn  5737:                        <li>$menu</li>
                   5738:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5739:     }
1.1075.2.13  raeburn  5740:     if ($env{'request.state'} eq 'construct') {
                   5741:         if (!$public){
                   5742:             if ($env{'request.state'} eq 'construct') {
                   5743:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5744:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5745:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5746:                             &Apache::lonmenu::innerregister($forcereg,
                   5747:                                                             $args->{'bread_crumbs'});
                   5748:             }
                   5749:         }
                   5750:     }
1.1075.2.21  raeburn  5751:     return $bodytag."\n".$funclist;
1.182     matthew  5752: }
                   5753: 
1.917     raeburn  5754: sub dc_courseid_toggle {
                   5755:     my ($dc_info) = @_;
1.980     raeburn  5756:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5757:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5758:            &mt('(More ...)').'</a></span>'.
                   5759:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5760: }
                   5761: 
1.330     albertel 5762: sub make_attr_string {
                   5763:     my ($register,$attr_ref) = @_;
                   5764: 
                   5765:     if ($attr_ref && !ref($attr_ref)) {
                   5766: 	die("addentries Must be a hash ref ".
                   5767: 	    join(':',caller(1))." ".
                   5768: 	    join(':',caller(0))." ");
                   5769:     }
                   5770: 
                   5771:     if ($register) {
1.339     albertel 5772: 	my ($on_load,$on_unload);
                   5773: 	foreach my $key (keys(%{$attr_ref})) {
                   5774: 	    if      (lc($key) eq 'onload') {
                   5775: 		$on_load.=$attr_ref->{$key}.';';
                   5776: 		delete($attr_ref->{$key});
                   5777: 
                   5778: 	    } elsif (lc($key) eq 'onunload') {
                   5779: 		$on_unload.=$attr_ref->{$key}.';';
                   5780: 		delete($attr_ref->{$key});
                   5781: 	    }
                   5782: 	}
1.1075.2.12  raeburn  5783:         if ($env{'environment.remote'} eq 'on') {
                   5784:             $attr_ref->{'onload'}  =
                   5785:                 &Apache::lonmenu::loadevents().  $on_load;
                   5786:             $attr_ref->{'onunload'}=
                   5787:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5788:         } else {  
                   5789: 	    $attr_ref->{'onload'}  = $on_load;
                   5790: 	    $attr_ref->{'onunload'}= $on_unload;
                   5791:         }
1.330     albertel 5792:     }
1.339     albertel 5793: 
1.330     albertel 5794:     my $attr_string;
1.1075.2.56  raeburn  5795:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5796: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5797:     }
                   5798:     return $attr_string;
                   5799: }
                   5800: 
                   5801: 
1.182     matthew  5802: ###############################################
1.251     albertel 5803: ###############################################
                   5804: 
                   5805: =pod
                   5806: 
                   5807: =item * &endbodytag()
                   5808: 
                   5809: Returns a uniform footer for LON-CAPA web pages.
                   5810: 
1.635     raeburn  5811: Inputs: 1 - optional reference to an args hash
                   5812: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5813: a 'Continue' link is not displayed if the page contains an
                   5814: internal redirect in the <head></head> section,
                   5815: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5816: 
                   5817: =cut
                   5818: 
                   5819: sub endbodytag {
1.635     raeburn  5820:     my ($args) = @_;
1.1075.2.6  raeburn  5821:     my $endbodytag;
                   5822:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5823:         $endbodytag='</body>';
                   5824:     }
1.315     albertel 5825:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5826:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5827: 	    $endbodytag=
                   5828: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5829: 	        &mt('Continue').'</a>'.
                   5830: 	        $endbodytag;
                   5831:         }
1.315     albertel 5832:     }
1.251     albertel 5833:     return $endbodytag;
                   5834: }
                   5835: 
1.352     albertel 5836: =pod
                   5837: 
                   5838: =item * &standard_css()
                   5839: 
                   5840: Returns a style sheet
                   5841: 
                   5842: Inputs: (all optional)
                   5843:             domain         -> force to color decorate a page for a specific
                   5844:                                domain
                   5845:             function       -> force usage of a specific rolish color scheme
                   5846:             bgcolor        -> override the default page bgcolor
                   5847: 
                   5848: =cut
                   5849: 
1.343     albertel 5850: sub standard_css {
1.345     albertel 5851:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5852:     $function  = &get_users_function() if (!$function);
                   5853:     my $img    = &designparm($function.'.img',   $domain);
                   5854:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5855:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5856:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5857: #second colour for later usage
1.345     albertel 5858:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5859:     my $pgbg_or_bgcolor =
                   5860: 	         $bgcolor ||
1.352     albertel 5861: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5862:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5863:     my $alink  = &designparm($function.'.alink', $domain);
                   5864:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5865:     my $link   = &designparm($function.'.link',  $domain);
                   5866: 
1.602     albertel 5867:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5868:     my $mono                 = 'monospace';
1.850     bisitz   5869:     my $data_table_head      = $sidebg;
                   5870:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5871:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5872:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5873:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5874:     my $mail_new             = '#FFBB77';
                   5875:     my $mail_new_hover       = '#DD9955';
                   5876:     my $mail_read            = '#BBBB77';
                   5877:     my $mail_read_hover      = '#999944';
                   5878:     my $mail_replied         = '#AAAA88';
                   5879:     my $mail_replied_hover   = '#888855';
                   5880:     my $mail_other           = '#99BBBB';
                   5881:     my $mail_other_hover     = '#669999';
1.391     albertel 5882:     my $table_header         = '#DDDDDD';
1.489     raeburn  5883:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5884:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5885:     my $button_hover         = '#BF2317';
1.392     albertel 5886: 
1.608     albertel 5887:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5888:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5889:                                              : '0 3px 0 4px';
1.448     albertel 5890: 
1.523     albertel 5891: 
1.343     albertel 5892:     return <<END;
1.947     droeschl 5893: 
                   5894: /* needed for iframe to allow 100% height in FF */
                   5895: body, html { 
                   5896:     margin: 0;
                   5897:     padding: 0 0.5%;
                   5898:     height: 99%; /* to avoid scrollbars */
                   5899: }
                   5900: 
1.795     www      5901: body {
1.911     bisitz   5902:   font-family: $sans;
                   5903:   line-height:130%;
                   5904:   font-size:0.83em;
                   5905:   color:$font;
1.795     www      5906: }
                   5907: 
1.959     onken    5908: a:focus,
                   5909: a:focus img {
1.795     www      5910:   color: red;
                   5911: }
1.698     harmsja  5912: 
1.911     bisitz   5913: form, .inline {
                   5914:   display: inline;
1.795     www      5915: }
1.721     harmsja  5916: 
1.795     www      5917: .LC_right {
1.911     bisitz   5918:   text-align:right;
1.795     www      5919: }
                   5920: 
                   5921: .LC_middle {
1.911     bisitz   5922:   vertical-align:middle;
1.795     www      5923: }
1.721     harmsja  5924: 
1.1075.2.38  raeburn  5925: .LC_floatleft {
                   5926:   float: left;
                   5927: }
                   5928: 
                   5929: .LC_floatright {
                   5930:   float: right;
                   5931: }
                   5932: 
1.911     bisitz   5933: .LC_400Box {
                   5934:   width:400px;
                   5935: }
1.721     harmsja  5936: 
1.947     droeschl 5937: .LC_iframecontainer {
                   5938:     width: 98%;
                   5939:     margin: 0;
                   5940:     position: fixed;
                   5941:     top: 8.5em;
                   5942:     bottom: 0;
                   5943: }
                   5944: 
                   5945: .LC_iframecontainer iframe{
                   5946:     border: none;
                   5947:     width: 100%;
                   5948:     height: 100%;
                   5949: }
                   5950: 
1.778     bisitz   5951: .LC_filename {
                   5952:   font-family: $mono;
                   5953:   white-space:pre;
1.921     bisitz   5954:   font-size: 120%;
1.778     bisitz   5955: }
                   5956: 
                   5957: .LC_fileicon {
                   5958:   border: none;
                   5959:   height: 1.3em;
                   5960:   vertical-align: text-bottom;
                   5961:   margin-right: 0.3em;
                   5962:   text-decoration:none;
                   5963: }
                   5964: 
1.1008    www      5965: .LC_setting {
                   5966:   text-decoration:underline;
                   5967: }
                   5968: 
1.350     albertel 5969: .LC_error {
                   5970:   color: red;
                   5971: }
1.795     www      5972: 
1.1075.2.15  raeburn  5973: .LC_warning {
                   5974:   color: darkorange;
                   5975: }
                   5976: 
1.457     albertel 5977: .LC_diff_removed {
1.733     bisitz   5978:   color: red;
1.394     albertel 5979: }
1.532     albertel 5980: 
                   5981: .LC_info,
1.457     albertel 5982: .LC_success,
                   5983: .LC_diff_added {
1.350     albertel 5984:   color: green;
                   5985: }
1.795     www      5986: 
1.802     bisitz   5987: div.LC_confirm_box {
                   5988:   background-color: #FAFAFA;
                   5989:   border: 1px solid $lg_border_color;
                   5990:   margin-right: 0;
                   5991:   padding: 5px;
                   5992: }
                   5993: 
                   5994: div.LC_confirm_box .LC_error img,
                   5995: div.LC_confirm_box .LC_success img {
                   5996:   vertical-align: middle;
                   5997: }
                   5998: 
1.1075.2.108  raeburn  5999: .LC_maxwidth {
                   6000:   max-width: 100%;
                   6001:   height: auto;
                   6002: }
                   6003: 
                   6004: .LC_textsize_mobile {
                   6005:   \@media only screen and (max-device-width: 480px) {
                   6006:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6007:   }
                   6008: }
                   6009: 
1.440     albertel 6010: .LC_icon {
1.771     droeschl 6011:   border: none;
1.790     droeschl 6012:   vertical-align: middle;
1.771     droeschl 6013: }
                   6014: 
1.543     albertel 6015: .LC_docs_spacer {
                   6016:   width: 25px;
                   6017:   height: 1px;
1.771     droeschl 6018:   border: none;
1.543     albertel 6019: }
1.346     albertel 6020: 
1.532     albertel 6021: .LC_internal_info {
1.735     bisitz   6022:   color: #999999;
1.532     albertel 6023: }
                   6024: 
1.794     www      6025: .LC_discussion {
1.1050    www      6026:   background: $data_table_dark;
1.911     bisitz   6027:   border: 1px solid black;
                   6028:   margin: 2px;
1.794     www      6029: }
                   6030: 
                   6031: .LC_disc_action_left {
1.1050    www      6032:   background: $sidebg;
1.911     bisitz   6033:   text-align: left;
1.1050    www      6034:   padding: 4px;
                   6035:   margin: 2px;
1.794     www      6036: }
                   6037: 
                   6038: .LC_disc_action_right {
1.1050    www      6039:   background: $sidebg;
1.911     bisitz   6040:   text-align: right;
1.1050    www      6041:   padding: 4px;
                   6042:   margin: 2px;
1.794     www      6043: }
                   6044: 
                   6045: .LC_disc_new_item {
1.911     bisitz   6046:   background: white;
                   6047:   border: 2px solid red;
1.1050    www      6048:   margin: 4px;
                   6049:   padding: 4px;
1.794     www      6050: }
                   6051: 
                   6052: .LC_disc_old_item {
1.911     bisitz   6053:   background: white;
1.1050    www      6054:   margin: 4px;
                   6055:   padding: 4px;
1.794     www      6056: }
                   6057: 
1.458     albertel 6058: table.LC_pastsubmission {
                   6059:   border: 1px solid black;
                   6060:   margin: 2px;
                   6061: }
                   6062: 
1.924     bisitz   6063: table#LC_menubuttons {
1.345     albertel 6064:   width: 100%;
                   6065:   background: $pgbg;
1.392     albertel 6066:   border: 2px;
1.402     albertel 6067:   border-collapse: separate;
1.803     bisitz   6068:   padding: 0;
1.345     albertel 6069: }
1.392     albertel 6070: 
1.801     tempelho 6071: table#LC_title_bar a {
                   6072:   color: $fontmenu;
                   6073: }
1.836     bisitz   6074: 
1.807     droeschl 6075: table#LC_title_bar {
1.819     tempelho 6076:   clear: both;
1.836     bisitz   6077:   display: none;
1.807     droeschl 6078: }
                   6079: 
1.795     www      6080: table#LC_title_bar,
1.933     droeschl 6081: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6082: table#LC_title_bar.LC_with_remote {
1.359     albertel 6083:   width: 100%;
1.392     albertel 6084:   border-color: $pgbg;
                   6085:   border-style: solid;
                   6086:   border-width: $border;
1.379     albertel 6087:   background: $pgbg;
1.801     tempelho 6088:   color: $fontmenu;
1.392     albertel 6089:   border-collapse: collapse;
1.803     bisitz   6090:   padding: 0;
1.819     tempelho 6091:   margin: 0;
1.359     albertel 6092: }
1.795     www      6093: 
1.933     droeschl 6094: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6095:     margin: 0;
                   6096:     padding: 0;
1.933     droeschl 6097:     position: relative;
                   6098:     list-style: none;
1.913     droeschl 6099: }
1.933     droeschl 6100: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6101:     display: inline;
                   6102: }
1.933     droeschl 6103: 
                   6104: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6105:     padding: 0;
1.933     droeschl 6106:     margin: 0;
                   6107:     float: left;
1.913     droeschl 6108: }
1.933     droeschl 6109: .LC_breadcrumb_tools_tools {
                   6110:     padding: 0;
                   6111:     margin: 0;
1.913     droeschl 6112:     float: right;
                   6113: }
                   6114: 
1.359     albertel 6115: table#LC_title_bar td {
                   6116:   background: $tabbg;
                   6117: }
1.795     www      6118: 
1.911     bisitz   6119: table#LC_menubuttons img {
1.803     bisitz   6120:   border: none;
1.346     albertel 6121: }
1.795     www      6122: 
1.842     droeschl 6123: .LC_breadcrumbs_component {
1.911     bisitz   6124:   float: right;
                   6125:   margin: 0 1em;
1.357     albertel 6126: }
1.842     droeschl 6127: .LC_breadcrumbs_component img {
1.911     bisitz   6128:   vertical-align: middle;
1.777     tempelho 6129: }
1.795     www      6130: 
1.1075.2.108  raeburn  6131: .LC_breadcrumbs_hoverable {
                   6132:   background: $sidebg;
                   6133: }
                   6134: 
1.383     albertel 6135: td.LC_table_cell_checkbox {
                   6136:   text-align: center;
                   6137: }
1.795     www      6138: 
                   6139: .LC_fontsize_small {
1.911     bisitz   6140:   font-size: 70%;
1.705     tempelho 6141: }
                   6142: 
1.844     bisitz   6143: #LC_breadcrumbs {
1.911     bisitz   6144:   clear:both;
                   6145:   background: $sidebg;
                   6146:   border-bottom: 1px solid $lg_border_color;
                   6147:   line-height: 2.5em;
1.933     droeschl 6148:   overflow: hidden;
1.911     bisitz   6149:   margin: 0;
                   6150:   padding: 0;
1.995     raeburn  6151:   text-align: left;
1.819     tempelho 6152: }
1.862     bisitz   6153: 
1.1075.2.16  raeburn  6154: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6155:   clear:both;
                   6156:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6157:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6158:   margin: 0 0 10px 0;
1.966     bisitz   6159:   padding: 3px;
1.995     raeburn  6160:   text-align: left;
1.822     bisitz   6161: }
                   6162: 
1.795     www      6163: .LC_fontsize_medium {
1.911     bisitz   6164:   font-size: 85%;
1.705     tempelho 6165: }
                   6166: 
1.795     www      6167: .LC_fontsize_large {
1.911     bisitz   6168:   font-size: 120%;
1.705     tempelho 6169: }
                   6170: 
1.346     albertel 6171: .LC_menubuttons_inline_text {
                   6172:   color: $font;
1.698     harmsja  6173:   font-size: 90%;
1.701     harmsja  6174:   padding-left:3px;
1.346     albertel 6175: }
                   6176: 
1.934     droeschl 6177: .LC_menubuttons_inline_text img{
                   6178:   vertical-align: middle;
                   6179: }
                   6180: 
1.1051    www      6181: li.LC_menubuttons_inline_text img {
1.951     onken    6182:   cursor:pointer;
1.1002    droeschl 6183:   text-decoration: none;
1.951     onken    6184: }
                   6185: 
1.526     www      6186: .LC_menubuttons_link {
                   6187:   text-decoration: none;
                   6188: }
1.795     www      6189: 
1.522     albertel 6190: .LC_menubuttons_category {
1.521     www      6191:   color: $font;
1.526     www      6192:   background: $pgbg;
1.521     www      6193:   font-size: larger;
                   6194:   font-weight: bold;
                   6195: }
                   6196: 
1.346     albertel 6197: td.LC_menubuttons_text {
1.911     bisitz   6198:   color: $font;
1.346     albertel 6199: }
1.706     harmsja  6200: 
1.346     albertel 6201: .LC_current_location {
                   6202:   background: $tabbg;
                   6203: }
1.795     www      6204: 
1.1075.2.134  raeburn  6205: td.LC_zero_height {
                   6206:   line-height: 0;
                   6207:   cellpadding: 0;
                   6208: }
                   6209: 
1.938     bisitz   6210: table.LC_data_table {
1.347     albertel 6211:   border: 1px solid #000000;
1.402     albertel 6212:   border-collapse: separate;
1.426     albertel 6213:   border-spacing: 1px;
1.610     albertel 6214:   background: $pgbg;
1.347     albertel 6215: }
1.795     www      6216: 
1.422     albertel 6217: .LC_data_table_dense {
                   6218:   font-size: small;
                   6219: }
1.795     www      6220: 
1.507     raeburn  6221: table.LC_nested_outer {
                   6222:   border: 1px solid #000000;
1.589     raeburn  6223:   border-collapse: collapse;
1.803     bisitz   6224:   border-spacing: 0;
1.507     raeburn  6225:   width: 100%;
                   6226: }
1.795     www      6227: 
1.879     raeburn  6228: table.LC_innerpickbox,
1.507     raeburn  6229: table.LC_nested {
1.803     bisitz   6230:   border: none;
1.589     raeburn  6231:   border-collapse: collapse;
1.803     bisitz   6232:   border-spacing: 0;
1.507     raeburn  6233:   width: 100%;
                   6234: }
1.795     www      6235: 
1.911     bisitz   6236: table.LC_data_table tr th,
                   6237: table.LC_calendar tr th,
1.879     raeburn  6238: table.LC_prior_tries tr th,
                   6239: table.LC_innerpickbox tr th {
1.349     albertel 6240:   font-weight: bold;
                   6241:   background-color: $data_table_head;
1.801     tempelho 6242:   color:$fontmenu;
1.701     harmsja  6243:   font-size:90%;
1.347     albertel 6244: }
1.795     www      6245: 
1.879     raeburn  6246: table.LC_innerpickbox tr th,
                   6247: table.LC_innerpickbox tr td {
                   6248:   vertical-align: top;
                   6249: }
                   6250: 
1.711     raeburn  6251: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6252:   background-color: #CCCCCC;
1.711     raeburn  6253:   font-weight: bold;
                   6254:   text-align: left;
                   6255: }
1.795     www      6256: 
1.912     bisitz   6257: table.LC_data_table tr.LC_odd_row > td {
                   6258:   background-color: $data_table_light;
                   6259:   padding: 2px;
                   6260:   vertical-align: top;
                   6261: }
                   6262: 
1.809     bisitz   6263: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6264:   background-color: $data_table_light;
1.912     bisitz   6265:   vertical-align: top;
                   6266: }
                   6267: 
                   6268: table.LC_data_table tr.LC_even_row > td {
                   6269:   background-color: $data_table_dark;
1.425     albertel 6270:   padding: 2px;
1.900     bisitz   6271:   vertical-align: top;
1.347     albertel 6272: }
1.795     www      6273: 
1.809     bisitz   6274: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6275:   background-color: $data_table_dark;
1.900     bisitz   6276:   vertical-align: top;
1.347     albertel 6277: }
1.795     www      6278: 
1.425     albertel 6279: table.LC_data_table tr.LC_data_table_highlight td {
                   6280:   background-color: $data_table_darker;
                   6281: }
1.795     www      6282: 
1.639     raeburn  6283: table.LC_data_table tr td.LC_leftcol_header {
                   6284:   background-color: $data_table_head;
                   6285:   font-weight: bold;
                   6286: }
1.795     www      6287: 
1.451     albertel 6288: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6289: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6290:   font-weight: bold;
                   6291:   font-style: italic;
                   6292:   text-align: center;
                   6293:   padding: 8px;
1.347     albertel 6294: }
1.795     www      6295: 
1.1075.2.30  raeburn  6296: table.LC_data_table tr.LC_empty_row td,
                   6297: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6298:   background-color: $sidebg;
                   6299: }
                   6300: 
                   6301: table.LC_nested tr.LC_empty_row td {
                   6302:   background-color: #FFFFFF;
                   6303: }
                   6304: 
1.890     droeschl 6305: table.LC_caption {
                   6306: }
                   6307: 
1.507     raeburn  6308: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6309:   padding: 4ex
                   6310: }
1.795     www      6311: 
1.507     raeburn  6312: table.LC_nested_outer tr th {
                   6313:   font-weight: bold;
1.801     tempelho 6314:   color:$fontmenu;
1.507     raeburn  6315:   background-color: $data_table_head;
1.701     harmsja  6316:   font-size: small;
1.507     raeburn  6317:   border-bottom: 1px solid #000000;
                   6318: }
1.795     www      6319: 
1.507     raeburn  6320: table.LC_nested_outer tr td.LC_subheader {
                   6321:   background-color: $data_table_head;
                   6322:   font-weight: bold;
                   6323:   font-size: small;
                   6324:   border-bottom: 1px solid #000000;
                   6325:   text-align: right;
1.451     albertel 6326: }
1.795     www      6327: 
1.507     raeburn  6328: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6329:   background-color: #CCCCCC;
1.451     albertel 6330:   font-weight: bold;
                   6331:   font-size: small;
1.507     raeburn  6332:   text-align: center;
                   6333: }
1.795     www      6334: 
1.589     raeburn  6335: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6336: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6337:   text-align: left;
1.451     albertel 6338: }
1.795     www      6339: 
1.507     raeburn  6340: table.LC_nested td {
1.735     bisitz   6341:   background-color: #FFFFFF;
1.451     albertel 6342:   font-size: small;
1.507     raeburn  6343: }
1.795     www      6344: 
1.507     raeburn  6345: table.LC_nested_outer tr th.LC_right_item,
                   6346: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6347: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6348: table.LC_nested tr td.LC_right_item {
1.451     albertel 6349:   text-align: right;
                   6350: }
                   6351: 
1.507     raeburn  6352: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6353:   background-color: #EEEEEE;
1.451     albertel 6354: }
                   6355: 
1.473     raeburn  6356: table.LC_createuser {
                   6357: }
                   6358: 
                   6359: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6360:   font-size: small;
1.473     raeburn  6361: }
                   6362: 
                   6363: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6364:   background-color: #CCCCCC;
1.473     raeburn  6365:   font-weight: bold;
                   6366:   text-align: center;
                   6367: }
                   6368: 
1.349     albertel 6369: table.LC_calendar {
                   6370:   border: 1px solid #000000;
                   6371:   border-collapse: collapse;
1.917     raeburn  6372:   width: 98%;
1.349     albertel 6373: }
1.795     www      6374: 
1.349     albertel 6375: table.LC_calendar_pickdate {
                   6376:   font-size: xx-small;
                   6377: }
1.795     www      6378: 
1.349     albertel 6379: table.LC_calendar tr td {
                   6380:   border: 1px solid #000000;
                   6381:   vertical-align: top;
1.917     raeburn  6382:   width: 14%;
1.349     albertel 6383: }
1.795     www      6384: 
1.349     albertel 6385: table.LC_calendar tr td.LC_calendar_day_empty {
                   6386:   background-color: $data_table_dark;
                   6387: }
1.795     www      6388: 
1.779     bisitz   6389: table.LC_calendar tr td.LC_calendar_day_current {
                   6390:   background-color: $data_table_highlight;
1.777     tempelho 6391: }
1.795     www      6392: 
1.938     bisitz   6393: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6394:   background-color: $mail_new;
                   6395: }
1.795     www      6396: 
1.938     bisitz   6397: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6398:   background-color: $mail_new_hover;
                   6399: }
1.795     www      6400: 
1.938     bisitz   6401: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6402:   background-color: $mail_read;
                   6403: }
1.795     www      6404: 
1.938     bisitz   6405: /*
                   6406: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6407:   background-color: $mail_read_hover;
                   6408: }
1.938     bisitz   6409: */
1.795     www      6410: 
1.938     bisitz   6411: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6412:   background-color: $mail_replied;
                   6413: }
1.795     www      6414: 
1.938     bisitz   6415: /*
                   6416: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6417:   background-color: $mail_replied_hover;
                   6418: }
1.938     bisitz   6419: */
1.795     www      6420: 
1.938     bisitz   6421: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6422:   background-color: $mail_other;
                   6423: }
1.795     www      6424: 
1.938     bisitz   6425: /*
                   6426: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6427:   background-color: $mail_other_hover;
                   6428: }
1.938     bisitz   6429: */
1.494     raeburn  6430: 
1.777     tempelho 6431: table.LC_data_table tr > td.LC_browser_file,
                   6432: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6433:   background: #AAEE77;
1.389     albertel 6434: }
1.795     www      6435: 
1.777     tempelho 6436: table.LC_data_table tr > td.LC_browser_file_locked,
                   6437: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6438:   background: #FFAA99;
1.387     albertel 6439: }
1.795     www      6440: 
1.777     tempelho 6441: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6442:   background: #888888;
1.779     bisitz   6443: }
1.795     www      6444: 
1.777     tempelho 6445: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6446: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6447:   background: #F8F866;
1.777     tempelho 6448: }
1.795     www      6449: 
1.696     bisitz   6450: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6451:   background: #E0E8FF;
1.387     albertel 6452: }
1.696     bisitz   6453: 
1.707     bisitz   6454: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6455:   /* background: #77FF77; */
1.707     bisitz   6456: }
1.795     www      6457: 
1.707     bisitz   6458: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6459:   border-right: 8px solid #FFFF77;
1.707     bisitz   6460: }
1.795     www      6461: 
1.707     bisitz   6462: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6463:   border-right: 8px solid #FFAA77;
1.707     bisitz   6464: }
1.795     www      6465: 
1.707     bisitz   6466: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6467:   border-right: 8px solid #FF7777;
1.707     bisitz   6468: }
1.795     www      6469: 
1.707     bisitz   6470: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6471:   border-right: 8px solid #AAFF77;
1.707     bisitz   6472: }
1.795     www      6473: 
1.707     bisitz   6474: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6475:   border-right: 8px solid #11CC55;
1.707     bisitz   6476: }
                   6477: 
1.388     albertel 6478: span.LC_current_location {
1.701     harmsja  6479:   font-size:larger;
1.388     albertel 6480:   background: $pgbg;
                   6481: }
1.387     albertel 6482: 
1.1029    www      6483: span.LC_current_nav_location {
                   6484:   font-weight:bold;
                   6485:   background: $sidebg;
                   6486: }
                   6487: 
1.395     albertel 6488: span.LC_parm_menu_item {
                   6489:   font-size: larger;
                   6490: }
1.795     www      6491: 
1.395     albertel 6492: span.LC_parm_scope_all {
                   6493:   color: red;
                   6494: }
1.795     www      6495: 
1.395     albertel 6496: span.LC_parm_scope_folder {
                   6497:   color: green;
                   6498: }
1.795     www      6499: 
1.395     albertel 6500: span.LC_parm_scope_resource {
                   6501:   color: orange;
                   6502: }
1.795     www      6503: 
1.395     albertel 6504: span.LC_parm_part {
                   6505:   color: blue;
                   6506: }
1.795     www      6507: 
1.911     bisitz   6508: span.LC_parm_folder,
                   6509: span.LC_parm_symb {
1.395     albertel 6510:   font-size: x-small;
                   6511:   font-family: $mono;
                   6512:   color: #AAAAAA;
                   6513: }
                   6514: 
1.977     bisitz   6515: ul.LC_parm_parmlist li {
                   6516:   display: inline-block;
                   6517:   padding: 0.3em 0.8em;
                   6518:   vertical-align: top;
                   6519:   width: 150px;
                   6520:   border-top:1px solid $lg_border_color;
                   6521: }
                   6522: 
1.795     www      6523: td.LC_parm_overview_level_menu,
                   6524: td.LC_parm_overview_map_menu,
                   6525: td.LC_parm_overview_parm_selectors,
                   6526: td.LC_parm_overview_restrictions  {
1.396     albertel 6527:   border: 1px solid black;
                   6528:   border-collapse: collapse;
                   6529: }
1.795     www      6530: 
1.396     albertel 6531: table.LC_parm_overview_restrictions td {
                   6532:   border-width: 1px 4px 1px 4px;
                   6533:   border-style: solid;
                   6534:   border-color: $pgbg;
                   6535:   text-align: center;
                   6536: }
1.795     www      6537: 
1.396     albertel 6538: table.LC_parm_overview_restrictions th {
                   6539:   background: $tabbg;
                   6540:   border-width: 1px 4px 1px 4px;
                   6541:   border-style: solid;
                   6542:   border-color: $pgbg;
                   6543: }
1.795     www      6544: 
1.398     albertel 6545: table#LC_helpmenu {
1.803     bisitz   6546:   border: none;
1.398     albertel 6547:   height: 55px;
1.803     bisitz   6548:   border-spacing: 0;
1.398     albertel 6549: }
                   6550: 
                   6551: table#LC_helpmenu fieldset legend {
                   6552:   font-size: larger;
                   6553: }
1.795     www      6554: 
1.397     albertel 6555: table#LC_helpmenu_links {
                   6556:   width: 100%;
                   6557:   border: 1px solid black;
                   6558:   background: $pgbg;
1.803     bisitz   6559:   padding: 0;
1.397     albertel 6560:   border-spacing: 1px;
                   6561: }
1.795     www      6562: 
1.397     albertel 6563: table#LC_helpmenu_links tr td {
                   6564:   padding: 1px;
                   6565:   background: $tabbg;
1.399     albertel 6566:   text-align: center;
                   6567:   font-weight: bold;
1.397     albertel 6568: }
1.396     albertel 6569: 
1.795     www      6570: table#LC_helpmenu_links a:link,
                   6571: table#LC_helpmenu_links a:visited,
1.397     albertel 6572: table#LC_helpmenu_links a:active {
                   6573:   text-decoration: none;
                   6574:   color: $font;
                   6575: }
1.795     www      6576: 
1.397     albertel 6577: table#LC_helpmenu_links a:hover {
                   6578:   text-decoration: underline;
                   6579:   color: $vlink;
                   6580: }
1.396     albertel 6581: 
1.417     albertel 6582: .LC_chrt_popup_exists {
                   6583:   border: 1px solid #339933;
                   6584:   margin: -1px;
                   6585: }
1.795     www      6586: 
1.417     albertel 6587: .LC_chrt_popup_up {
                   6588:   border: 1px solid yellow;
                   6589:   margin: -1px;
                   6590: }
1.795     www      6591: 
1.417     albertel 6592: .LC_chrt_popup {
                   6593:   border: 1px solid #8888FF;
                   6594:   background: #CCCCFF;
                   6595: }
1.795     www      6596: 
1.421     albertel 6597: table.LC_pick_box {
                   6598:   border-collapse: separate;
                   6599:   background: white;
                   6600:   border: 1px solid black;
                   6601:   border-spacing: 1px;
                   6602: }
1.795     www      6603: 
1.421     albertel 6604: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6605:   background: $sidebg;
1.421     albertel 6606:   font-weight: bold;
1.900     bisitz   6607:   text-align: left;
1.740     bisitz   6608:   vertical-align: top;
1.421     albertel 6609:   width: 184px;
                   6610:   padding: 8px;
                   6611: }
1.795     www      6612: 
1.579     raeburn  6613: table.LC_pick_box td.LC_pick_box_value {
                   6614:   text-align: left;
                   6615:   padding: 8px;
                   6616: }
1.795     www      6617: 
1.579     raeburn  6618: table.LC_pick_box td.LC_pick_box_select {
                   6619:   text-align: left;
                   6620:   padding: 8px;
                   6621: }
1.795     www      6622: 
1.424     albertel 6623: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6624:   padding: 0;
1.421     albertel 6625:   height: 1px;
                   6626:   background: black;
                   6627: }
1.795     www      6628: 
1.421     albertel 6629: table.LC_pick_box td.LC_pick_box_submit {
                   6630:   text-align: right;
                   6631: }
1.795     www      6632: 
1.579     raeburn  6633: table.LC_pick_box td.LC_evenrow_value {
                   6634:   text-align: left;
                   6635:   padding: 8px;
                   6636:   background-color: $data_table_light;
                   6637: }
1.795     www      6638: 
1.579     raeburn  6639: table.LC_pick_box td.LC_oddrow_value {
                   6640:   text-align: left;
                   6641:   padding: 8px;
                   6642:   background-color: $data_table_light;
                   6643: }
1.795     www      6644: 
1.579     raeburn  6645: span.LC_helpform_receipt_cat {
                   6646:   font-weight: bold;
                   6647: }
1.795     www      6648: 
1.424     albertel 6649: table.LC_group_priv_box {
                   6650:   background: white;
                   6651:   border: 1px solid black;
                   6652:   border-spacing: 1px;
                   6653: }
1.795     www      6654: 
1.424     albertel 6655: table.LC_group_priv_box td.LC_pick_box_title {
                   6656:   background: $tabbg;
                   6657:   font-weight: bold;
                   6658:   text-align: right;
                   6659:   width: 184px;
                   6660: }
1.795     www      6661: 
1.424     albertel 6662: table.LC_group_priv_box td.LC_groups_fixed {
                   6663:   background: $data_table_light;
                   6664:   text-align: center;
                   6665: }
1.795     www      6666: 
1.424     albertel 6667: table.LC_group_priv_box td.LC_groups_optional {
                   6668:   background: $data_table_dark;
                   6669:   text-align: center;
                   6670: }
1.795     www      6671: 
1.424     albertel 6672: table.LC_group_priv_box td.LC_groups_functionality {
                   6673:   background: $data_table_darker;
                   6674:   text-align: center;
                   6675:   font-weight: bold;
                   6676: }
1.795     www      6677: 
1.424     albertel 6678: table.LC_group_priv td {
                   6679:   text-align: left;
1.803     bisitz   6680:   padding: 0;
1.424     albertel 6681: }
                   6682: 
                   6683: .LC_navbuttons {
                   6684:   margin: 2ex 0ex 2ex 0ex;
                   6685: }
1.795     www      6686: 
1.423     albertel 6687: .LC_topic_bar {
                   6688:   font-weight: bold;
                   6689:   background: $tabbg;
1.918     wenzelju 6690:   margin: 1em 0em 1em 2em;
1.805     bisitz   6691:   padding: 3px;
1.918     wenzelju 6692:   font-size: 1.2em;
1.423     albertel 6693: }
1.795     www      6694: 
1.423     albertel 6695: .LC_topic_bar span {
1.918     wenzelju 6696:   left: 0.5em;
                   6697:   position: absolute;
1.423     albertel 6698:   vertical-align: middle;
1.918     wenzelju 6699:   font-size: 1.2em;
1.423     albertel 6700: }
1.795     www      6701: 
1.423     albertel 6702: table.LC_course_group_status {
                   6703:   margin: 20px;
                   6704: }
1.795     www      6705: 
1.423     albertel 6706: table.LC_status_selector td {
                   6707:   vertical-align: top;
                   6708:   text-align: center;
1.424     albertel 6709:   padding: 4px;
                   6710: }
1.795     www      6711: 
1.599     albertel 6712: div.LC_feedback_link {
1.616     albertel 6713:   clear: both;
1.829     kalberla 6714:   background: $sidebg;
1.779     bisitz   6715:   width: 100%;
1.829     kalberla 6716:   padding-bottom: 10px;
                   6717:   border: 1px $tabbg solid;
1.833     kalberla 6718:   height: 22px;
                   6719:   line-height: 22px;
                   6720:   padding-top: 5px;
                   6721: }
                   6722: 
                   6723: div.LC_feedback_link img {
                   6724:   height: 22px;
1.867     kalberla 6725:   vertical-align:middle;
1.829     kalberla 6726: }
                   6727: 
1.911     bisitz   6728: div.LC_feedback_link a {
1.829     kalberla 6729:   text-decoration: none;
1.489     raeburn  6730: }
1.795     www      6731: 
1.867     kalberla 6732: div.LC_comblock {
1.911     bisitz   6733:   display:inline;
1.867     kalberla 6734:   color:$font;
                   6735:   font-size:90%;
                   6736: }
                   6737: 
                   6738: div.LC_feedback_link div.LC_comblock {
                   6739:   padding-left:5px;
                   6740: }
                   6741: 
                   6742: div.LC_feedback_link div.LC_comblock a {
                   6743:   color:$font;
                   6744: }
                   6745: 
1.489     raeburn  6746: span.LC_feedback_link {
1.858     bisitz   6747:   /* background: $feedback_link_bg; */
1.599     albertel 6748:   font-size: larger;
                   6749: }
1.795     www      6750: 
1.599     albertel 6751: span.LC_message_link {
1.858     bisitz   6752:   /* background: $feedback_link_bg; */
1.599     albertel 6753:   font-size: larger;
                   6754:   position: absolute;
                   6755:   right: 1em;
1.489     raeburn  6756: }
1.421     albertel 6757: 
1.515     albertel 6758: table.LC_prior_tries {
1.524     albertel 6759:   border: 1px solid #000000;
                   6760:   border-collapse: separate;
                   6761:   border-spacing: 1px;
1.515     albertel 6762: }
1.523     albertel 6763: 
1.515     albertel 6764: table.LC_prior_tries td {
1.524     albertel 6765:   padding: 2px;
1.515     albertel 6766: }
1.523     albertel 6767: 
                   6768: .LC_answer_correct {
1.795     www      6769:   background: lightgreen;
                   6770:   color: darkgreen;
                   6771:   padding: 6px;
1.523     albertel 6772: }
1.795     www      6773: 
1.523     albertel 6774: .LC_answer_charged_try {
1.797     www      6775:   background: #FFAAAA;
1.795     www      6776:   color: darkred;
                   6777:   padding: 6px;
1.523     albertel 6778: }
1.795     www      6779: 
1.779     bisitz   6780: .LC_answer_not_charged_try,
1.523     albertel 6781: .LC_answer_no_grade,
                   6782: .LC_answer_late {
1.795     www      6783:   background: lightyellow;
1.523     albertel 6784:   color: black;
1.795     www      6785:   padding: 6px;
1.523     albertel 6786: }
1.795     www      6787: 
1.523     albertel 6788: .LC_answer_previous {
1.795     www      6789:   background: lightblue;
                   6790:   color: darkblue;
                   6791:   padding: 6px;
1.523     albertel 6792: }
1.795     www      6793: 
1.779     bisitz   6794: .LC_answer_no_message {
1.777     tempelho 6795:   background: #FFFFFF;
                   6796:   color: black;
1.795     www      6797:   padding: 6px;
1.779     bisitz   6798: }
1.795     www      6799: 
1.1075.2.140  raeburn  6800: .LC_answer_unknown,
                   6801: .LC_answer_warning {
1.779     bisitz   6802:   background: orange;
                   6803:   color: black;
1.795     www      6804:   padding: 6px;
1.777     tempelho 6805: }
1.795     www      6806: 
1.529     albertel 6807: span.LC_prior_numerical,
                   6808: span.LC_prior_string,
                   6809: span.LC_prior_custom,
                   6810: span.LC_prior_reaction,
                   6811: span.LC_prior_math {
1.925     bisitz   6812:   font-family: $mono;
1.523     albertel 6813:   white-space: pre;
                   6814: }
                   6815: 
1.525     albertel 6816: span.LC_prior_string {
1.925     bisitz   6817:   font-family: $mono;
1.525     albertel 6818:   white-space: pre;
                   6819: }
                   6820: 
1.523     albertel 6821: table.LC_prior_option {
                   6822:   width: 100%;
                   6823:   border-collapse: collapse;
                   6824: }
1.795     www      6825: 
1.911     bisitz   6826: table.LC_prior_rank,
1.795     www      6827: table.LC_prior_match {
1.528     albertel 6828:   border-collapse: collapse;
                   6829: }
1.795     www      6830: 
1.528     albertel 6831: table.LC_prior_option tr td,
                   6832: table.LC_prior_rank tr td,
                   6833: table.LC_prior_match tr td {
1.524     albertel 6834:   border: 1px solid #000000;
1.515     albertel 6835: }
                   6836: 
1.855     bisitz   6837: .LC_nobreak {
1.544     albertel 6838:   white-space: nowrap;
1.519     raeburn  6839: }
                   6840: 
1.576     raeburn  6841: span.LC_cusr_emph {
                   6842:   font-style: italic;
                   6843: }
                   6844: 
1.633     raeburn  6845: span.LC_cusr_subheading {
                   6846:   font-weight: normal;
                   6847:   font-size: 85%;
                   6848: }
                   6849: 
1.861     bisitz   6850: div.LC_docs_entry_move {
1.859     bisitz   6851:   border: 1px solid #BBBBBB;
1.545     albertel 6852:   background: #DDDDDD;
1.861     bisitz   6853:   width: 22px;
1.859     bisitz   6854:   padding: 1px;
                   6855:   margin: 0;
1.545     albertel 6856: }
                   6857: 
1.861     bisitz   6858: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6859: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6860:   font-size: x-small;
                   6861: }
1.795     www      6862: 
1.861     bisitz   6863: .LC_docs_entry_parameter {
                   6864:   white-space: nowrap;
                   6865: }
                   6866: 
1.544     albertel 6867: .LC_docs_copy {
1.545     albertel 6868:   color: #000099;
1.544     albertel 6869: }
1.795     www      6870: 
1.544     albertel 6871: .LC_docs_cut {
1.545     albertel 6872:   color: #550044;
1.544     albertel 6873: }
1.795     www      6874: 
1.544     albertel 6875: .LC_docs_rename {
1.545     albertel 6876:   color: #009900;
1.544     albertel 6877: }
1.795     www      6878: 
1.544     albertel 6879: .LC_docs_remove {
1.545     albertel 6880:   color: #990000;
                   6881: }
                   6882: 
1.1075.2.134  raeburn  6883: .LC_domprefs_email,
1.547     albertel 6884: .LC_docs_reinit_warn,
                   6885: .LC_docs_ext_edit {
                   6886:   font-size: x-small;
                   6887: }
                   6888: 
1.545     albertel 6889: table.LC_docs_adddocs td,
                   6890: table.LC_docs_adddocs th {
                   6891:   border: 1px solid #BBBBBB;
                   6892:   padding: 4px;
                   6893:   background: #DDDDDD;
1.543     albertel 6894: }
                   6895: 
1.584     albertel 6896: table.LC_sty_begin {
                   6897:   background: #BBFFBB;
                   6898: }
1.795     www      6899: 
1.584     albertel 6900: table.LC_sty_end {
                   6901:   background: #FFBBBB;
                   6902: }
                   6903: 
1.589     raeburn  6904: table.LC_double_column {
1.803     bisitz   6905:   border-width: 0;
1.589     raeburn  6906:   border-collapse: collapse;
                   6907:   width: 100%;
                   6908:   padding: 2px;
                   6909: }
                   6910: 
                   6911: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6912:   top: 2px;
1.589     raeburn  6913:   left: 2px;
                   6914:   width: 47%;
                   6915:   vertical-align: top;
                   6916: }
                   6917: 
                   6918: table.LC_double_column tr td.LC_right_col {
                   6919:   top: 2px;
1.779     bisitz   6920:   right: 2px;
1.589     raeburn  6921:   width: 47%;
                   6922:   vertical-align: top;
                   6923: }
                   6924: 
1.591     raeburn  6925: div.LC_left_float {
                   6926:   float: left;
                   6927:   padding-right: 5%;
1.597     albertel 6928:   padding-bottom: 4px;
1.591     raeburn  6929: }
                   6930: 
                   6931: div.LC_clear_float_header {
1.597     albertel 6932:   padding-bottom: 2px;
1.591     raeburn  6933: }
                   6934: 
                   6935: div.LC_clear_float_footer {
1.597     albertel 6936:   padding-top: 10px;
1.591     raeburn  6937:   clear: both;
                   6938: }
                   6939: 
1.597     albertel 6940: div.LC_grade_show_user {
1.941     bisitz   6941: /*  border-left: 5px solid $sidebg; */
                   6942:   border-top: 5px solid #000000;
                   6943:   margin: 50px 0 0 0;
1.936     bisitz   6944:   padding: 15px 0 5px 10px;
1.597     albertel 6945: }
1.795     www      6946: 
1.936     bisitz   6947: div.LC_grade_show_user_odd_row {
1.941     bisitz   6948: /*  border-left: 5px solid #000000; */
                   6949: }
                   6950: 
                   6951: div.LC_grade_show_user div.LC_Box {
                   6952:   margin-right: 50px;
1.597     albertel 6953: }
                   6954: 
                   6955: div.LC_grade_submissions,
                   6956: div.LC_grade_message_center,
1.936     bisitz   6957: div.LC_grade_info_links {
1.597     albertel 6958:   margin: 5px;
                   6959:   width: 99%;
                   6960:   background: #FFFFFF;
                   6961: }
1.795     www      6962: 
1.597     albertel 6963: div.LC_grade_submissions_header,
1.936     bisitz   6964: div.LC_grade_message_center_header {
1.705     tempelho 6965:   font-weight: bold;
                   6966:   font-size: large;
1.597     albertel 6967: }
1.795     www      6968: 
1.597     albertel 6969: div.LC_grade_submissions_body,
1.936     bisitz   6970: div.LC_grade_message_center_body {
1.597     albertel 6971:   border: 1px solid black;
                   6972:   width: 99%;
                   6973:   background: #FFFFFF;
                   6974: }
1.795     www      6975: 
1.613     albertel 6976: table.LC_scantron_action {
                   6977:   width: 100%;
                   6978: }
1.795     www      6979: 
1.613     albertel 6980: table.LC_scantron_action tr th {
1.698     harmsja  6981:   font-weight:bold;
                   6982:   font-style:normal;
1.613     albertel 6983: }
1.795     www      6984: 
1.779     bisitz   6985: .LC_edit_problem_header,
1.614     albertel 6986: div.LC_edit_problem_footer {
1.705     tempelho 6987:   font-weight: normal;
                   6988:   font-size:  medium;
1.602     albertel 6989:   margin: 2px;
1.1060    bisitz   6990:   background-color: $sidebg;
1.600     albertel 6991: }
1.795     www      6992: 
1.600     albertel 6993: div.LC_edit_problem_header,
1.602     albertel 6994: div.LC_edit_problem_header div,
1.614     albertel 6995: div.LC_edit_problem_footer,
                   6996: div.LC_edit_problem_footer div,
1.602     albertel 6997: div.LC_edit_problem_editxml_header,
                   6998: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6999:   z-index: 100;
1.600     albertel 7000: }
1.795     www      7001: 
1.600     albertel 7002: div.LC_edit_problem_header_title {
1.705     tempelho 7003:   font-weight: bold;
                   7004:   font-size: larger;
1.602     albertel 7005:   background: $tabbg;
                   7006:   padding: 3px;
1.1060    bisitz   7007:   margin: 0 0 5px 0;
1.602     albertel 7008: }
1.795     www      7009: 
1.602     albertel 7010: table.LC_edit_problem_header_title {
                   7011:   width: 100%;
1.600     albertel 7012:   background: $tabbg;
1.602     albertel 7013: }
                   7014: 
1.1075.2.112  raeburn  7015: div.LC_edit_actionbar {
                   7016:     background-color: $sidebg;
                   7017:     margin: 0;
                   7018:     padding: 0;
                   7019:     line-height: 200%;
1.602     albertel 7020: }
1.795     www      7021: 
1.1075.2.112  raeburn  7022: div.LC_edit_actionbar div{
                   7023:     padding: 0;
                   7024:     margin: 0;
                   7025:     display: inline-block;
1.600     albertel 7026: }
1.795     www      7027: 
1.1075.2.34  raeburn  7028: .LC_edit_opt {
                   7029:   padding-left: 1em;
                   7030:   white-space: nowrap;
                   7031: }
                   7032: 
1.1075.2.57  raeburn  7033: .LC_edit_problem_latexhelper{
                   7034:     text-align: right;
                   7035: }
                   7036: 
                   7037: #LC_edit_problem_colorful div{
                   7038:     margin-left: 40px;
                   7039: }
                   7040: 
1.1075.2.112  raeburn  7041: #LC_edit_problem_codemirror div{
                   7042:     margin-left: 0px;
                   7043: }
                   7044: 
1.911     bisitz   7045: img.stift {
1.803     bisitz   7046:   border-width: 0;
                   7047:   vertical-align: middle;
1.677     riegler  7048: }
1.680     riegler  7049: 
1.923     bisitz   7050: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7051:   vertical-align: top;
1.777     tempelho 7052: }
1.795     www      7053: 
1.716     raeburn  7054: div.LC_createcourse {
1.911     bisitz   7055:   margin: 10px 10px 10px 10px;
1.716     raeburn  7056: }
                   7057: 
1.917     raeburn  7058: .LC_dccid {
1.1075.2.38  raeburn  7059:   float: right;
1.917     raeburn  7060:   margin: 0.2em 0 0 0;
                   7061:   padding: 0;
                   7062:   font-size: 90%;
                   7063:   display:none;
                   7064: }
                   7065: 
1.897     wenzelju 7066: ol.LC_primary_menu a:hover,
1.721     harmsja  7067: ol#LC_MenuBreadcrumbs a:hover,
                   7068: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7069: ul#LC_secondary_menu a:hover,
1.721     harmsja  7070: .LC_FormSectionClearButton input:hover
1.795     www      7071: ul.LC_TabContent   li:hover a {
1.952     onken    7072:   color:$button_hover;
1.911     bisitz   7073:   text-decoration:none;
1.693     droeschl 7074: }
                   7075: 
1.779     bisitz   7076: h1 {
1.911     bisitz   7077:   padding: 0;
                   7078:   line-height:130%;
1.693     droeschl 7079: }
1.698     harmsja  7080: 
1.911     bisitz   7081: h2,
                   7082: h3,
                   7083: h4,
                   7084: h5,
                   7085: h6 {
                   7086:   margin: 5px 0 5px 0;
                   7087:   padding: 0;
                   7088:   line-height:130%;
1.693     droeschl 7089: }
1.795     www      7090: 
                   7091: .LC_hcell {
1.911     bisitz   7092:   padding:3px 15px 3px 15px;
                   7093:   margin: 0;
                   7094:   background-color:$tabbg;
                   7095:   color:$fontmenu;
                   7096:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7097: }
1.795     www      7098: 
1.840     bisitz   7099: .LC_Box > .LC_hcell {
1.911     bisitz   7100:   margin: 0 -10px 10px -10px;
1.835     bisitz   7101: }
                   7102: 
1.721     harmsja  7103: .LC_noBorder {
1.911     bisitz   7104:   border: 0;
1.698     harmsja  7105: }
1.693     droeschl 7106: 
1.721     harmsja  7107: .LC_FormSectionClearButton input {
1.911     bisitz   7108:   background-color:transparent;
                   7109:   border: none;
                   7110:   cursor:pointer;
                   7111:   text-decoration:underline;
1.693     droeschl 7112: }
1.763     bisitz   7113: 
                   7114: .LC_help_open_topic {
1.911     bisitz   7115:   color: #FFFFFF;
                   7116:   background-color: #EEEEFF;
                   7117:   margin: 1px;
                   7118:   padding: 4px;
                   7119:   border: 1px solid #000033;
                   7120:   white-space: nowrap;
                   7121:   /* vertical-align: middle; */
1.759     neumanie 7122: }
1.693     droeschl 7123: 
1.911     bisitz   7124: dl,
                   7125: ul,
                   7126: div,
                   7127: fieldset {
                   7128:   margin: 10px 10px 10px 0;
                   7129:   /* overflow: hidden; */
1.693     droeschl 7130: }
1.795     www      7131: 
1.1075.2.90  raeburn  7132: article.geogebraweb div {
                   7133:     margin: 0;
                   7134: }
                   7135: 
1.838     bisitz   7136: fieldset > legend {
1.911     bisitz   7137:   font-weight: bold;
                   7138:   padding: 0 5px 0 5px;
1.838     bisitz   7139: }
                   7140: 
1.813     bisitz   7141: #LC_nav_bar {
1.911     bisitz   7142:   float: left;
1.995     raeburn  7143:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7144:   margin: 0 0 2px 0;
1.807     droeschl 7145: }
                   7146: 
1.916     droeschl 7147: #LC_realm {
                   7148:   margin: 0.2em 0 0 0;
                   7149:   padding: 0;
                   7150:   font-weight: bold;
                   7151:   text-align: center;
1.995     raeburn  7152:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7153: }
                   7154: 
1.911     bisitz   7155: #LC_nav_bar em {
                   7156:   font-weight: bold;
                   7157:   font-style: normal;
1.807     droeschl 7158: }
                   7159: 
1.897     wenzelju 7160: ol.LC_primary_menu {
1.934     droeschl 7161:   margin: 0;
1.1075.2.2  raeburn  7162:   padding: 0;
1.807     droeschl 7163: }
                   7164: 
1.852     droeschl 7165: ol#LC_PathBreadcrumbs {
1.911     bisitz   7166:   margin: 0;
1.693     droeschl 7167: }
                   7168: 
1.897     wenzelju 7169: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7170:   color: RGB(80, 80, 80);
                   7171:   vertical-align: middle;
                   7172:   text-align: left;
                   7173:   list-style: none;
1.1075.2.112  raeburn  7174:   position: relative;
1.1075.2.2  raeburn  7175:   float: left;
1.1075.2.112  raeburn  7176:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7177:   line-height: 1.5em;
1.1075.2.2  raeburn  7178: }
                   7179: 
1.1075.2.113  raeburn  7180: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7181: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7182:   display: block;
                   7183:   margin: 0;
                   7184:   padding: 0 5px 0 10px;
                   7185:   text-decoration: none;
                   7186: }
                   7187: 
1.1075.2.112  raeburn  7188: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7189:   display: inline-block;
                   7190:   width: 95%;
                   7191:   text-align: left;
                   7192: }
                   7193: 
                   7194: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7195:   display: inline-block;
                   7196:   width: 5%;
                   7197:   float: right;
                   7198:   text-align: right;
                   7199:   font-size: 70%;
                   7200: }
                   7201: 
                   7202: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7203:   display: none;
1.1075.2.112  raeburn  7204:   width: 15em;
1.1075.2.2  raeburn  7205:   background-color: $data_table_light;
1.1075.2.112  raeburn  7206:   position: absolute;
                   7207:   top: 100%;
                   7208: }
                   7209: 
                   7210: ol.LC_primary_menu ul ul {
                   7211:   left: 100%;
                   7212:   top: 0;
1.1075.2.2  raeburn  7213: }
                   7214: 
1.1075.2.112  raeburn  7215: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7216:   display: block;
                   7217:   position: absolute;
                   7218:   margin: 0;
                   7219:   padding: 0;
1.1075.2.5  raeburn  7220:   z-index: 2;
1.1075.2.2  raeburn  7221: }
                   7222: 
                   7223: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7224: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7225:   font-size: 90%;
1.911     bisitz   7226:   vertical-align: top;
1.1075.2.2  raeburn  7227:   float: none;
1.1075.2.5  raeburn  7228:   border-left: 1px solid black;
                   7229:   border-right: 1px solid black;
1.1075.2.112  raeburn  7230: /* A dark bottom border to visualize different menu options;
                   7231: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7232:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7233: }
                   7234: 
1.1075.2.112  raeburn  7235: ol.LC_primary_menu li li p:hover {
                   7236:   color:$button_hover;
                   7237:   text-decoration:none;
                   7238:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7239: }
                   7240: 
                   7241: ol.LC_primary_menu li li a:hover {
                   7242:    color:$button_hover;
                   7243:    background-color:$data_table_dark;
1.693     droeschl 7244: }
                   7245: 
1.1075.2.112  raeburn  7246: /* Font-size equal to the size of the predecessors*/
                   7247: ol.LC_primary_menu li:hover li li {
                   7248:   font-size: 100%;
                   7249: }
                   7250: 
1.897     wenzelju 7251: ol.LC_primary_menu li img {
1.911     bisitz   7252:   vertical-align: bottom;
1.934     droeschl 7253:   height: 1.1em;
1.1075.2.3  raeburn  7254:   margin: 0.2em 0 0 0;
1.693     droeschl 7255: }
                   7256: 
1.897     wenzelju 7257: ol.LC_primary_menu a {
1.911     bisitz   7258:   color: RGB(80, 80, 80);
                   7259:   text-decoration: none;
1.693     droeschl 7260: }
1.795     www      7261: 
1.949     droeschl 7262: ol.LC_primary_menu a.LC_new_message {
                   7263:   font-weight:bold;
                   7264:   color: darkred;
                   7265: }
                   7266: 
1.975     raeburn  7267: ol.LC_docs_parameters {
                   7268:   margin-left: 0;
                   7269:   padding: 0;
                   7270:   list-style: none;
                   7271: }
                   7272: 
                   7273: ol.LC_docs_parameters li {
                   7274:   margin: 0;
                   7275:   padding-right: 20px;
                   7276:   display: inline;
                   7277: }
                   7278: 
1.976     raeburn  7279: ol.LC_docs_parameters li:before {
                   7280:   content: "\\002022 \\0020";
                   7281: }
                   7282: 
                   7283: li.LC_docs_parameters_title {
                   7284:   font-weight: bold;
                   7285: }
                   7286: 
                   7287: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7288:   content: "";
                   7289: }
                   7290: 
1.897     wenzelju 7291: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7292:   clear: right;
1.911     bisitz   7293:   color: $fontmenu;
                   7294:   background: $tabbg;
                   7295:   list-style: none;
                   7296:   padding: 0;
                   7297:   margin: 0;
                   7298:   width: 100%;
1.995     raeburn  7299:   text-align: left;
1.1075.2.4  raeburn  7300:   float: left;
1.808     droeschl 7301: }
                   7302: 
1.897     wenzelju 7303: ul#LC_secondary_menu li {
1.911     bisitz   7304:   font-weight: bold;
                   7305:   line-height: 1.8em;
                   7306:   border-right: 1px solid black;
1.1075.2.4  raeburn  7307:   float: left;
                   7308: }
                   7309: 
                   7310: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7311:   background-color: $data_table_light;
                   7312: }
                   7313: 
                   7314: ul#LC_secondary_menu li a {
                   7315:   padding: 0 0.8em;
                   7316: }
                   7317: 
                   7318: ul#LC_secondary_menu li ul {
                   7319:   display: none;
                   7320: }
                   7321: 
                   7322: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7323:   display: block;
                   7324:   position: absolute;
                   7325:   margin: 0;
                   7326:   padding: 0;
                   7327:   list-style:none;
                   7328:   float: none;
                   7329:   background-color: $data_table_light;
1.1075.2.5  raeburn  7330:   z-index: 2;
1.1075.2.10  raeburn  7331:   margin-left: -1px;
1.1075.2.4  raeburn  7332: }
                   7333: 
                   7334: ul#LC_secondary_menu li ul li {
                   7335:   font-size: 90%;
                   7336:   vertical-align: top;
                   7337:   border-left: 1px solid black;
                   7338:   border-right: 1px solid black;
1.1075.2.33  raeburn  7339:   background-color: $data_table_light;
1.1075.2.4  raeburn  7340:   list-style:none;
                   7341:   float: none;
                   7342: }
                   7343: 
                   7344: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7345:   background-color: $data_table_dark;
1.807     droeschl 7346: }
                   7347: 
1.847     tempelho 7348: ul.LC_TabContent {
1.911     bisitz   7349:   display:block;
                   7350:   background: $sidebg;
                   7351:   border-bottom: solid 1px $lg_border_color;
                   7352:   list-style:none;
1.1020    raeburn  7353:   margin: -1px -10px 0 -10px;
1.911     bisitz   7354:   padding: 0;
1.693     droeschl 7355: }
                   7356: 
1.795     www      7357: ul.LC_TabContent li,
                   7358: ul.LC_TabContentBigger li {
1.911     bisitz   7359:   float:left;
1.741     harmsja  7360: }
1.795     www      7361: 
1.897     wenzelju 7362: ul#LC_secondary_menu li a {
1.911     bisitz   7363:   color: $fontmenu;
                   7364:   text-decoration: none;
1.693     droeschl 7365: }
1.795     www      7366: 
1.721     harmsja  7367: ul.LC_TabContent {
1.952     onken    7368:   min-height:20px;
1.721     harmsja  7369: }
1.795     www      7370: 
                   7371: ul.LC_TabContent li {
1.911     bisitz   7372:   vertical-align:middle;
1.959     onken    7373:   padding: 0 16px 0 10px;
1.911     bisitz   7374:   background-color:$tabbg;
                   7375:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7376:   border-left: solid 1px $font;
1.721     harmsja  7377: }
1.795     www      7378: 
1.847     tempelho 7379: ul.LC_TabContent .right {
1.911     bisitz   7380:   float:right;
1.847     tempelho 7381: }
                   7382: 
1.911     bisitz   7383: ul.LC_TabContent li a,
                   7384: ul.LC_TabContent li {
                   7385:   color:rgb(47,47,47);
                   7386:   text-decoration:none;
                   7387:   font-size:95%;
                   7388:   font-weight:bold;
1.952     onken    7389:   min-height:20px;
                   7390: }
                   7391: 
1.959     onken    7392: ul.LC_TabContent li a:hover,
                   7393: ul.LC_TabContent li a:focus {
1.952     onken    7394:   color: $button_hover;
1.959     onken    7395:   background:none;
                   7396:   outline:none;
1.952     onken    7397: }
                   7398: 
                   7399: ul.LC_TabContent li:hover {
                   7400:   color: $button_hover;
                   7401:   cursor:pointer;
1.721     harmsja  7402: }
1.795     www      7403: 
1.911     bisitz   7404: ul.LC_TabContent li.active {
1.952     onken    7405:   color: $font;
1.911     bisitz   7406:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7407:   border-bottom:solid 1px #FFFFFF;
                   7408:   cursor: default;
1.744     ehlerst  7409: }
1.795     www      7410: 
1.959     onken    7411: ul.LC_TabContent li.active a {
                   7412:   color:$font;
                   7413:   background:#FFFFFF;
                   7414:   outline: none;
                   7415: }
1.1047    raeburn  7416: 
                   7417: ul.LC_TabContent li.goback {
                   7418:   float: left;
                   7419:   border-left: none;
                   7420: }
                   7421: 
1.870     tempelho 7422: #maincoursedoc {
1.911     bisitz   7423:   clear:both;
1.870     tempelho 7424: }
                   7425: 
                   7426: ul.LC_TabContentBigger {
1.911     bisitz   7427:   display:block;
                   7428:   list-style:none;
                   7429:   padding: 0;
1.870     tempelho 7430: }
                   7431: 
1.795     www      7432: ul.LC_TabContentBigger li {
1.911     bisitz   7433:   vertical-align:bottom;
                   7434:   height: 30px;
                   7435:   font-size:110%;
                   7436:   font-weight:bold;
                   7437:   color: #737373;
1.841     tempelho 7438: }
                   7439: 
1.957     onken    7440: ul.LC_TabContentBigger li.active {
                   7441:   position: relative;
                   7442:   top: 1px;
                   7443: }
                   7444: 
1.870     tempelho 7445: ul.LC_TabContentBigger li a {
1.911     bisitz   7446:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7447:   height: 30px;
                   7448:   line-height: 30px;
                   7449:   text-align: center;
                   7450:   display: block;
                   7451:   text-decoration: none;
1.958     onken    7452:   outline: none;  
1.741     harmsja  7453: }
1.795     www      7454: 
1.870     tempelho 7455: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7456:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7457:   color:$font;
1.744     ehlerst  7458: }
1.795     www      7459: 
1.870     tempelho 7460: ul.LC_TabContentBigger li b {
1.911     bisitz   7461:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7462:   display: block;
                   7463:   float: left;
                   7464:   padding: 0 30px;
1.957     onken    7465:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7466: }
                   7467: 
1.956     onken    7468: ul.LC_TabContentBigger li:hover b {
                   7469:   color:$button_hover;
                   7470: }
                   7471: 
1.870     tempelho 7472: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7473:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7474:   color:$font;
1.957     onken    7475:   border: 0;
1.741     harmsja  7476: }
1.693     droeschl 7477: 
1.870     tempelho 7478: 
1.862     bisitz   7479: ul.LC_CourseBreadcrumbs {
                   7480:   background: $sidebg;
1.1020    raeburn  7481:   height: 2em;
1.862     bisitz   7482:   padding-left: 10px;
1.1020    raeburn  7483:   margin: 0;
1.862     bisitz   7484:   list-style-position: inside;
                   7485: }
                   7486: 
1.911     bisitz   7487: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7488: ol#LC_PathBreadcrumbs {
1.911     bisitz   7489:   padding-left: 10px;
                   7490:   margin: 0;
1.933     droeschl 7491:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7492: }
                   7493: 
1.911     bisitz   7494: ol#LC_MenuBreadcrumbs li,
                   7495: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7496: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7497:   display: inline;
1.933     droeschl 7498:   white-space: normal;  
1.693     droeschl 7499: }
                   7500: 
1.823     bisitz   7501: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7502: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7503:   text-decoration: none;
                   7504:   font-size:90%;
1.693     droeschl 7505: }
1.795     www      7506: 
1.969     droeschl 7507: ol#LC_MenuBreadcrumbs h1 {
                   7508:   display: inline;
                   7509:   font-size: 90%;
                   7510:   line-height: 2.5em;
                   7511:   margin: 0;
                   7512:   padding: 0;
                   7513: }
                   7514: 
1.795     www      7515: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7516:   text-decoration:none;
                   7517:   font-size:100%;
                   7518:   font-weight:bold;
1.693     droeschl 7519: }
1.795     www      7520: 
1.840     bisitz   7521: .LC_Box {
1.911     bisitz   7522:   border: solid 1px $lg_border_color;
                   7523:   padding: 0 10px 10px 10px;
1.746     neumanie 7524: }
1.795     www      7525: 
1.1020    raeburn  7526: .LC_DocsBox {
                   7527:   border: solid 1px $lg_border_color;
                   7528:   padding: 0 0 10px 10px;
                   7529: }
                   7530: 
1.795     www      7531: .LC_AboutMe_Image {
1.911     bisitz   7532:   float:left;
                   7533:   margin-right:10px;
1.747     neumanie 7534: }
1.795     www      7535: 
                   7536: .LC_Clear_AboutMe_Image {
1.911     bisitz   7537:   clear:left;
1.747     neumanie 7538: }
1.795     www      7539: 
1.721     harmsja  7540: dl.LC_ListStyleClean dt {
1.911     bisitz   7541:   padding-right: 5px;
                   7542:   display: table-header-group;
1.693     droeschl 7543: }
                   7544: 
1.721     harmsja  7545: dl.LC_ListStyleClean dd {
1.911     bisitz   7546:   display: table-row;
1.693     droeschl 7547: }
                   7548: 
1.721     harmsja  7549: .LC_ListStyleClean,
                   7550: .LC_ListStyleSimple,
                   7551: .LC_ListStyleNormal,
1.795     www      7552: .LC_ListStyleSpecial {
1.911     bisitz   7553:   /* display:block; */
                   7554:   list-style-position: inside;
                   7555:   list-style-type: none;
                   7556:   overflow: hidden;
                   7557:   padding: 0;
1.693     droeschl 7558: }
                   7559: 
1.721     harmsja  7560: .LC_ListStyleSimple li,
                   7561: .LC_ListStyleSimple dd,
                   7562: .LC_ListStyleNormal li,
                   7563: .LC_ListStyleNormal dd,
                   7564: .LC_ListStyleSpecial li,
1.795     www      7565: .LC_ListStyleSpecial dd {
1.911     bisitz   7566:   margin: 0;
                   7567:   padding: 5px 5px 5px 10px;
                   7568:   clear: both;
1.693     droeschl 7569: }
                   7570: 
1.721     harmsja  7571: .LC_ListStyleClean li,
                   7572: .LC_ListStyleClean dd {
1.911     bisitz   7573:   padding-top: 0;
                   7574:   padding-bottom: 0;
1.693     droeschl 7575: }
                   7576: 
1.721     harmsja  7577: .LC_ListStyleSimple dd,
1.795     www      7578: .LC_ListStyleSimple li {
1.911     bisitz   7579:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7580: }
                   7581: 
1.721     harmsja  7582: .LC_ListStyleSpecial li,
                   7583: .LC_ListStyleSpecial dd {
1.911     bisitz   7584:   list-style-type: none;
                   7585:   background-color: RGB(220, 220, 220);
                   7586:   margin-bottom: 4px;
1.693     droeschl 7587: }
                   7588: 
1.721     harmsja  7589: table.LC_SimpleTable {
1.911     bisitz   7590:   margin:5px;
                   7591:   border:solid 1px $lg_border_color;
1.795     www      7592: }
1.693     droeschl 7593: 
1.721     harmsja  7594: table.LC_SimpleTable tr {
1.911     bisitz   7595:   padding: 0;
                   7596:   border:solid 1px $lg_border_color;
1.693     droeschl 7597: }
1.795     www      7598: 
                   7599: table.LC_SimpleTable thead {
1.911     bisitz   7600:   background:rgb(220,220,220);
1.693     droeschl 7601: }
                   7602: 
1.721     harmsja  7603: div.LC_columnSection {
1.911     bisitz   7604:   display: block;
                   7605:   clear: both;
                   7606:   overflow: hidden;
                   7607:   margin: 0;
1.693     droeschl 7608: }
                   7609: 
1.721     harmsja  7610: div.LC_columnSection>* {
1.911     bisitz   7611:   float: left;
                   7612:   margin: 10px 20px 10px 0;
                   7613:   overflow:hidden;
1.693     droeschl 7614: }
1.721     harmsja  7615: 
1.795     www      7616: table em {
1.911     bisitz   7617:   font-weight: bold;
                   7618:   font-style: normal;
1.748     schulted 7619: }
1.795     www      7620: 
1.779     bisitz   7621: table.LC_tableBrowseRes,
1.795     www      7622: table.LC_tableOfContent {
1.911     bisitz   7623:   border:none;
                   7624:   border-spacing: 1px;
                   7625:   padding: 3px;
                   7626:   background-color: #FFFFFF;
                   7627:   font-size: 90%;
1.753     droeschl 7628: }
1.789     droeschl 7629: 
1.911     bisitz   7630: table.LC_tableOfContent {
                   7631:   border-collapse: collapse;
1.789     droeschl 7632: }
                   7633: 
1.771     droeschl 7634: table.LC_tableBrowseRes a,
1.768     schulted 7635: table.LC_tableOfContent a {
1.911     bisitz   7636:   background-color: transparent;
                   7637:   text-decoration: none;
1.753     droeschl 7638: }
                   7639: 
1.795     www      7640: table.LC_tableOfContent img {
1.911     bisitz   7641:   border: none;
                   7642:   height: 1.3em;
                   7643:   vertical-align: text-bottom;
                   7644:   margin-right: 0.3em;
1.753     droeschl 7645: }
1.757     schulted 7646: 
1.795     www      7647: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7648:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7649: }
                   7650: 
1.795     www      7651: a#LC_content_toolbar_everything {
1.911     bisitz   7652:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7653: }
                   7654: 
1.795     www      7655: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7656:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7657: }
                   7658: 
1.795     www      7659: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7660:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7661: }
                   7662: 
1.795     www      7663: a#LC_content_toolbar_changefolder {
1.911     bisitz   7664:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7665: }
                   7666: 
1.795     www      7667: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7668:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7669: }
                   7670: 
1.1043    raeburn  7671: a#LC_content_toolbar_edittoplevel {
                   7672:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7673: }
                   7674: 
1.795     www      7675: ul#LC_toolbar li a:hover {
1.911     bisitz   7676:   background-position: bottom center;
1.757     schulted 7677: }
                   7678: 
1.795     www      7679: ul#LC_toolbar {
1.911     bisitz   7680:   padding: 0;
                   7681:   margin: 2px;
                   7682:   list-style:none;
                   7683:   position:relative;
                   7684:   background-color:white;
1.1075.2.9  raeburn  7685:   overflow: auto;
1.757     schulted 7686: }
                   7687: 
1.795     www      7688: ul#LC_toolbar li {
1.911     bisitz   7689:   border:1px solid white;
                   7690:   padding: 0;
                   7691:   margin: 0;
                   7692:   float: left;
                   7693:   display:inline;
                   7694:   vertical-align:middle;
1.1075.2.9  raeburn  7695:   white-space: nowrap;
1.911     bisitz   7696: }
1.757     schulted 7697: 
1.783     amueller 7698: 
1.795     www      7699: a.LC_toolbarItem {
1.911     bisitz   7700:   display:block;
                   7701:   padding: 0;
                   7702:   margin: 0;
                   7703:   height: 32px;
                   7704:   width: 32px;
                   7705:   color:white;
                   7706:   border: none;
                   7707:   background-repeat:no-repeat;
                   7708:   background-color:transparent;
1.757     schulted 7709: }
                   7710: 
1.915     droeschl 7711: ul.LC_funclist {
                   7712:     margin: 0;
                   7713:     padding: 0.5em 1em 0.5em 0;
                   7714: }
                   7715: 
1.933     droeschl 7716: ul.LC_funclist > li:first-child {
                   7717:     font-weight:bold; 
                   7718:     margin-left:0.8em;
                   7719: }
                   7720: 
1.915     droeschl 7721: ul.LC_funclist + ul.LC_funclist {
                   7722:     /* 
                   7723:        left border as a seperator if we have more than
                   7724:        one list 
                   7725:     */
                   7726:     border-left: 1px solid $sidebg;
                   7727:     /* 
                   7728:        this hides the left border behind the border of the 
                   7729:        outer box if element is wrapped to the next 'line' 
                   7730:     */
                   7731:     margin-left: -1px;
                   7732: }
                   7733: 
1.843     bisitz   7734: ul.LC_funclist li {
1.915     droeschl 7735:   display: inline;
1.782     bisitz   7736:   white-space: nowrap;
1.915     droeschl 7737:   margin: 0 0 0 25px;
                   7738:   line-height: 150%;
1.782     bisitz   7739: }
                   7740: 
1.974     wenzelju 7741: .LC_hidden {
                   7742:   display: none;
                   7743: }
                   7744: 
1.1030    www      7745: .LCmodal-overlay {
                   7746: 		position:fixed;
                   7747: 		top:0;
                   7748: 		right:0;
                   7749: 		bottom:0;
                   7750: 		left:0;
                   7751: 		height:100%;
                   7752: 		width:100%;
                   7753: 		margin:0;
                   7754: 		padding:0;
                   7755: 		background:#999;
                   7756: 		opacity:.75;
                   7757: 		filter: alpha(opacity=75);
                   7758: 		-moz-opacity: 0.75;
                   7759: 		z-index:101;
                   7760: }
                   7761: 
                   7762: * html .LCmodal-overlay {   
                   7763: 		position: absolute;
                   7764: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7765: }
                   7766: 
                   7767: .LCmodal-window {
                   7768: 		position:fixed;
                   7769: 		top:50%;
                   7770: 		left:50%;
                   7771: 		margin:0;
                   7772: 		padding:0;
                   7773: 		z-index:102;
                   7774: 	}
                   7775: 
                   7776: * html .LCmodal-window {
                   7777: 		position:absolute;
                   7778: }
                   7779: 
                   7780: .LCclose-window {
                   7781: 		position:absolute;
                   7782: 		width:32px;
                   7783: 		height:32px;
                   7784: 		right:8px;
                   7785: 		top:8px;
                   7786: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7787: 		text-indent:-99999px;
                   7788: 		overflow:hidden;
                   7789: 		cursor:pointer;
                   7790: }
                   7791: 
1.1075.2.141  raeburn  7792: pre.LC_wordwrap {
                   7793:   white-space: pre-wrap;
                   7794:   white-space: -moz-pre-wrap;
                   7795:   white-space: -pre-wrap;
                   7796:   white-space: -o-pre-wrap;
                   7797:   word-wrap: break-word;
                   7798: }
                   7799: 
1.1075.2.17  raeburn  7800: /*
                   7801:   styles used by TTH when "Default set of options to pass to tth/m
                   7802:   when converting TeX" in course settings has been set
                   7803: 
                   7804:   option passed: -t
                   7805: 
                   7806: */
                   7807: 
                   7808: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7809: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7810: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7811: td div.norm {line-height:normal;}
                   7812: 
                   7813: /*
                   7814:   option passed -y3
                   7815: */
                   7816: 
                   7817: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7818: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7819: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7820: 
1.1075.2.121  raeburn  7821: #LC_minitab_header {
                   7822:   float:left;
                   7823:   width:100%;
                   7824:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7825:   font-size:93%;
                   7826:   line-height:normal;
                   7827:   margin: 0.5em 0 0.5em 0;
                   7828: }
                   7829: #LC_minitab_header ul {
                   7830:   margin:0;
                   7831:   padding:10px 10px 0;
                   7832:   list-style:none;
                   7833: }
                   7834: #LC_minitab_header li {
                   7835:   float:left;
                   7836:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7837:   margin:0;
                   7838:   padding:0 0 0 9px;
                   7839: }
                   7840: #LC_minitab_header a {
                   7841:   display:block;
                   7842:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7843:   padding:5px 15px 4px 6px;
                   7844: }
                   7845: #LC_minitab_header #LC_current_minitab {
                   7846:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7847: }
                   7848: #LC_minitab_header #LC_current_minitab a {
                   7849:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7850:   padding-bottom:5px;
                   7851: }
                   7852: 
                   7853: 
1.343     albertel 7854: END
                   7855: }
                   7856: 
1.306     albertel 7857: =pod
                   7858: 
                   7859: =item * &headtag()
                   7860: 
                   7861: Returns a uniform footer for LON-CAPA web pages.
                   7862: 
1.307     albertel 7863: Inputs: $title - optional title for the head
                   7864:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7865:         $args - optional arguments
1.319     albertel 7866:             force_register - if is true call registerurl so the remote is 
                   7867:                              informed
1.415     albertel 7868:             redirect       -> array ref of
                   7869:                                    1- seconds before redirect occurs
                   7870:                                    2- url to redirect to
                   7871:                                    3- whether the side effect should occur
1.315     albertel 7872:                            (side effect of setting 
                   7873:                                $env{'internal.head.redirect'} to the url 
                   7874:                                redirected too)
1.352     albertel 7875:             domain         -> force to color decorate a page for a specific
                   7876:                                domain
                   7877:             function       -> force usage of a specific rolish color scheme
                   7878:             bgcolor        -> override the default page bgcolor
1.460     albertel 7879:             no_auto_mt_title
                   7880:                            -> prevent &mt()ing the title arg
1.464     albertel 7881: 
1.306     albertel 7882: =cut
                   7883: 
                   7884: sub headtag {
1.313     albertel 7885:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7886:     
1.363     albertel 7887:     my $function = $args->{'function'} || &get_users_function();
                   7888:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7889:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7890:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7891:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7892: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7893: 		   #time(),
1.418     albertel 7894: 		   $env{'environment.color.timestamp'},
1.363     albertel 7895: 		   $function,$domain,$bgcolor);
                   7896: 
1.369     www      7897:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7898: 
1.308     albertel 7899:     my $result =
                   7900: 	'<head>'.
1.1075.2.56  raeburn  7901: 	&font_settings($args);
1.319     albertel 7902: 
1.1075.2.72  raeburn  7903:     my $inhibitprint;
                   7904:     if ($args->{'print_suppress'}) {
                   7905:         $inhibitprint = &print_suppression();
                   7906:     }
1.1064    raeburn  7907: 
1.461     albertel 7908:     if (!$args->{'frameset'}) {
                   7909: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7910:     }
1.1075.2.12  raeburn  7911:     if ($args->{'force_register'}) {
                   7912:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7913:     }
1.436     albertel 7914:     if (!$args->{'no_nav_bar'} 
                   7915: 	&& !$args->{'only_body'}
                   7916: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7917: 	$result .= &help_menu_js($httphost);
1.1032    www      7918:         $result.=&modal_window();
1.1038    www      7919:         $result.=&togglebox_script();
1.1034    www      7920:         $result.=&wishlist_window();
1.1041    www      7921:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7922:     } else {
                   7923:         if ($args->{'add_modal'}) {
                   7924:            $result.=&modal_window();
                   7925:         }
                   7926:         if ($args->{'add_wishlist'}) {
                   7927:            $result.=&wishlist_window();
                   7928:         }
1.1038    www      7929:         if ($args->{'add_togglebox'}) {
                   7930:            $result.=&togglebox_script();
                   7931:         }
1.1041    www      7932:         if ($args->{'add_progressbar'}) {
                   7933:            $result.=&LCprogressbarUpdate_script();
                   7934:         }
1.436     albertel 7935:     }
1.314     albertel 7936:     if (ref($args->{'redirect'})) {
1.414     albertel 7937: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7938: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7939: 	if (!$inhibit_continue) {
                   7940: 	    $env{'internal.head.redirect'} = $url;
                   7941: 	}
1.313     albertel 7942: 	$result.=<<ADDMETA
                   7943: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7944: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7945: ADDMETA
1.1075.2.89  raeburn  7946:     } else {
                   7947:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7948:             my $requrl = $env{'request.uri'};
                   7949:             if ($requrl eq '') {
                   7950:                 $requrl = $ENV{'REQUEST_URI'};
                   7951:                 $requrl =~ s/\?.+$//;
                   7952:             }
                   7953:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7954:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7955:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7956:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7957:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7958:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.141.  .4(raebu 7959:20):                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7960:20):                     my $offload;
1.1075.2.89  raeburn  7961:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7962:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.141.  .4(raebu 7963:20):                             $offload = 1;
                   7964:20):                         }
                   7965:20):                     }
                   7966:20):                     unless ($offload) {
                   7967:20):                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   7968:20):                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   7969:20):                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   7970:20):                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   7971:20):                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   7972:20):                                         $offload = 1;
                   7973:20):                                         $dom_in_use = $env{'user.domain'};
                   7974:20):                                     }
1.1075.2.89  raeburn  7975:                                 }
1.1075.2.141.  .4(raebu 7976:20):                             }
                   7977:20):                         }
                   7978:20):                     }
                   7979:20):                     if ($offload) {
                   7980:20):                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7981:20):                         if (($newserver) && ($newserver ne $lonhost)) {
                   7982:20):                             my $numsec = 5;
                   7983:20):                             my $timeout = $numsec * 1000;
                   7984:20):                             my ($newurl,$locknum,%locks,$msg);
                   7985:20):                             if ($env{'request.role.adv'}) {
                   7986:20):                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7987:20):                             }
                   7988:20):                             my $disable_submit = 0;
                   7989:20):                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   7990:20):                                 $disable_submit = 1;
                   7991:20):                             }
                   7992:20):                             if ($locknum) {
                   7993:20):                                 my @lockinfo = sort(values(%locks));
                   7994:20):                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   7995:20):                                        join(", ",sort(values(%locks)))."\n";
                   7996:20):                                 if (&show_course()) {
                   7997:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  7998:                                 } else {
1.1075.2.141.  .4(raebu 7999:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8000:20):                                 }
                   8001:20):                             } else {
                   8002:20):                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8003:20):                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8004:20):                                 }
                   8005:20):                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8006:20):                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8007:20):                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8008:20):                                     $newurl .= '&role='.$env{'request.role'};
                   8009:20):                                 }
                   8010:20):                                 if ($env{'request.symb'}) {
                   8011:20):                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8012:20):                                     if ($shownsymb =~ m{^/enc/}) {
                   8013:20):                                         my $reqdmajor = 2;
                   8014:20):                                         my $reqdminor = 11;
                   8015:20):                                         my $reqdsubminor = 3;
                   8016:20):                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8017:20):                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8018:20):                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8019:20):                                         if (($major eq '' && $minor eq '') ||
                   8020:20):                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8021:20):                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8022:20):                                              ($reqdsubminor > $subminor))))) {
                   8023:20):                                             undef($shownsymb);
                   8024:20):                                         }
1.1075.2.89  raeburn  8025:                                     }
1.1075.2.141.  .4(raebu 8026:20):                                     if ($shownsymb) {
                   8027:20):                                         &js_escape(\$shownsymb);
                   8028:20):                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8029:                                     }
1.1075.2.141.  .4(raebu 8030:20):                                 } else {
                   8031:20):                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8032:20):                                     &js_escape(\$shownurl);
                   8033:20):                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8034:                                 }
1.1075.2.141.  .4(raebu 8035:20):                             }
                   8036:20):                             &js_escape(\$msg);
                   8037:20):                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8038: <meta http-equiv="pragma" content="no-cache" />
                   8039: <script type="text/javascript">
1.1075.2.92  raeburn  8040: // <![CDATA[
1.1075.2.89  raeburn  8041: function LC_Offload_Now() {
                   8042:     var dest = "$newurl";
                   8043:     if (dest != '') {
                   8044:         window.location.href="$newurl";
                   8045:     }
                   8046: }
1.1075.2.92  raeburn  8047: \$(document).ready(function () {
                   8048:     window.alert('$msg');
                   8049:     if ($disable_submit) {
1.1075.2.89  raeburn  8050:         \$(".LC_hwk_submit").prop("disabled", true);
                   8051:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8052:     }
                   8053:     setTimeout('LC_Offload_Now()', $timeout);
                   8054: });
                   8055: // ]]>
1.1075.2.89  raeburn  8056: </script>
                   8057: OFFLOAD
                   8058:                         }
                   8059:                     }
                   8060:                 }
                   8061:             }
                   8062:         }
1.313     albertel 8063:     }
1.306     albertel 8064:     if (!defined($title)) {
                   8065: 	$title = 'The LearningOnline Network with CAPA';
                   8066:     }
1.460     albertel 8067:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8068:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8069: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8070:     if (!$args->{'frameset'}) {
                   8071:         $result .= ' /';
                   8072:     }
                   8073:     $result .= '>'
1.1064    raeburn  8074:         .$inhibitprint
1.414     albertel 8075: 	.$head_extra;
1.1075.2.108  raeburn  8076:     my $clientmobile;
                   8077:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8078:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8079:     } else {
                   8080:         $clientmobile = $env{'browser.mobile'};
                   8081:     }
                   8082:     if ($clientmobile) {
1.1075.2.42  raeburn  8083:         $result .= '
                   8084: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8085: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8086:     }
1.1075.2.126  raeburn  8087:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8088:     return $result.'</head>';
1.306     albertel 8089: }
                   8090: 
                   8091: =pod
                   8092: 
1.340     albertel 8093: =item * &font_settings()
                   8094: 
                   8095: Returns neccessary <meta> to set the proper encoding
                   8096: 
1.1075.2.56  raeburn  8097: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8098: 
                   8099: =cut
                   8100: 
                   8101: sub font_settings {
1.1075.2.56  raeburn  8102:     my ($args) = @_;
1.340     albertel 8103:     my $headerstring='';
1.1075.2.56  raeburn  8104:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8105:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8106: 	$headerstring.=
1.1075.2.61  raeburn  8107: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8108:         if (!$args->{'frameset'}) {
                   8109:             $headerstring.= ' /';
                   8110:         }
                   8111:         $headerstring .= '>'."\n";
1.340     albertel 8112:     }
                   8113:     return $headerstring;
                   8114: }
                   8115: 
1.341     albertel 8116: =pod
                   8117: 
1.1064    raeburn  8118: =item * &print_suppression()
                   8119: 
                   8120: In course context returns css which causes the body to be blank when media="print",
                   8121: if printout generation is unavailable for the current resource.
                   8122: 
                   8123: This could be because:
                   8124: 
                   8125: (a) printstartdate is in the future
                   8126: 
                   8127: (b) printenddate is in the past
                   8128: 
                   8129: (c) there is an active exam block with "printout"
                   8130: functionality blocked
                   8131: 
                   8132: Users with pav, pfo or evb privileges are exempt.
                   8133: 
                   8134: Inputs: none
                   8135: 
                   8136: =cut
                   8137: 
                   8138: 
                   8139: sub print_suppression {
                   8140:     my $noprint;
                   8141:     if ($env{'request.course.id'}) {
                   8142:         my $scope = $env{'request.course.id'};
                   8143:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8144:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8145:             return;
                   8146:         }
                   8147:         if ($env{'request.course.sec'} ne '') {
                   8148:             $scope .= "/$env{'request.course.sec'}";
                   8149:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8150:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8151:                 return;
1.1064    raeburn  8152:             }
                   8153:         }
                   8154:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8155:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8156:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8157:         if ($blocked) {
                   8158:             my $checkrole = "cm./$cdom/$cnum";
                   8159:             if ($env{'request.course.sec'} ne '') {
                   8160:                 $checkrole .= "/$env{'request.course.sec'}";
                   8161:             }
                   8162:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8163:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8164:                 $noprint = 1;
                   8165:             }
                   8166:         }
                   8167:         unless ($noprint) {
                   8168:             my $symb = &Apache::lonnet::symbread();
                   8169:             if ($symb ne '') {
                   8170:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8171:                 if (ref($navmap)) {
                   8172:                     my $res = $navmap->getBySymb($symb);
                   8173:                     if (ref($res)) {
                   8174:                         if (!$res->resprintable()) {
                   8175:                             $noprint = 1;
                   8176:                         }
                   8177:                     }
                   8178:                 }
                   8179:             }
                   8180:         }
                   8181:         if ($noprint) {
                   8182:             return <<"ENDSTYLE";
                   8183: <style type="text/css" media="print">
                   8184:     body { display:none }
                   8185: </style>
                   8186: ENDSTYLE
                   8187:         }
                   8188:     }
                   8189:     return;
                   8190: }
                   8191: 
                   8192: =pod
                   8193: 
1.341     albertel 8194: =item * &xml_begin()
                   8195: 
                   8196: Returns the needed doctype and <html>
                   8197: 
                   8198: Inputs: none
                   8199: 
                   8200: =cut
                   8201: 
                   8202: sub xml_begin {
1.1075.2.61  raeburn  8203:     my ($is_frameset) = @_;
1.341     albertel 8204:     my $output='';
                   8205: 
                   8206:     if ($env{'browser.mathml'}) {
                   8207: 	$output='<?xml version="1.0"?>'
                   8208:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8209: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8210:             
                   8211: #	    .'<!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">] >'
                   8212: 	    .'<!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">'
                   8213:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8214: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8215:     } elsif ($is_frameset) {
                   8216:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8217:                 '<html>'."\n";
1.341     albertel 8218:     } else {
1.1075.2.61  raeburn  8219: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8220:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8221:     }
                   8222:     return $output;
                   8223: }
1.340     albertel 8224: 
                   8225: =pod
                   8226: 
1.306     albertel 8227: =item * &start_page()
                   8228: 
                   8229: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8230: 
1.648     raeburn  8231: Inputs:
                   8232: 
                   8233: =over 4
                   8234: 
                   8235: $title - optional title for the page
                   8236: 
                   8237: $head_extra - optional extra HTML to incude inside the <head>
                   8238: 
                   8239: $args - additional optional args supported are:
                   8240: 
                   8241: =over 8
                   8242: 
                   8243:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8244:                                     arg on
1.814     bisitz   8245:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8246:              add_entries    -> additional attributes to add to the  <body>
                   8247:              domain         -> force to color decorate a page for a 
1.317     albertel 8248:                                     specific domain
1.648     raeburn  8249:              function       -> force usage of a specific rolish color
1.317     albertel 8250:                                     scheme
1.648     raeburn  8251:              redirect       -> see &headtag()
                   8252:              bgcolor        -> override the default page bg color
                   8253:              js_ready       -> return a string ready for being used in 
1.317     albertel 8254:                                     a javascript writeln
1.648     raeburn  8255:              html_encode    -> return a string ready for being used in 
1.320     albertel 8256:                                     a html attribute
1.648     raeburn  8257:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8258:                                     $forcereg arg
1.648     raeburn  8259:              frameset       -> if true will start with a <frameset>
1.330     albertel 8260:                                     rather than <body>
1.648     raeburn  8261:              skip_phases    -> hash ref of 
1.338     albertel 8262:                                     head -> skip the <html><head> generation
                   8263:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8264:              no_inline_link -> if true and in remote mode, don't show the
                   8265:                                     'Switch To Inline Menu' link
1.648     raeburn  8266:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8267:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8268:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8269:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8270:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8271:              group          -> includes the current group, if page is for a
                   8272:                                specific group
1.1075.2.133  raeburn  8273:              use_absolute   -> for request for external resource or syllabus, this
                   8274:                                will contain https://<hostname> if server uses
                   8275:                                https (as per hosts.tab), but request is for http
                   8276:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8277: 
1.648     raeburn  8278: =back
1.460     albertel 8279: 
1.648     raeburn  8280: =back
1.562     albertel 8281: 
1.306     albertel 8282: =cut
                   8283: 
                   8284: sub start_page {
1.309     albertel 8285:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8286:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8287: 
1.315     albertel 8288:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8289:     my ($result,@advtools);
1.964     droeschl 8290: 
1.338     albertel 8291:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8292:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8293:     }
                   8294:     
                   8295:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8296: 	if ($args->{'frameset'}) {
                   8297: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8298: 						$args->{'add_entries'});
                   8299: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8300:         } else {
                   8301:             $result .=
                   8302:                 &bodytag($title, 
                   8303:                          $args->{'function'},       $args->{'add_entries'},
                   8304:                          $args->{'only_body'},      $args->{'domain'},
                   8305:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8306:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8307:                          $args,                     \@advtools);
1.831     bisitz   8308:         }
1.330     albertel 8309:     }
1.338     albertel 8310: 
1.315     albertel 8311:     if ($args->{'js_ready'}) {
1.713     kaisler  8312: 		$result = &js_ready($result);
1.315     albertel 8313:     }
1.320     albertel 8314:     if ($args->{'html_encode'}) {
1.713     kaisler  8315: 		$result = &html_encode($result);
                   8316:     }
                   8317: 
1.813     bisitz   8318:     # Preparation for new and consistent functionlist at top of screen
                   8319:     # if ($args->{'functionlist'}) {
                   8320:     #            $result .= &build_functionlist();
                   8321:     #}
                   8322: 
1.964     droeschl 8323:     # Don't add anything more if only_body wanted or in const space
                   8324:     return $result if    $args->{'only_body'} 
                   8325:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8326: 
                   8327:     #Breadcrumbs
1.758     kaisler  8328:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8329: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8330: 		#if any br links exists, add them to the breadcrumbs
                   8331: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8332: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8333: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8334: 			}
                   8335: 		}
1.1075.2.19  raeburn  8336:                 # if @advtools array contains items add then to the breadcrumbs
                   8337:                 if (@advtools > 0) {
                   8338:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8339:                 }
1.1075.2.123  raeburn  8340:                 my $menulink;
                   8341:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8342:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8343:                     $menulink = 0;
                   8344:                 } else {
                   8345:                     undef($menulink);
                   8346:                 }
1.758     kaisler  8347: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8348: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8349: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8350: 		}else{
1.1075.2.123  raeburn  8351: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8352: 		}
1.1075.2.24  raeburn  8353:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8354:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8355:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8356:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8357:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8358:     }
1.315     albertel 8359:     return $result;
1.306     albertel 8360: }
                   8361: 
                   8362: sub end_page {
1.315     albertel 8363:     my ($args) = @_;
                   8364:     $env{'internal.end_page'}++;
1.330     albertel 8365:     my $result;
1.335     albertel 8366:     if ($args->{'discussion'}) {
                   8367: 	my ($target,$parser);
                   8368: 	if (ref($args->{'discussion'})) {
                   8369: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8370: 				$args->{'discussion'}{'parser'});
                   8371: 	}
                   8372: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8373:     }
1.330     albertel 8374:     if ($args->{'frameset'}) {
                   8375: 	$result .= '</frameset>';
                   8376:     } else {
1.635     raeburn  8377: 	$result .= &endbodytag($args);
1.330     albertel 8378:     }
1.1075.2.6  raeburn  8379:     unless ($args->{'notbody'}) {
                   8380:         $result .= "\n</html>";
                   8381:     }
1.330     albertel 8382: 
1.315     albertel 8383:     if ($args->{'js_ready'}) {
1.317     albertel 8384: 	$result = &js_ready($result);
1.315     albertel 8385:     }
1.335     albertel 8386: 
1.320     albertel 8387:     if ($args->{'html_encode'}) {
                   8388: 	$result = &html_encode($result);
                   8389:     }
1.335     albertel 8390: 
1.315     albertel 8391:     return $result;
                   8392: }
                   8393: 
1.1034    www      8394: sub wishlist_window {
                   8395:     return(<<'ENDWISHLIST');
1.1046    raeburn  8396: <script type="text/javascript">
1.1034    www      8397: // <![CDATA[
                   8398: // <!-- BEGIN LON-CAPA Internal
                   8399: function set_wishlistlink(title, path) {
                   8400:     if (!title) {
                   8401:         title = document.title;
                   8402:         title = title.replace(/^LON-CAPA /,'');
                   8403:     }
1.1075.2.65  raeburn  8404:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8405:     title = title.replace("'","\\\'");
1.1034    www      8406:     if (!path) {
                   8407:         path = location.pathname;
                   8408:     }
1.1075.2.65  raeburn  8409:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8410:     path = path.replace("'","\\\'");
1.1034    www      8411:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8412:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8413: }
                   8414: // END LON-CAPA Internal -->
                   8415: // ]]>
                   8416: </script>
                   8417: ENDWISHLIST
                   8418: }
                   8419: 
1.1030    www      8420: sub modal_window {
                   8421:     return(<<'ENDMODAL');
1.1046    raeburn  8422: <script type="text/javascript">
1.1030    www      8423: // <![CDATA[
                   8424: // <!-- BEGIN LON-CAPA Internal
                   8425: var modalWindow = {
                   8426: 	parent:"body",
                   8427: 	windowId:null,
                   8428: 	content:null,
                   8429: 	width:null,
                   8430: 	height:null,
                   8431: 	close:function()
                   8432: 	{
                   8433: 	        $(".LCmodal-window").remove();
                   8434: 	        $(".LCmodal-overlay").remove();
                   8435: 	},
                   8436: 	open:function()
                   8437: 	{
                   8438: 		var modal = "";
                   8439: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8440: 		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;\">";
                   8441: 		modal += this.content;
                   8442: 		modal += "</div>";	
                   8443: 
                   8444: 		$(this.parent).append(modal);
                   8445: 
                   8446: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8447: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8448: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8449: 	}
                   8450: };
1.1075.2.42  raeburn  8451: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8452: 	{
1.1075.2.119  raeburn  8453:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8454: 		modalWindow.windowId = "myModal";
                   8455: 		modalWindow.width = width;
                   8456: 		modalWindow.height = height;
1.1075.2.80  raeburn  8457: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8458: 		modalWindow.open();
1.1075.2.87  raeburn  8459: 	};
1.1030    www      8460: // END LON-CAPA Internal -->
                   8461: // ]]>
                   8462: </script>
                   8463: ENDMODAL
                   8464: }
                   8465: 
                   8466: sub modal_link {
1.1075.2.42  raeburn  8467:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8468:     unless ($width) { $width=480; }
                   8469:     unless ($height) { $height=400; }
1.1031    www      8470:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8471:     unless ($transparency) { $transparency='true'; }
                   8472: 
1.1074    raeburn  8473:     my $target_attr;
                   8474:     if (defined($target)) {
                   8475:         $target_attr = 'target="'.$target.'"';
                   8476:     }
                   8477:     return <<"ENDLINK";
1.1075.2.141.  .3(raebu 8478:20): <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8479: ENDLINK
1.1030    www      8480: }
                   8481: 
1.1032    www      8482: sub modal_adhoc_script {
                   8483:     my ($funcname,$width,$height,$content)=@_;
                   8484:     return (<<ENDADHOC);
1.1046    raeburn  8485: <script type="text/javascript">
1.1032    www      8486: // <![CDATA[
                   8487:         var $funcname = function()
                   8488:         {
                   8489:                 modalWindow.windowId = "myModal";
                   8490:                 modalWindow.width = $width;
                   8491:                 modalWindow.height = $height;
                   8492:                 modalWindow.content = '$content';
                   8493:                 modalWindow.open();
                   8494:         };  
                   8495: // ]]>
                   8496: </script>
                   8497: ENDADHOC
                   8498: }
                   8499: 
1.1041    www      8500: sub modal_adhoc_inner {
                   8501:     my ($funcname,$width,$height,$content)=@_;
                   8502:     my $innerwidth=$width-20;
                   8503:     $content=&js_ready(
1.1042    www      8504:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8505:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8506:                  $content.
1.1041    www      8507:                  &end_scrollbox().
1.1075.2.42  raeburn  8508:                  &end_page()
1.1041    www      8509:              );
                   8510:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8511: }
                   8512: 
                   8513: sub modal_adhoc_window {
                   8514:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8515:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8516:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8517: }
                   8518: 
                   8519: sub modal_adhoc_launch {
                   8520:     my ($funcname,$width,$height,$content)=@_;
                   8521:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8522: <script type="text/javascript">
                   8523: // <![CDATA[
                   8524: $funcname();
                   8525: // ]]>
                   8526: </script>
                   8527: ENDLAUNCH
                   8528: }
                   8529: 
                   8530: sub modal_adhoc_close {
                   8531:     return (<<ENDCLOSE);
                   8532: <script type="text/javascript">
                   8533: // <![CDATA[
                   8534: modalWindow.close();
                   8535: // ]]>
                   8536: </script>
                   8537: ENDCLOSE
                   8538: }
                   8539: 
1.1038    www      8540: sub togglebox_script {
                   8541:    return(<<ENDTOGGLE);
                   8542: <script type="text/javascript"> 
                   8543: // <![CDATA[
                   8544: function LCtoggleDisplay(id,hidetext,showtext) {
                   8545:    link = document.getElementById(id + "link").childNodes[0];
                   8546:    with (document.getElementById(id).style) {
                   8547:       if (display == "none" ) {
                   8548:           display = "inline";
                   8549:           link.nodeValue = hidetext;
                   8550:         } else {
                   8551:           display = "none";
                   8552:           link.nodeValue = showtext;
                   8553:        }
                   8554:    }
                   8555: }
                   8556: // ]]>
                   8557: </script>
                   8558: ENDTOGGLE
                   8559: }
                   8560: 
1.1039    www      8561: sub start_togglebox {
                   8562:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8563:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8564:     unless ($showtext) { $showtext=&mt('show'); }
                   8565:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8566:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8567:     return &start_data_table().
                   8568:            &start_data_table_header_row().
                   8569:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8570:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8571:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8572:            &end_data_table_header_row().
                   8573:            '<tr id="'.$id.'" style="display:none""><td>';
                   8574: }
                   8575: 
                   8576: sub end_togglebox {
                   8577:     return '</td></tr>'.&end_data_table();
                   8578: }
                   8579: 
1.1041    www      8580: sub LCprogressbar_script {
1.1075.2.130  raeburn  8581:    my ($id,$number_to_do)=@_;
                   8582:    if ($number_to_do) {
                   8583:        return(<<ENDPROGRESS);
1.1041    www      8584: <script type="text/javascript">
                   8585: // <![CDATA[
1.1045    www      8586: \$('#progressbar$id').progressbar({
1.1041    www      8587:   value: 0,
                   8588:   change: function(event, ui) {
                   8589:     var newVal = \$(this).progressbar('option', 'value');
                   8590:     \$('.pblabel', this).text(LCprogressTxt);
                   8591:   }
                   8592: });
                   8593: // ]]>
                   8594: </script>
                   8595: ENDPROGRESS
1.1075.2.130  raeburn  8596:    } else {
                   8597:        return(<<ENDPROGRESS);
                   8598: <script type="text/javascript">
                   8599: // <![CDATA[
                   8600: \$('#progressbar$id').progressbar({
                   8601:   value: false,
                   8602:   create: function(event, ui) {
                   8603:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8604:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8605:   }
                   8606: });
                   8607: // ]]>
                   8608: </script>
                   8609: ENDPROGRESS
                   8610:    }
1.1041    www      8611: }
                   8612: 
                   8613: sub LCprogressbarUpdate_script {
                   8614:    return(<<ENDPROGRESSUPDATE);
                   8615: <style type="text/css">
                   8616: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8617: .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      8618: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8619: </style>
                   8620: <script type="text/javascript">
                   8621: // <![CDATA[
1.1045    www      8622: var LCprogressTxt='---';
                   8623: 
1.1075.2.130  raeburn  8624: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8625:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8626:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8627:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8628:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8629:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8630:    } else {
                   8631:        \$('#progressbar'+id).progressbar('value',percent);
                   8632:    }
1.1041    www      8633: }
                   8634: // ]]>
                   8635: </script>
                   8636: ENDPROGRESSUPDATE
                   8637: }
                   8638: 
1.1042    www      8639: my $LClastpercent;
1.1045    www      8640: my $LCidcnt;
                   8641: my $LCcurrentid;
1.1042    www      8642: 
1.1041    www      8643: sub LCprogressbar {
1.1075.2.130  raeburn  8644:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8645:     $LClastpercent=0;
1.1045    www      8646:     $LCidcnt++;
                   8647:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8648:     my ($starting,$content);
                   8649:     if ($number_to_do) {
                   8650:         $starting=&mt('Starting');
                   8651:         $content=(<<ENDPROGBAR);
                   8652: $preamble
1.1045    www      8653:   <div id="progressbar$LCcurrentid">
1.1041    www      8654:     <span class="pblabel">$starting</span>
                   8655:   </div>
                   8656: ENDPROGBAR
1.1075.2.130  raeburn  8657:     } else {
                   8658:         $starting=&mt('Loading...');
                   8659:         $LClastpercent='false';
                   8660:         $content=(<<ENDPROGBAR);
                   8661: $preamble
                   8662:   <div id="progressbar$LCcurrentid">
                   8663:       <div class="progress-label">$starting</div>
                   8664:   </div>
                   8665: ENDPROGBAR
                   8666:     }
                   8667:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8668: }
                   8669: 
                   8670: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8671:     my ($r,$val,$text,$number_to_do)=@_;
                   8672:     if ($number_to_do) {
                   8673:         unless ($val) { 
                   8674:             if ($LClastpercent) {
                   8675:                 $val=$LClastpercent;
                   8676:             } else {
                   8677:                 $val=0;
                   8678:             }
                   8679:         }
                   8680:         if ($val<0) { $val=0; }
                   8681:         if ($val>100) { $val=0; }
                   8682:         $LClastpercent=$val;
                   8683:         unless ($text) { $text=$val.'%'; }
                   8684:     } else {
                   8685:         $val = 'false';
1.1042    www      8686:     }
1.1041    www      8687:     $text=&js_ready($text);
1.1044    www      8688:     &r_print($r,<<ENDUPDATE);
1.1041    www      8689: <script type="text/javascript">
                   8690: // <![CDATA[
1.1075.2.130  raeburn  8691: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8692: // ]]>
                   8693: </script>
                   8694: ENDUPDATE
1.1035    www      8695: }
                   8696: 
1.1042    www      8697: sub LCprogressbarClose {
                   8698:     my ($r)=@_;
                   8699:     $LClastpercent=0;
1.1044    www      8700:     &r_print($r,<<ENDCLOSE);
1.1042    www      8701: <script type="text/javascript">
                   8702: // <![CDATA[
1.1045    www      8703: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8704: // ]]>
                   8705: </script>
                   8706: ENDCLOSE
1.1044    www      8707: }
                   8708: 
                   8709: sub r_print {
                   8710:     my ($r,$to_print)=@_;
                   8711:     if ($r) {
                   8712:       $r->print($to_print);
                   8713:       $r->rflush();
                   8714:     } else {
                   8715:       print($to_print);
                   8716:     }
1.1042    www      8717: }
                   8718: 
1.320     albertel 8719: sub html_encode {
                   8720:     my ($result) = @_;
                   8721: 
1.322     albertel 8722:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8723:     
                   8724:     return $result;
                   8725: }
1.1044    www      8726: 
1.317     albertel 8727: sub js_ready {
                   8728:     my ($result) = @_;
                   8729: 
1.323     albertel 8730:     $result =~ s/[\n\r]/ /xmsg;
                   8731:     $result =~ s/\\/\\\\/xmsg;
                   8732:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8733:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8734:     
                   8735:     return $result;
                   8736: }
                   8737: 
1.315     albertel 8738: sub validate_page {
                   8739:     if (  exists($env{'internal.start_page'})
1.316     albertel 8740: 	  &&     $env{'internal.start_page'} > 1) {
                   8741: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8742: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8743: 				 $ENV{'request.filename'});
1.315     albertel 8744:     }
                   8745:     if (  exists($env{'internal.end_page'})
1.316     albertel 8746: 	  &&     $env{'internal.end_page'} > 1) {
                   8747: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8748: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8749: 				 $env{'request.filename'});
1.315     albertel 8750:     }
                   8751:     if (     exists($env{'internal.start_page'})
                   8752: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8753: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8754: 				 $env{'request.filename'});
1.315     albertel 8755:     }
                   8756:     if (   ! exists($env{'internal.start_page'})
                   8757: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8758: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8759: 				 $env{'request.filename'});
1.315     albertel 8760:     }
1.306     albertel 8761: }
1.315     albertel 8762: 
1.996     www      8763: 
                   8764: sub start_scrollbox {
1.1075.2.56  raeburn  8765:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8766:     unless ($outerwidth) { $outerwidth='520px'; }
                   8767:     unless ($width) { $width='500px'; }
                   8768:     unless ($height) { $height='200px'; }
1.1075    raeburn  8769:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8770:     if ($id ne '') {
1.1075.2.42  raeburn  8771:         $table_id = ' id="table_'.$id.'"';
                   8772:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8773:     }
1.1075    raeburn  8774:     if ($bgcolor ne '') {
                   8775:         $tdcol = "background-color: $bgcolor;";
                   8776:     }
1.1075.2.42  raeburn  8777:     my $nicescroll_js;
                   8778:     if ($env{'browser.mobile'}) {
                   8779:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8780:     }
1.1075    raeburn  8781:     return <<"END";
1.1075.2.42  raeburn  8782: $nicescroll_js
                   8783: 
                   8784: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8785: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8786: END
1.996     www      8787: }
                   8788: 
                   8789: sub end_scrollbox {
1.1036    www      8790:     return '</div></td></tr></table>';
1.996     www      8791: }
                   8792: 
1.1075.2.42  raeburn  8793: sub nicescroll_javascript {
                   8794:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8795:     my %options;
                   8796:     if (ref($cursor) eq 'HASH') {
                   8797:         %options = %{$cursor};
                   8798:     }
                   8799:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8800:         $options{'railalign'} = 'left';
                   8801:     }
                   8802:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8803:         my $function  = &get_users_function();
                   8804:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8805:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8806:             $options{'cursorcolor'} = '#00F';
                   8807:         }
                   8808:     }
                   8809:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8810:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8811:             $options{'cursoropacity'}='1.0';
                   8812:         }
                   8813:     } else {
                   8814:         $options{'cursoropacity'}='1.0';
                   8815:     }
                   8816:     if ($options{'cursorfixedheight'} eq 'none') {
                   8817:         delete($options{'cursorfixedheight'});
                   8818:     } else {
                   8819:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8820:     }
                   8821:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8822:         delete($options{'railoffset'});
                   8823:     }
                   8824:     my @niceoptions;
                   8825:     while (my($key,$value) = each(%options)) {
                   8826:         if ($value =~ /^\{.+\}$/) {
                   8827:             push(@niceoptions,$key.':'.$value);
                   8828:         } else {
                   8829:             push(@niceoptions,$key.':"'.$value.'"');
                   8830:         }
                   8831:     }
                   8832:     my $nicescroll_js = '
                   8833: $(document).ready(
                   8834:       function() {
                   8835:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8836:       }
                   8837: );
                   8838: ';
                   8839:     if ($framecheck) {
                   8840:         $nicescroll_js .= '
                   8841: function expand_div(caller) {
                   8842:     if (top === self) {
                   8843:         document.getElementById("'.$id.'").style.width = "auto";
                   8844:         document.getElementById("'.$id.'").style.height = "auto";
                   8845:     } else {
                   8846:         try {
                   8847:             if (parent.frames) {
                   8848:                 if (parent.frames.length > 1) {
                   8849:                     var framesrc = parent.frames[1].location.href;
                   8850:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8851:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8852:                         document.getElementById("'.$id.'").style.width = "auto";
                   8853:                         document.getElementById("'.$id.'").style.height = "auto";
                   8854:                     }
                   8855:                 }
                   8856:             }
                   8857:         } catch (e) {
                   8858:             return;
                   8859:         }
                   8860:     }
                   8861:     return;
                   8862: }
                   8863: ';
                   8864:     }
                   8865:     if ($needjsready) {
                   8866:         $nicescroll_js = '
                   8867: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8868:     } else {
                   8869:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8870:     }
                   8871:     return $nicescroll_js;
                   8872: }
                   8873: 
1.318     albertel 8874: sub simple_error_page {
1.1075.2.49  raeburn  8875:     my ($r,$title,$msg,$args) = @_;
                   8876:     if (ref($args) eq 'HASH') {
                   8877:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8878:     } else {
                   8879:         $msg = &mt($msg);
                   8880:     }
                   8881: 
1.318     albertel 8882:     my $page =
                   8883: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8884: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8885: 	&Apache::loncommon::end_page();
                   8886:     if (ref($r)) {
                   8887: 	$r->print($page);
1.327     albertel 8888: 	return;
1.318     albertel 8889:     }
                   8890:     return $page;
                   8891: }
1.347     albertel 8892: 
                   8893: {
1.610     albertel 8894:     my @row_count;
1.961     onken    8895: 
                   8896:     sub start_data_table_count {
                   8897:         unshift(@row_count, 0);
                   8898:         return;
                   8899:     }
                   8900: 
                   8901:     sub end_data_table_count {
                   8902:         shift(@row_count);
                   8903:         return;
                   8904:     }
                   8905: 
1.347     albertel 8906:     sub start_data_table {
1.1018    raeburn  8907: 	my ($add_class,$id) = @_;
1.422     albertel 8908: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8909:         my $table_id;
                   8910:         if (defined($id)) {
                   8911:             $table_id = ' id="'.$id.'"';
                   8912:         }
1.961     onken    8913: 	&start_data_table_count();
1.1018    raeburn  8914: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8915:     }
                   8916: 
                   8917:     sub end_data_table {
1.961     onken    8918: 	&end_data_table_count();
1.389     albertel 8919: 	return '</table>'."\n";;
1.347     albertel 8920:     }
                   8921: 
                   8922:     sub start_data_table_row {
1.974     wenzelju 8923: 	my ($add_class, $id) = @_;
1.610     albertel 8924: 	$row_count[0]++;
                   8925: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8926: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8927:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8928:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8929:     }
1.471     banghart 8930:     
                   8931:     sub continue_data_table_row {
1.974     wenzelju 8932: 	my ($add_class, $id) = @_;
1.610     albertel 8933: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8934: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8935:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8936:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8937:     }
1.347     albertel 8938: 
                   8939:     sub end_data_table_row {
1.389     albertel 8940: 	return '</tr>'."\n";;
1.347     albertel 8941:     }
1.367     www      8942: 
1.421     albertel 8943:     sub start_data_table_empty_row {
1.707     bisitz   8944: #	$row_count[0]++;
1.421     albertel 8945: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8946:     }
                   8947: 
                   8948:     sub end_data_table_empty_row {
                   8949: 	return '</tr>'."\n";;
                   8950:     }
                   8951: 
1.367     www      8952:     sub start_data_table_header_row {
1.389     albertel 8953: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8954:     }
                   8955: 
                   8956:     sub end_data_table_header_row {
1.389     albertel 8957: 	return '</tr>'."\n";;
1.367     www      8958:     }
1.890     droeschl 8959: 
                   8960:     sub data_table_caption {
                   8961:         my $caption = shift;
                   8962:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8963:     }
1.347     albertel 8964: }
                   8965: 
1.548     albertel 8966: =pod
                   8967: 
                   8968: =item * &inhibit_menu_check($arg)
                   8969: 
                   8970: Checks for a inhibitmenu state and generates output to preserve it
                   8971: 
                   8972: Inputs:         $arg - can be any of
                   8973:                      - undef - in which case the return value is a string 
                   8974:                                to add  into arguments list of a uri
                   8975:                      - 'input' - in which case the return value is a HTML
                   8976:                                  <form> <input> field of type hidden to
                   8977:                                  preserve the value
                   8978:                      - a url - in which case the return value is the url with
                   8979:                                the neccesary cgi args added to preserve the
                   8980:                                inhibitmenu state
                   8981:                      - a ref to a url - no return value, but the string is
                   8982:                                         updated to include the neccessary cgi
                   8983:                                         args to preserve the inhibitmenu state
                   8984: 
                   8985: =cut
                   8986: 
                   8987: sub inhibit_menu_check {
                   8988:     my ($arg) = @_;
                   8989:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8990:     if ($arg eq 'input') {
                   8991: 	if ($env{'form.inhibitmenu'}) {
                   8992: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8993: 	} else {
                   8994: 	    return
                   8995: 	}
                   8996:     }
                   8997:     if ($env{'form.inhibitmenu'}) {
                   8998: 	if (ref($arg)) {
                   8999: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9000: 	} elsif ($arg eq '') {
                   9001: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9002: 	} else {
                   9003: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9004: 	}
                   9005:     }
                   9006:     if (!ref($arg)) {
                   9007: 	return $arg;
                   9008:     }
                   9009: }
                   9010: 
1.251     albertel 9011: ###############################################
1.182     matthew  9012: 
                   9013: =pod
                   9014: 
1.549     albertel 9015: =back
                   9016: 
                   9017: =head1 User Information Routines
                   9018: 
                   9019: =over 4
                   9020: 
1.405     albertel 9021: =item * &get_users_function()
1.182     matthew  9022: 
                   9023: Used by &bodytag to determine the current users primary role.
                   9024: Returns either 'student','coordinator','admin', or 'author'.
                   9025: 
                   9026: =cut
                   9027: 
                   9028: ###############################################
                   9029: sub get_users_function {
1.815     tempelho 9030:     my $function = 'norole';
1.818     tempelho 9031:     if ($env{'request.role'}=~/^(st)/) {
                   9032:         $function='student';
                   9033:     }
1.907     raeburn  9034:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9035:         $function='coordinator';
                   9036:     }
1.258     albertel 9037:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9038:         $function='admin';
                   9039:     }
1.826     bisitz   9040:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9041:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9042:         $function='author';
                   9043:     }
                   9044:     return $function;
1.54      www      9045: }
1.99      www      9046: 
                   9047: ###############################################
                   9048: 
1.233     raeburn  9049: =pod
                   9050: 
1.821     raeburn  9051: =item * &show_course()
                   9052: 
                   9053: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9054: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9055: 
                   9056: Inputs:
                   9057: None
                   9058: 
                   9059: Outputs:
                   9060: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9061: 
                   9062: =cut
                   9063: 
                   9064: ###############################################
                   9065: sub show_course {
                   9066:     my $course = !$env{'user.adv'};
                   9067:     if (!$env{'user.adv'}) {
                   9068:         foreach my $env (keys(%env)) {
                   9069:             next if ($env !~ m/^user\.priv\./);
                   9070:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9071:                 $course = 0;
                   9072:                 last;
                   9073:             }
                   9074:         }
                   9075:     }
                   9076:     return $course;
                   9077: }
                   9078: 
                   9079: ###############################################
                   9080: 
                   9081: =pod
                   9082: 
1.542     raeburn  9083: =item * &check_user_status()
1.274     raeburn  9084: 
                   9085: Determines current status of supplied role for a
                   9086: specific user. Roles can be active, previous or future.
                   9087: 
                   9088: Inputs: 
                   9089: user's domain, user's username, course's domain,
1.375     raeburn  9090: course's number, optional section ID.
1.274     raeburn  9091: 
                   9092: Outputs:
                   9093: role status: active, previous or future. 
                   9094: 
                   9095: =cut
                   9096: 
                   9097: sub check_user_status {
1.412     raeburn  9098:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9099:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9100:     my @uroles = keys(%userinfo);
1.274     raeburn  9101:     my $srchstr;
                   9102:     my $active_chk = 'none';
1.412     raeburn  9103:     my $now = time;
1.274     raeburn  9104:     if (@uroles > 0) {
1.908     raeburn  9105:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9106:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9107:         } else {
1.412     raeburn  9108:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9109:         }
                   9110:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9111:             my $role_end = 0;
                   9112:             my $role_start = 0;
                   9113:             $active_chk = 'active';
1.412     raeburn  9114:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9115:                 $role_end = $1;
                   9116:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9117:                     $role_start = $1;
1.274     raeburn  9118:                 }
                   9119:             }
                   9120:             if ($role_start > 0) {
1.412     raeburn  9121:                 if ($now < $role_start) {
1.274     raeburn  9122:                     $active_chk = 'future';
                   9123:                 }
                   9124:             }
                   9125:             if ($role_end > 0) {
1.412     raeburn  9126:                 if ($now > $role_end) {
1.274     raeburn  9127:                     $active_chk = 'previous';
                   9128:                 }
                   9129:             }
                   9130:         }
                   9131:     }
                   9132:     return $active_chk;
                   9133: }
                   9134: 
                   9135: ###############################################
                   9136: 
                   9137: =pod
                   9138: 
1.405     albertel 9139: =item * &get_sections()
1.233     raeburn  9140: 
                   9141: Determines all the sections for a course including
                   9142: sections with students and sections containing other roles.
1.419     raeburn  9143: Incoming parameters: 
                   9144: 
                   9145: 1. domain
                   9146: 2. course number 
                   9147: 3. reference to array containing roles for which sections should 
                   9148: be gathered (optional).
                   9149: 4. reference to array containing status types for which sections 
                   9150: should be gathered (optional).
                   9151: 
                   9152: If the third argument is undefined, sections are gathered for any role. 
                   9153: If the fourth argument is undefined, sections are gathered for any status.
                   9154: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9155:  
1.374     raeburn  9156: Returns section hash (keys are section IDs, values are
                   9157: number of users in each section), subject to the
1.419     raeburn  9158: optional roles filter, optional status filter 
1.233     raeburn  9159: 
                   9160: =cut
                   9161: 
                   9162: ###############################################
                   9163: sub get_sections {
1.419     raeburn  9164:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9165:     if (!defined($cdom) || !defined($cnum)) {
                   9166:         my $cid =  $env{'request.course.id'};
                   9167: 
                   9168: 	return if (!defined($cid));
                   9169: 
                   9170:         $cdom = $env{'course.'.$cid.'.domain'};
                   9171:         $cnum = $env{'course.'.$cid.'.num'};
                   9172:     }
                   9173: 
                   9174:     my %sectioncount;
1.419     raeburn  9175:     my $now = time;
1.240     albertel 9176: 
1.1075.2.33  raeburn  9177:     my $check_students = 1;
                   9178:     my $only_students = 0;
                   9179:     if (ref($possible_roles) eq 'ARRAY') {
                   9180:         if (grep(/^st$/,@{$possible_roles})) {
                   9181:             if (@{$possible_roles} == 1) {
                   9182:                 $only_students = 1;
                   9183:             }
                   9184:         } else {
                   9185:             $check_students = 0;
                   9186:         }
                   9187:     }
                   9188: 
                   9189:     if ($check_students) {
1.276     albertel 9190: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9191: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9192: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9193:         my $start_index = &Apache::loncoursedata::CL_START();
                   9194:         my $end_index = &Apache::loncoursedata::CL_END();
                   9195:         my $status;
1.366     albertel 9196: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9197: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9198: 				                     $data->[$status_index],
                   9199:                                                      $data->[$start_index],
                   9200:                                                      $data->[$end_index]);
                   9201:             if ($stu_status eq 'Active') {
                   9202:                 $status = 'active';
                   9203:             } elsif ($end < $now) {
                   9204:                 $status = 'previous';
                   9205:             } elsif ($start > $now) {
                   9206:                 $status = 'future';
                   9207:             } 
                   9208: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9209:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9210:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9211: 		    $sectioncount{$section}++;
                   9212:                 }
1.240     albertel 9213: 	    }
                   9214: 	}
                   9215:     }
1.1075.2.33  raeburn  9216:     if ($only_students) {
                   9217:         return %sectioncount;
                   9218:     }
1.240     albertel 9219:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9220:     foreach my $user (sort(keys(%courseroles))) {
                   9221: 	if ($user !~ /^(\w{2})/) { next; }
                   9222: 	my ($role) = ($user =~ /^(\w{2})/);
                   9223: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9224: 	my ($section,$status);
1.240     albertel 9225: 	if ($role eq 'cr' &&
                   9226: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9227: 	    $section=$1;
                   9228: 	}
                   9229: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9230: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9231:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9232:         if ($end == -1 && $start == -1) {
                   9233:             next; #deleted role
                   9234:         }
                   9235:         if (!defined($possible_status)) { 
                   9236:             $sectioncount{$section}++;
                   9237:         } else {
                   9238:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9239:                 $status = 'active';
                   9240:             } elsif ($end < $now) {
                   9241:                 $status = 'future';
                   9242:             } elsif ($start > $now) {
                   9243:                 $status = 'previous';
                   9244:             }
                   9245:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9246:                 $sectioncount{$section}++;
                   9247:             }
                   9248:         }
1.233     raeburn  9249:     }
1.366     albertel 9250:     return %sectioncount;
1.233     raeburn  9251: }
                   9252: 
1.274     raeburn  9253: ###############################################
1.294     raeburn  9254: 
                   9255: =pod
1.405     albertel 9256: 
                   9257: =item * &get_course_users()
                   9258: 
1.275     raeburn  9259: Retrieves usernames:domains for users in the specified course
                   9260: with specific role(s), and access status. 
                   9261: 
                   9262: Incoming parameters:
1.277     albertel 9263: 1. course domain
                   9264: 2. course number
                   9265: 3. access status: users must have - either active, 
1.275     raeburn  9266: previous, future, or all.
1.277     albertel 9267: 4. reference to array of permissible roles
1.288     raeburn  9268: 5. reference to array of section restrictions (optional)
                   9269: 6. reference to results object (hash of hashes).
                   9270: 7. reference to optional userdata hash
1.609     raeburn  9271: 8. reference to optional statushash
1.630     raeburn  9272: 9. flag if privileged users (except those set to unhide in
                   9273:    course settings) should be excluded    
1.609     raeburn  9274: Keys of top level results hash are roles.
1.275     raeburn  9275: Keys of inner hashes are username:domain, with 
                   9276: values set to access type.
1.288     raeburn  9277: Optional userdata hash returns an array with arguments in the 
                   9278: same order as loncoursedata::get_classlist() for student data.
                   9279: 
1.609     raeburn  9280: Optional statushash returns
                   9281: 
1.288     raeburn  9282: Entries for end, start, section and status are blank because
                   9283: of the possibility of multiple values for non-student roles.
                   9284: 
1.275     raeburn  9285: =cut
1.405     albertel 9286: 
1.275     raeburn  9287: ###############################################
1.405     albertel 9288: 
1.275     raeburn  9289: sub get_course_users {
1.630     raeburn  9290:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9291:     my %idx = ();
1.419     raeburn  9292:     my %seclists;
1.288     raeburn  9293: 
                   9294:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9295:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9296:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9297:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9298:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9299:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9300:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9301:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9302: 
1.290     albertel 9303:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9304:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9305:         my $now = time;
1.277     albertel 9306:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9307:             my $match = 0;
1.412     raeburn  9308:             my $secmatch = 0;
1.419     raeburn  9309:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9310:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9311:             if ($section eq '') {
                   9312:                 $section = 'none';
                   9313:             }
1.291     albertel 9314:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9315:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9316:                     $secmatch = 1;
                   9317:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9318:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9319:                         $secmatch = 1;
                   9320:                     }
                   9321:                 } else {  
1.419     raeburn  9322: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9323: 		        $secmatch = 1;
                   9324:                     }
1.290     albertel 9325: 		}
1.412     raeburn  9326:                 if (!$secmatch) {
                   9327:                     next;
                   9328:                 }
1.419     raeburn  9329:             }
1.275     raeburn  9330:             if (defined($$types{'active'})) {
1.288     raeburn  9331:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9332:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9333:                     $match = 1;
1.275     raeburn  9334:                 }
                   9335:             }
                   9336:             if (defined($$types{'previous'})) {
1.609     raeburn  9337:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9338:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9339:                     $match = 1;
1.275     raeburn  9340:                 }
                   9341:             }
                   9342:             if (defined($$types{'future'})) {
1.609     raeburn  9343:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9344:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9345:                     $match = 1;
1.275     raeburn  9346:                 }
                   9347:             }
1.609     raeburn  9348:             if ($match) {
                   9349:                 push(@{$seclists{$student}},$section);
                   9350:                 if (ref($userdata) eq 'HASH') {
                   9351:                     $$userdata{$student} = $$classlist{$student};
                   9352:                 }
                   9353:                 if (ref($statushash) eq 'HASH') {
                   9354:                     $statushash->{$student}{'st'}{$section} = $status;
                   9355:                 }
1.288     raeburn  9356:             }
1.275     raeburn  9357:         }
                   9358:     }
1.412     raeburn  9359:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9360:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9361:         my $now = time;
1.609     raeburn  9362:         my %displaystatus = ( previous => 'Expired',
                   9363:                               active   => 'Active',
                   9364:                               future   => 'Future',
                   9365:                             );
1.1075.2.36  raeburn  9366:         my (%nothide,@possdoms);
1.630     raeburn  9367:         if ($hidepriv) {
                   9368:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9369:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9370:                 if ($user !~ /:/) {
                   9371:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9372:                 } else {
                   9373:                     $nothide{$user} = 1;
                   9374:                 }
                   9375:             }
1.1075.2.36  raeburn  9376:             my @possdoms = ($cdom);
                   9377:             if ($coursehash{'checkforpriv'}) {
                   9378:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9379:             }
1.630     raeburn  9380:         }
1.439     raeburn  9381:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9382:             my $match = 0;
1.412     raeburn  9383:             my $secmatch = 0;
1.439     raeburn  9384:             my $status;
1.412     raeburn  9385:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9386:             $user =~ s/:$//;
1.439     raeburn  9387:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9388:             if ($end == -1 || $start == -1) {
                   9389:                 next;
                   9390:             }
                   9391:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9392:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9393:                 my ($uname,$udom) = split(/:/,$user);
                   9394:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9395:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9396:                         $secmatch = 1;
                   9397:                     } elsif ($usec eq '') {
1.420     albertel 9398:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9399:                             $secmatch = 1;
                   9400:                         }
                   9401:                     } else {
                   9402:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9403:                             $secmatch = 1;
                   9404:                         }
                   9405:                     }
                   9406:                     if (!$secmatch) {
                   9407:                         next;
                   9408:                     }
1.288     raeburn  9409:                 }
1.419     raeburn  9410:                 if ($usec eq '') {
                   9411:                     $usec = 'none';
                   9412:                 }
1.275     raeburn  9413:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9414:                     if ($hidepriv) {
1.1075.2.36  raeburn  9415:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9416:                             (!$nothide{$uname.':'.$udom})) {
                   9417:                             next;
                   9418:                         }
                   9419:                     }
1.503     raeburn  9420:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9421:                         $status = 'previous';
                   9422:                     } elsif ($start > $now) {
                   9423:                         $status = 'future';
                   9424:                     } else {
                   9425:                         $status = 'active';
                   9426:                     }
1.277     albertel 9427:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9428:                         if ($status eq $type) {
1.420     albertel 9429:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9430:                                 push(@{$$users{$role}{$user}},$type);
                   9431:                             }
1.288     raeburn  9432:                             $match = 1;
                   9433:                         }
                   9434:                     }
1.419     raeburn  9435:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9436:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9437: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9438:                         }
1.420     albertel 9439:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9440:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9441:                         }
1.609     raeburn  9442:                         if (ref($statushash) eq 'HASH') {
                   9443:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9444:                         }
1.275     raeburn  9445:                     }
                   9446:                 }
                   9447:             }
                   9448:         }
1.290     albertel 9449:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9450:             if ((defined($cdom)) && (defined($cnum))) {
                   9451:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9452:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9453:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9454:                     next if ($owner eq '');
                   9455:                     my ($ownername,$ownerdom);
                   9456:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9457:                         $ownername = $1;
                   9458:                         $ownerdom = $2;
                   9459:                     } else {
                   9460:                         $ownername = $owner;
                   9461:                         $ownerdom = $cdom;
                   9462:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9463:                     }
                   9464:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9465:                     if (defined($userdata) && 
1.609     raeburn  9466: 			!exists($$userdata{$owner})) {
                   9467: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9468:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9469:                             push(@{$seclists{$owner}},'none');
                   9470:                         }
                   9471:                         if (ref($statushash) eq 'HASH') {
                   9472:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9473:                         }
1.290     albertel 9474: 		    }
1.279     raeburn  9475:                 }
                   9476:             }
                   9477:         }
1.419     raeburn  9478:         foreach my $user (keys(%seclists)) {
                   9479:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9480:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9481:         }
1.275     raeburn  9482:     }
                   9483:     return;
                   9484: }
                   9485: 
1.288     raeburn  9486: sub get_user_info {
                   9487:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9488:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9489: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9490:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9491:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9492:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9493:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9494:     return;
                   9495: }
1.275     raeburn  9496: 
1.472     raeburn  9497: ###############################################
                   9498: 
                   9499: =pod
                   9500: 
                   9501: =item * &get_user_quota()
                   9502: 
1.1075.2.41  raeburn  9503: Retrieves quota assigned for storage of user files.
                   9504: Default is to report quota for portfolio files.
1.472     raeburn  9505: 
                   9506: Incoming parameters:
                   9507: 1. user's username
                   9508: 2. user's domain
1.1075.2.41  raeburn  9509: 3. quota name - portfolio, author, or course
                   9510:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9511: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9512:    course
1.472     raeburn  9513: 
                   9514: Returns:
1.1075.2.58  raeburn  9515: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9516: 2. (Optional) Type of setting: custom or default
                   9517:    (individually assigned or default for user's 
                   9518:    institutional status).
                   9519: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9520:    or student - types as defined in localenroll::inst_usertypes 
                   9521:    for user's domain, which determines default quota for user.
                   9522: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9523: 
                   9524: If a value has been stored in the user's environment, 
1.536     raeburn  9525: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9526: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9527: 
                   9528: =cut
                   9529: 
                   9530: ###############################################
                   9531: 
                   9532: 
                   9533: sub get_user_quota {
1.1075.2.42  raeburn  9534:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9535:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9536:     if (!defined($udom)) {
                   9537:         $udom = $env{'user.domain'};
                   9538:     }
                   9539:     if (!defined($uname)) {
                   9540:         $uname = $env{'user.name'};
                   9541:     }
                   9542:     if (($udom eq '' || $uname eq '') ||
                   9543:         ($udom eq 'public') && ($uname eq 'public')) {
                   9544:         $quota = 0;
1.536     raeburn  9545:         $quotatype = 'default';
                   9546:         $defquota = 0; 
1.472     raeburn  9547:     } else {
1.536     raeburn  9548:         my $inststatus;
1.1075.2.41  raeburn  9549:         if ($quotaname eq 'course') {
                   9550:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9551:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9552:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9553:             } else {
                   9554:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9555:                 $quota = $cenv{'internal.uploadquota'};
                   9556:             }
1.536     raeburn  9557:         } else {
1.1075.2.41  raeburn  9558:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9559:                 if ($quotaname eq 'author') {
                   9560:                     $quota = $env{'environment.authorquota'};
                   9561:                 } else {
                   9562:                     $quota = $env{'environment.portfolioquota'};
                   9563:                 }
                   9564:                 $inststatus = $env{'environment.inststatus'};
                   9565:             } else {
                   9566:                 my %userenv = 
                   9567:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9568:                                          'authorquota','inststatus'],$udom,$uname);
                   9569:                 my ($tmp) = keys(%userenv);
                   9570:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9571:                     if ($quotaname eq 'author') {
                   9572:                         $quota = $userenv{'authorquota'};
                   9573:                     } else {
                   9574:                         $quota = $userenv{'portfolioquota'};
                   9575:                     }
                   9576:                     $inststatus = $userenv{'inststatus'};
                   9577:                 } else {
                   9578:                     undef(%userenv);
                   9579:                 }
                   9580:             }
                   9581:         }
                   9582:         if ($quota eq '' || wantarray) {
                   9583:             if ($quotaname eq 'course') {
                   9584:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9585:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9586:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9587:                     $defquota = $domdefs{$crstype.'quota'};
                   9588:                 }
                   9589:                 if ($defquota eq '') {
                   9590:                     $defquota = 500;
                   9591:                 }
1.1075.2.41  raeburn  9592:             } else {
                   9593:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9594:             }
                   9595:             if ($quota eq '') {
                   9596:                 $quota = $defquota;
                   9597:                 $quotatype = 'default';
                   9598:             } else {
                   9599:                 $quotatype = 'custom';
                   9600:             }
1.472     raeburn  9601:         }
                   9602:     }
1.536     raeburn  9603:     if (wantarray) {
                   9604:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9605:     } else {
                   9606:         return $quota;
                   9607:     }
1.472     raeburn  9608: }
                   9609: 
                   9610: ###############################################
                   9611: 
                   9612: =pod
                   9613: 
                   9614: =item * &default_quota()
                   9615: 
1.536     raeburn  9616: Retrieves default quota assigned for storage of user portfolio files,
                   9617: given an (optional) user's institutional status.
1.472     raeburn  9618: 
                   9619: Incoming parameters:
1.1075.2.42  raeburn  9620: 
1.472     raeburn  9621: 1. domain
1.536     raeburn  9622: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9623:    status types (e.g., faculty, staff, student etc.)
                   9624:    which apply to the user for whom the default is being retrieved.
                   9625:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9626:    default quota will be returned.
                   9627: 3.  quota name - portfolio, author, or course
                   9628:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9629: 
                   9630: Returns:
1.1075.2.42  raeburn  9631: 
1.1075.2.58  raeburn  9632: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9633: 2. (Optional) institutional type which determined the value of the
                   9634:    default quota.
1.472     raeburn  9635: 
                   9636: If a value has been stored in the domain's configuration db,
                   9637: it will return that, otherwise it returns 20 (for backwards 
                   9638: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9639: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9640: 
1.536     raeburn  9641: If the user's status includes multiple types (e.g., staff and student),
                   9642: the largest default quota which applies to the user determines the
                   9643: default quota returned.
                   9644: 
1.472     raeburn  9645: =cut
                   9646: 
                   9647: ###############################################
                   9648: 
                   9649: 
                   9650: sub default_quota {
1.1075.2.41  raeburn  9651:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9652:     my ($defquota,$settingstatus);
                   9653:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9654:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9655:     my $key = 'defaultquota';
                   9656:     if ($quotaname eq 'author') {
                   9657:         $key = 'authorquota';
                   9658:     }
1.622     raeburn  9659:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9660:         if ($inststatus ne '') {
1.765     raeburn  9661:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9662:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9663:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9664:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9665:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9666:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9667:                             $settingstatus = $item;
1.1075.2.41  raeburn  9668:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9669:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9670:                             $settingstatus = $item;
                   9671:                         }
                   9672:                     }
1.1075.2.41  raeburn  9673:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9674:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9675:                         if ($defquota eq '') {
                   9676:                             $defquota = $quotahash{'quotas'}{$item};
                   9677:                             $settingstatus = $item;
                   9678:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9679:                             $defquota = $quotahash{'quotas'}{$item};
                   9680:                             $settingstatus = $item;
                   9681:                         }
1.536     raeburn  9682:                     }
                   9683:                 }
                   9684:             }
                   9685:         }
                   9686:         if ($defquota eq '') {
1.1075.2.41  raeburn  9687:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9688:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9689:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9690:                 $defquota = $quotahash{'quotas'}{'default'};
                   9691:             }
1.536     raeburn  9692:             $settingstatus = 'default';
1.1075.2.42  raeburn  9693:             if ($defquota eq '') {
                   9694:                 if ($quotaname eq 'author') {
                   9695:                     $defquota = 500;
                   9696:                 }
                   9697:             }
1.536     raeburn  9698:         }
                   9699:     } else {
                   9700:         $settingstatus = 'default';
1.1075.2.41  raeburn  9701:         if ($quotaname eq 'author') {
                   9702:             $defquota = 500;
                   9703:         } else {
                   9704:             $defquota = 20;
                   9705:         }
1.536     raeburn  9706:     }
                   9707:     if (wantarray) {
                   9708:         return ($defquota,$settingstatus);
1.472     raeburn  9709:     } else {
1.536     raeburn  9710:         return $defquota;
1.472     raeburn  9711:     }
                   9712: }
                   9713: 
1.1075.2.41  raeburn  9714: ###############################################
                   9715: 
                   9716: =pod
                   9717: 
1.1075.2.42  raeburn  9718: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9719: 
                   9720: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9721: of existing file within authoring space will cause quota for the authoring
                   9722: space to be exceeded.
                   9723: 
                   9724: Same, if upload of a file directly to a course/community via Course Editor
                   9725: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9726: 
1.1075.2.61  raeburn  9727: Inputs: 7 
1.1075.2.42  raeburn  9728: 1. username or coursenum
1.1075.2.41  raeburn  9729: 2. domain
1.1075.2.42  raeburn  9730: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9731: 4. filename of file for which action is being requested
                   9732: 5. filesize (kB) of file
                   9733: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9734: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9735: 
                   9736: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9737:          otherwise return null.
                   9738: 
1.1075.2.42  raeburn  9739: =back
                   9740: 
1.1075.2.41  raeburn  9741: =cut
                   9742: 
1.1075.2.42  raeburn  9743: sub excess_filesize_warning {
1.1075.2.59  raeburn  9744:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9745:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9746:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9747:     if ($context eq 'author') {
                   9748:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9749:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9750:     } else {
                   9751:         foreach my $subdir ('docs','supplemental') {
                   9752:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9753:         }
                   9754:     }
1.1075.2.41  raeburn  9755:     $disk_quota = int($disk_quota * 1000);
                   9756:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9757:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9758:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9759:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9760:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9761:                             $disk_quota,$current_disk_usage).
                   9762:                '</p>';
                   9763:     }
                   9764:     return;
                   9765: }
                   9766: 
                   9767: ###############################################
                   9768: 
                   9769: 
1.384     raeburn  9770: sub get_secgrprole_info {
                   9771:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9772:     my %sections_count = &get_sections($cdom,$cnum);
                   9773:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9774:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9775:     my @groups = sort(keys(%curr_groups));
                   9776:     my $allroles = [];
                   9777:     my $rolehash;
                   9778:     my $accesshash = {
                   9779:                      active => 'Currently has access',
                   9780:                      future => 'Will have future access',
                   9781:                      previous => 'Previously had access',
                   9782:                   };
                   9783:     if ($needroles) {
                   9784:         $rolehash = {'all' => 'all'};
1.385     albertel 9785:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9786: 	if (&Apache::lonnet::error(%user_roles)) {
                   9787: 	    undef(%user_roles);
                   9788: 	}
                   9789:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9790:             my ($role)=split(/\:/,$item,2);
                   9791:             if ($role eq 'cr') { next; }
                   9792:             if ($role =~ /^cr/) {
                   9793:                 $$rolehash{$role} = (split('/',$role))[3];
                   9794:             } else {
                   9795:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9796:             }
                   9797:         }
                   9798:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9799:             push(@{$allroles},$key);
                   9800:         }
                   9801:         push (@{$allroles},'st');
                   9802:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9803:     }
                   9804:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9805: }
                   9806: 
1.555     raeburn  9807: sub user_picker {
1.1075.2.127  raeburn  9808:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9809:     my $currdom = $dom;
1.1075.2.114  raeburn  9810:     my @alldoms = &Apache::lonnet::all_domains();
                   9811:     if (@alldoms == 1) {
                   9812:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9813:                                                ['directorysrch'],$alldoms[0]);
                   9814:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9815:         my $showdom = $domdesc;
                   9816:         if ($showdom eq '') {
                   9817:             $showdom = $dom;
                   9818:         }
                   9819:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9820:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9821:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9822:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9823:             }
                   9824:         }
                   9825:     }
1.555     raeburn  9826:     my %curr_selected = (
                   9827:                         srchin => 'dom',
1.580     raeburn  9828:                         srchby => 'lastname',
1.555     raeburn  9829:                       );
                   9830:     my $srchterm;
1.625     raeburn  9831:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9832:         if ($srch->{'srchby'} ne '') {
                   9833:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9834:         }
                   9835:         if ($srch->{'srchin'} ne '') {
                   9836:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9837:         }
                   9838:         if ($srch->{'srchtype'} ne '') {
                   9839:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9840:         }
                   9841:         if ($srch->{'srchdomain'} ne '') {
                   9842:             $currdom = $srch->{'srchdomain'};
                   9843:         }
                   9844:         $srchterm = $srch->{'srchterm'};
                   9845:     }
1.1075.2.98  raeburn  9846:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9847:                     'usr'       => 'Search criteria',
1.563     raeburn  9848:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9849:                     'uname'     => 'username',
                   9850:                     'lastname'  => 'last name',
1.555     raeburn  9851:                     'lastfirst' => 'last name, first name',
1.558     albertel 9852:                     'crs'       => 'in this course',
1.576     raeburn  9853:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9854:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9855:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9856:                     'exact'     => 'is',
                   9857:                     'contains'  => 'contains',
1.569     raeburn  9858:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9859:                                        );
                   9860:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9861:                     'youm'      => "You must include some text to search for.",
                   9862:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9863:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9864:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9865:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9866:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9867:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9868:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9869:                                        );
1.1075.2.98  raeburn  9870:     &html_escape(\%html_lt);
                   9871:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9872:     my $domform;
1.1075.2.126  raeburn  9873:     my $allow_blank = 1;
1.1075.2.115  raeburn  9874:     if ($fixeddom) {
1.1075.2.126  raeburn  9875:         $allow_blank = 0;
                   9876:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9877:     } else {
1.1075.2.126  raeburn  9878:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9879:     }
1.563     raeburn  9880:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9881: 
                   9882:     my @srchins = ('crs','dom','alc','instd');
                   9883: 
                   9884:     foreach my $option (@srchins) {
                   9885:         # FIXME 'alc' option unavailable until 
                   9886:         #       loncreateuser::print_user_query_page()
                   9887:         #       has been completed.
                   9888:         next if ($option eq 'alc');
1.880     raeburn  9889:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9890:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9891:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9892:         if ($curr_selected{'srchin'} eq $option) {
                   9893:             $srchinsel .= ' 
1.1075.2.98  raeburn  9894:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9895:         } else {
                   9896:             $srchinsel .= '
1.1075.2.98  raeburn  9897:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9898:         }
1.555     raeburn  9899:     }
1.563     raeburn  9900:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9901: 
                   9902:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9903:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9904:         if ($curr_selected{'srchby'} eq $option) {
                   9905:             $srchbysel .= '
1.1075.2.98  raeburn  9906:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9907:         } else {
                   9908:             $srchbysel .= '
1.1075.2.98  raeburn  9909:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9910:          }
                   9911:     }
                   9912:     $srchbysel .= "\n  </select>\n";
                   9913: 
                   9914:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9915:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9916:         if ($curr_selected{'srchtype'} eq $option) {
                   9917:             $srchtypesel .= '
1.1075.2.98  raeburn  9918:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9919:         } else {
                   9920:             $srchtypesel .= '
1.1075.2.98  raeburn  9921:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9922:         }
                   9923:     }
                   9924:     $srchtypesel .= "\n  </select>\n";
                   9925: 
1.558     albertel 9926:     my ($newuserscript,$new_user_create);
1.994     raeburn  9927:     my $context_dom = $env{'request.role.domain'};
                   9928:     if ($context eq 'requestcrs') {
                   9929:         if ($env{'form.coursedom'} ne '') { 
                   9930:             $context_dom = $env{'form.coursedom'};
                   9931:         }
                   9932:     }
1.556     raeburn  9933:     if ($forcenewuser) {
1.576     raeburn  9934:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9935:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9936:                 if ($cancreate) {
                   9937:                     $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>';
                   9938:                 } else {
1.799     bisitz   9939:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9940:                     my %usertypetext = (
                   9941:                         official   => 'institutional',
                   9942:                         unofficial => 'non-institutional',
                   9943:                     );
1.799     bisitz   9944:                     $new_user_create = '<p class="LC_warning">'
                   9945:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9946:                                       .' '
                   9947:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9948:                                           ,'<a href="'.$helplink.'">','</a>')
                   9949:                                       .'</p><br />';
1.627     raeburn  9950:                 }
1.576     raeburn  9951:             }
                   9952:         }
                   9953: 
1.556     raeburn  9954:         $newuserscript = <<"ENDSCRIPT";
                   9955: 
1.570     raeburn  9956: function setSearch(createnew,callingForm) {
1.556     raeburn  9957:     if (createnew == 1) {
1.570     raeburn  9958:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9959:             if (callingForm.srchby.options[i].value == 'uname') {
                   9960:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9961:             }
                   9962:         }
1.570     raeburn  9963:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9964:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9965: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9966:             }
                   9967:         }
1.570     raeburn  9968:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9969:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9970:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9971:             }
                   9972:         }
1.570     raeburn  9973:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9974:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9975:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9976:             }
                   9977:         }
                   9978:     }
                   9979: }
                   9980: ENDSCRIPT
1.558     albertel 9981: 
1.556     raeburn  9982:     }
                   9983: 
1.555     raeburn  9984:     my $output = <<"END_BLOCK";
1.556     raeburn  9985: <script type="text/javascript">
1.824     bisitz   9986: // <![CDATA[
1.570     raeburn  9987: function validateEntry(callingForm) {
1.558     albertel 9988: 
1.556     raeburn  9989:     var checkok = 1;
1.558     albertel 9990:     var srchin;
1.570     raeburn  9991:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9992: 	if ( callingForm.srchin[i].checked ) {
                   9993: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9994: 	}
                   9995:     }
                   9996: 
1.570     raeburn  9997:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9998:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9999:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10000:     var srchterm =  callingForm.srchterm.value;
                   10001:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10002:     var msg = "";
                   10003: 
                   10004:     if (srchterm == "") {
                   10005:         checkok = 0;
1.1075.2.98  raeburn  10006:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10007:     }
                   10008: 
1.569     raeburn  10009:     if (srchtype== 'begins') {
                   10010:         if (srchterm.length < 2) {
                   10011:             checkok = 0;
1.1075.2.98  raeburn  10012:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10013:         }
                   10014:     }
                   10015: 
1.556     raeburn  10016:     if (srchtype== 'contains') {
                   10017:         if (srchterm.length < 3) {
                   10018:             checkok = 0;
1.1075.2.98  raeburn  10019:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10020:         }
                   10021:     }
                   10022:     if (srchin == 'instd') {
                   10023:         if (srchdomain == '') {
                   10024:             checkok = 0;
1.1075.2.98  raeburn  10025:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10026:         }
                   10027:     }
                   10028:     if (srchin == 'dom') {
                   10029:         if (srchdomain == '') {
                   10030:             checkok = 0;
1.1075.2.98  raeburn  10031:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10032:         }
                   10033:     }
                   10034:     if (srchby == 'lastfirst') {
                   10035:         if (srchterm.indexOf(",") == -1) {
                   10036:             checkok = 0;
1.1075.2.98  raeburn  10037:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10038:         }
                   10039:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10040:             checkok = 0;
1.1075.2.98  raeburn  10041:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10042:         }
                   10043:     }
                   10044:     if (checkok == 0) {
1.1075.2.98  raeburn  10045:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10046:         return;
                   10047:     }
                   10048:     if (checkok == 1) {
1.570     raeburn  10049:         callingForm.submit();
1.556     raeburn  10050:     }
                   10051: }
                   10052: 
                   10053: $newuserscript
                   10054: 
1.824     bisitz   10055: // ]]>
1.556     raeburn  10056: </script>
1.558     albertel 10057: 
                   10058: $new_user_create
                   10059: 
1.555     raeburn  10060: END_BLOCK
1.558     albertel 10061: 
1.876     raeburn  10062:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10063:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10064:                $domform.
                   10065:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10066:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10067:                $srchbysel.
                   10068:                $srchtypesel. 
                   10069:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10070:                $srchinsel.
                   10071:                &Apache::lonhtmlcommon::row_closure(1). 
                   10072:                &Apache::lonhtmlcommon::end_pick_box().
                   10073:                '<br />';
1.1075.2.114  raeburn  10074:     return ($output,1);
1.555     raeburn  10075: }
                   10076: 
1.612     raeburn  10077: sub user_rule_check {
1.615     raeburn  10078:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10079:     my ($response,%inst_response);
1.612     raeburn  10080:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10081:         if (keys(%{$usershash}) > 1) {
                   10082:             my (%by_username,%by_id,%userdoms);
                   10083:             my $checkid;
1.612     raeburn  10084:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10085:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10086:                     $checkid = 1;
                   10087:                 }
                   10088:             }
                   10089:             foreach my $user (keys(%{$usershash})) {
                   10090:                 my ($uname,$udom) = split(/:/,$user);
                   10091:                 if ($checkid) {
                   10092:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10093:                         if ($usershash->{$user}->{'id'} ne '') {
                   10094:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10095:                             $userdoms{$udom} = 1;
                   10096:                             if (ref($inst_results) eq 'HASH') {
                   10097:                                 $inst_results->{$uname.':'.$udom} = {};
                   10098:                             }
                   10099:                         }
                   10100:                     }
                   10101:                 } else {
                   10102:                     $by_username{$udom}{$uname} = 1;
                   10103:                     $userdoms{$udom} = 1;
                   10104:                     if (ref($inst_results) eq 'HASH') {
                   10105:                         $inst_results->{$uname.':'.$udom} = {};
                   10106:                     }
                   10107:                 }
                   10108:             }
                   10109:             foreach my $udom (keys(%userdoms)) {
                   10110:                 if (!$got_rules->{$udom}) {
                   10111:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10112:                                                              ['usercreation'],$udom);
                   10113:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10114:                         foreach my $item ('username','id') {
                   10115:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10116:                                 $$curr_rules{$udom}{$item} =
                   10117:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10118:                             }
                   10119:                         }
                   10120:                     }
                   10121:                     $got_rules->{$udom} = 1;
                   10122:                 }
                   10123:             }
                   10124:             if ($checkid) {
                   10125:                 foreach my $udom (keys(%by_id)) {
                   10126:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10127:                     if ($outcome eq 'ok') {
                   10128:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10129:                             my $uname = $by_id{$udom}{$id};
                   10130:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10131:                         }
                   10132:                         if (ref($results) eq 'HASH') {
                   10133:                             foreach my $uname (keys(%{$results})) {
                   10134:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10135:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10136:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10137:                                 }
                   10138:                             }
                   10139:                         }
                   10140:                     }
1.612     raeburn  10141:                 }
1.615     raeburn  10142:             } else {
1.1075.2.99  raeburn  10143:                 foreach my $udom (keys(%by_username)) {
                   10144:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10145:                     if ($outcome eq 'ok') {
                   10146:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10147:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10148:                         }
                   10149:                         if (ref($results) eq 'HASH') {
                   10150:                             foreach my $uname (keys(%{$results})) {
                   10151:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10152:                             }
                   10153:                         }
                   10154:                     }
                   10155:                 }
1.612     raeburn  10156:             }
1.1075.2.99  raeburn  10157:         } elsif (keys(%{$usershash}) == 1) {
                   10158:             my $user = (keys(%{$usershash}))[0];
                   10159:             my ($uname,$udom) = split(/:/,$user);
                   10160:             if (($udom ne '') && ($uname ne '')) {
                   10161:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10162:                     if (ref($checks) eq 'HASH') {
                   10163:                         if (defined($checks->{'username'})) {
                   10164:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10165:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10166:                         } elsif (defined($checks->{'id'})) {
                   10167:                             if ($usershash->{$user}->{'id'} ne '') {
                   10168:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10169:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10170:                                                                   $usershash->{$user}->{'id'});
                   10171:                             } else {
                   10172:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10173:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10174:                             }
                   10175:                         }
                   10176:                     } else {
                   10177:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10178:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10179:                        return;
                   10180:                     }
                   10181:                     if (!$got_rules->{$udom}) {
                   10182:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10183:                                                                  ['usercreation'],$udom);
                   10184:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10185:                             foreach my $item ('username','id') {
                   10186:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10187:                                    $$curr_rules{$udom}{$item} =
                   10188:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10189:                                 }
                   10190:                             }
1.585     raeburn  10191:                         }
1.1075.2.99  raeburn  10192:                         $got_rules->{$udom} = 1;
1.585     raeburn  10193:                     }
                   10194:                 }
1.1075.2.99  raeburn  10195:             } else {
                   10196:                 return;
                   10197:             }
                   10198:         } else {
                   10199:             return;
                   10200:         }
                   10201:         foreach my $user (keys(%{$usershash})) {
                   10202:             my ($uname,$udom) = split(/:/,$user);
                   10203:             next if (($udom eq '') || ($uname eq ''));
                   10204:             my $id;
                   10205:             if (ref($inst_results) eq 'HASH') {
                   10206:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10207:                     $id = $inst_results->{$user}->{'id'};
                   10208:                 }
                   10209:             }
                   10210:             if ($id eq '') {
                   10211:                 if (ref($usershash->{$user})) {
                   10212:                     $id = $usershash->{$user}->{'id'};
                   10213:                 }
1.585     raeburn  10214:             }
1.612     raeburn  10215:             foreach my $item (keys(%{$checks})) {
                   10216:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10217:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10218:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10219:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10220:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10221:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10222:                                 if ($rule_check{$rule}) {
                   10223:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10224:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10225:                                         if (ref($inst_results) eq 'HASH') {
                   10226:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10227:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10228:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10229:                                                 } elsif ($item eq 'id') {
                   10230:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10231:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10232:                                                     }
1.615     raeburn  10233:                                                 }
1.612     raeburn  10234:                                             }
                   10235:                                         }
1.615     raeburn  10236:                                     }
                   10237:                                     last;
1.585     raeburn  10238:                                 }
                   10239:                             }
                   10240:                         }
                   10241:                     }
                   10242:                 }
                   10243:             }
                   10244:         }
                   10245:     }
1.612     raeburn  10246:     return;
                   10247: }
                   10248: 
                   10249: sub user_rule_formats {
                   10250:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10251:     my %text = ( 
                   10252:                  'username' => 'Usernames',
                   10253:                  'id'       => 'IDs',
                   10254:                );
                   10255:     my $output;
                   10256:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10257:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10258:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10259:             $output = '<br />'.
                   10260:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10261:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10262:                       ' <ul>';
1.612     raeburn  10263:             foreach my $rule (@{$ruleorder}) {
                   10264:                 if (ref($curr_rules) eq 'ARRAY') {
                   10265:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10266:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10267:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10268:                                         $rules->{$rule}{'desc'}.'</li>';
                   10269:                         }
                   10270:                     }
                   10271:                 }
                   10272:             }
                   10273:             $output .= '</ul>';
                   10274:         }
                   10275:     }
                   10276:     return $output;
                   10277: }
                   10278: 
                   10279: sub instrule_disallow_msg {
1.615     raeburn  10280:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10281:     my $response;
                   10282:     my %text = (
                   10283:                   item   => 'username',
                   10284:                   items  => 'usernames',
                   10285:                   match  => 'matches',
                   10286:                   do     => 'does',
                   10287:                   action => 'a username',
                   10288:                   one    => 'one',
                   10289:                );
                   10290:     if ($count > 1) {
                   10291:         $text{'item'} = 'usernames';
                   10292:         $text{'match'} ='match';
                   10293:         $text{'do'} = 'do';
                   10294:         $text{'action'} = 'usernames',
                   10295:         $text{'one'} = 'ones';
                   10296:     }
                   10297:     if ($checkitem eq 'id') {
                   10298:         $text{'items'} = 'IDs';
                   10299:         $text{'item'} = 'ID';
                   10300:         $text{'action'} = 'an ID';
1.615     raeburn  10301:         if ($count > 1) {
                   10302:             $text{'item'} = 'IDs';
                   10303:             $text{'action'} = 'IDs';
                   10304:         }
1.612     raeburn  10305:     }
1.674     bisitz   10306:     $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  10307:     if ($mode eq 'upload') {
                   10308:         if ($checkitem eq 'username') {
                   10309:             $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'}.");
                   10310:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10311:             $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  10312:         }
1.669     raeburn  10313:     } elsif ($mode eq 'selfcreate') {
                   10314:         if ($checkitem eq 'id') {
                   10315:             $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.");
                   10316:         }
1.615     raeburn  10317:     } else {
                   10318:         if ($checkitem eq 'username') {
                   10319:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10320:         } elsif ($checkitem eq 'id') {
                   10321:             $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.");
                   10322:         }
1.612     raeburn  10323:     }
                   10324:     return $response;
1.585     raeburn  10325: }
                   10326: 
1.624     raeburn  10327: sub personal_data_fieldtitles {
                   10328:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10329:                         id => 'Student/Employee ID',
                   10330:                         permanentemail => 'E-mail address',
                   10331:                         lastname => 'Last Name',
                   10332:                         firstname => 'First Name',
                   10333:                         middlename => 'Middle Name',
                   10334:                         generation => 'Generation',
                   10335:                         gen => 'Generation',
1.765     raeburn  10336:                         inststatus => 'Affiliation',
1.624     raeburn  10337:                    );
                   10338:     return %fieldtitles;
                   10339: }
                   10340: 
1.642     raeburn  10341: sub sorted_inst_types {
                   10342:     my ($dom) = @_;
1.1075.2.70  raeburn  10343:     my ($usertypes,$order);
                   10344:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10345:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10346:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10347:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10348:     } else {
                   10349:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10350:     }
1.642     raeburn  10351:     my $othertitle = &mt('All users');
                   10352:     if ($env{'request.course.id'}) {
1.668     raeburn  10353:         $othertitle  = &mt('Any users');
1.642     raeburn  10354:     }
                   10355:     my @types;
                   10356:     if (ref($order) eq 'ARRAY') {
                   10357:         @types = @{$order};
                   10358:     }
                   10359:     if (@types == 0) {
                   10360:         if (ref($usertypes) eq 'HASH') {
                   10361:             @types = sort(keys(%{$usertypes}));
                   10362:         }
                   10363:     }
                   10364:     if (keys(%{$usertypes}) > 0) {
                   10365:         $othertitle = &mt('Other users');
                   10366:     }
                   10367:     return ($othertitle,$usertypes,\@types);
                   10368: }
                   10369: 
1.645     raeburn  10370: sub get_institutional_codes {
                   10371:     my ($settings,$allcourses,$LC_code) = @_;
                   10372: # Get complete list of course sections to update
                   10373:     my @currsections = ();
                   10374:     my @currxlists = ();
                   10375:     my $coursecode = $$settings{'internal.coursecode'};
                   10376: 
                   10377:     if ($$settings{'internal.sectionnums'} ne '') {
                   10378:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10379:     }
                   10380: 
                   10381:     if ($$settings{'internal.crosslistings'} ne '') {
                   10382:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10383:     }
                   10384: 
                   10385:     if (@currxlists > 0) {
                   10386:         foreach (@currxlists) {
                   10387:             if (m/^([^:]+):(\w*)$/) {
                   10388:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10389:                     push(@{$allcourses},$1);
1.645     raeburn  10390:                     $$LC_code{$1} = $2;
                   10391:                 }
                   10392:             }
                   10393:         }
                   10394:     }
                   10395:  
                   10396:     if (@currsections > 0) {
                   10397:         foreach (@currsections) {
                   10398:             if (m/^(\w+):(\w*)$/) {
                   10399:                 my $sec = $coursecode.$1;
                   10400:                 my $lc_sec = $2;
                   10401:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10402:                     push(@{$allcourses},$sec);
1.645     raeburn  10403:                     $$LC_code{$sec} = $lc_sec;
                   10404:                 }
                   10405:             }
                   10406:         }
                   10407:     }
                   10408:     return;
                   10409: }
                   10410: 
1.971     raeburn  10411: sub get_standard_codeitems {
                   10412:     return ('Year','Semester','Department','Number','Section');
                   10413: }
                   10414: 
1.112     bowersj2 10415: =pod
                   10416: 
1.780     raeburn  10417: =head1 Slot Helpers
                   10418: 
                   10419: =over 4
                   10420: 
                   10421: =item * sorted_slots()
                   10422: 
1.1040    raeburn  10423: Sorts an array of slot names in order of an optional sort key,
                   10424: default sort is by slot start time (earliest first). 
1.780     raeburn  10425: 
                   10426: Inputs:
                   10427: 
                   10428: =over 4
                   10429: 
                   10430: slotsarr  - Reference to array of unsorted slot names.
                   10431: 
                   10432: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10433: 
1.1040    raeburn  10434: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10435: 
1.549     albertel 10436: =back
                   10437: 
1.780     raeburn  10438: Returns:
                   10439: 
                   10440: =over 4
                   10441: 
1.1040    raeburn  10442: sorted   - An array of slot names sorted by a specified sort key 
                   10443:            (default sort key is start time of the slot).
1.780     raeburn  10444: 
                   10445: =back
                   10446: 
                   10447: =cut
                   10448: 
                   10449: 
                   10450: sub sorted_slots {
1.1040    raeburn  10451:     my ($slotsarr,$slots,$sortkey) = @_;
                   10452:     if ($sortkey eq '') {
                   10453:         $sortkey = 'starttime';
                   10454:     }
1.780     raeburn  10455:     my @sorted;
                   10456:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10457:         @sorted =
                   10458:             sort {
                   10459:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10460:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10461:                      }
                   10462:                      if (ref($slots->{$a})) { return -1;}
                   10463:                      if (ref($slots->{$b})) { return 1;}
                   10464:                      return 0;
                   10465:                  } @{$slotsarr};
                   10466:     }
                   10467:     return @sorted;
                   10468: }
                   10469: 
1.1040    raeburn  10470: =pod
                   10471: 
                   10472: =item * get_future_slots()
                   10473: 
                   10474: Inputs:
                   10475: 
                   10476: =over 4
                   10477: 
                   10478: cnum - course number
                   10479: 
                   10480: cdom - course domain
                   10481: 
                   10482: now - current UNIX time
                   10483: 
                   10484: symb - optional symb
                   10485: 
                   10486: =back
                   10487: 
                   10488: Returns:
                   10489: 
                   10490: =over 4
                   10491: 
                   10492: sorted_reservable - ref to array of student_schedulable slots currently 
                   10493:                     reservable, ordered by end date of reservation period.
                   10494: 
                   10495: reservable_now - ref to hash of student_schedulable slots currently
                   10496:                  reservable.
                   10497: 
                   10498:     Keys in inner hash are:
                   10499:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10500:     (b) endreserve: end date of reservation period.
                   10501:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10502:         selected.
1.1040    raeburn  10503: 
                   10504: sorted_future - ref to array of student_schedulable slots reservable in
                   10505:                 the future, ordered by start date of reservation period.
                   10506: 
                   10507: future_reservable - ref to hash of student_schedulable slots reservable
                   10508:                     in the future.
                   10509: 
                   10510:     Keys in inner hash are:
                   10511:     (a) symb: either blank or symb to which slot use is restricted.
                   10512:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10513:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10514:         selected.
1.1040    raeburn  10515: 
                   10516: =back
                   10517: 
                   10518: =cut
                   10519: 
                   10520: sub get_future_slots {
                   10521:     my ($cnum,$cdom,$now,$symb) = @_;
                   10522:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10523:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10524:     foreach my $slot (keys(%slots)) {
                   10525:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10526:         if ($symb) {
                   10527:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10528:                      ($slots{$slot}->{'symb'} ne $symb));
                   10529:         }
                   10530:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10531:             ($slots{$slot}->{'endtime'} > $now)) {
                   10532:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10533:                 my $userallowed = 0;
                   10534:                 if ($slots{$slot}->{'allowedsections'}) {
                   10535:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10536:                     if (!defined($env{'request.role.sec'})
                   10537:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10538:                         $userallowed=1;
                   10539:                     } else {
                   10540:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10541:                             $userallowed=1;
                   10542:                         }
                   10543:                     }
                   10544:                     unless ($userallowed) {
                   10545:                         if (defined($env{'request.course.groups'})) {
                   10546:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10547:                             foreach my $group (@groups) {
                   10548:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10549:                                     $userallowed=1;
                   10550:                                     last;
                   10551:                                 }
                   10552:                             }
                   10553:                         }
                   10554:                     }
                   10555:                 }
                   10556:                 if ($slots{$slot}->{'allowedusers'}) {
                   10557:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10558:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10559:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10560:                         $userallowed = 1;
                   10561:                     }
                   10562:                 }
                   10563:                 next unless($userallowed);
                   10564:             }
                   10565:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10566:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10567:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10568:             my $uniqueperiod;
                   10569:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10570:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10571:             }
1.1040    raeburn  10572:             if (($startreserve < $now) &&
                   10573:                 (!$endreserve || $endreserve > $now)) {
                   10574:                 my $lastres = $endreserve;
                   10575:                 if (!$lastres) {
                   10576:                     $lastres = $slots{$slot}->{'starttime'};
                   10577:                 }
                   10578:                 $reservable_now{$slot} = {
                   10579:                                            symb       => $symb,
1.1075.2.104  raeburn  10580:                                            endreserve => $lastres,
                   10581:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10582:                                          };
                   10583:             } elsif (($startreserve > $now) &&
                   10584:                      (!$endreserve || $endreserve > $startreserve)) {
                   10585:                 $future_reservable{$slot} = {
                   10586:                                               symb         => $symb,
1.1075.2.104  raeburn  10587:                                               startreserve => $startreserve,
                   10588:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10589:                                             };
                   10590:             }
                   10591:         }
                   10592:     }
                   10593:     my @unsorted_reservable = keys(%reservable_now);
                   10594:     if (@unsorted_reservable > 0) {
                   10595:         @sorted_reservable = 
                   10596:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10597:     }
                   10598:     my @unsorted_future = keys(%future_reservable);
                   10599:     if (@unsorted_future > 0) {
                   10600:         @sorted_future =
                   10601:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10602:     }
                   10603:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10604: }
1.780     raeburn  10605: 
                   10606: =pod
                   10607: 
1.1057    foxr     10608: =back
                   10609: 
1.549     albertel 10610: =head1 HTTP Helpers
                   10611: 
                   10612: =over 4
                   10613: 
1.648     raeburn  10614: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10615: 
1.258     albertel 10616: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10617: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10618: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10619: 
                   10620: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10621: $possible_names is an ref to an array of form element names.  As an example:
                   10622: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10623: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10624: 
                   10625: =cut
1.1       albertel 10626: 
1.6       albertel 10627: sub get_unprocessed_cgi {
1.25      albertel 10628:   my ($query,$possible_names)= @_;
1.26      matthew  10629:   # $Apache::lonxml::debug=1;
1.356     albertel 10630:   foreach my $pair (split(/&/,$query)) {
                   10631:     my ($name, $value) = split(/=/,$pair);
1.369     www      10632:     $name = &unescape($name);
1.25      albertel 10633:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10634:       $value =~ tr/+/ /;
                   10635:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10636:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10637:     }
1.16      harris41 10638:   }
1.6       albertel 10639: }
                   10640: 
1.112     bowersj2 10641: =pod
                   10642: 
1.648     raeburn  10643: =item * &cacheheader() 
1.112     bowersj2 10644: 
                   10645: returns cache-controlling header code
                   10646: 
                   10647: =cut
                   10648: 
1.7       albertel 10649: sub cacheheader {
1.258     albertel 10650:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10651:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10652:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10653:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10654:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10655:     return $output;
1.7       albertel 10656: }
                   10657: 
1.112     bowersj2 10658: =pod
                   10659: 
1.648     raeburn  10660: =item * &no_cache($r) 
1.112     bowersj2 10661: 
                   10662: specifies header code to not have cache
                   10663: 
                   10664: =cut
                   10665: 
1.9       albertel 10666: sub no_cache {
1.216     albertel 10667:     my ($r) = @_;
                   10668:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10669: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10670:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10671:     $r->no_cache(1);
                   10672:     $r->header_out("Expires" => $date);
                   10673:     $r->header_out("Pragma" => "no-cache");
1.123     www      10674: }
                   10675: 
                   10676: sub content_type {
1.181     albertel 10677:     my ($r,$type,$charset) = @_;
1.299     foxr     10678:     if ($r) {
                   10679: 	#  Note that printout.pl calls this with undef for $r.
                   10680: 	&no_cache($r);
                   10681:     }
1.258     albertel 10682:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10683:     unless ($charset) {
                   10684: 	$charset=&Apache::lonlocal::current_encoding;
                   10685:     }
                   10686:     if ($charset) { $type.='; charset='.$charset; }
                   10687:     if ($r) {
                   10688: 	$r->content_type($type);
                   10689:     } else {
                   10690: 	print("Content-type: $type\n\n");
                   10691:     }
1.9       albertel 10692: }
1.25      albertel 10693: 
1.112     bowersj2 10694: =pod
                   10695: 
1.648     raeburn  10696: =item * &add_to_env($name,$value) 
1.112     bowersj2 10697: 
1.258     albertel 10698: adds $name to the %env hash with value
1.112     bowersj2 10699: $value, if $name already exists, the entry is converted to an array
                   10700: reference and $value is added to the array.
                   10701: 
                   10702: =cut
                   10703: 
1.25      albertel 10704: sub add_to_env {
                   10705:   my ($name,$value)=@_;
1.258     albertel 10706:   if (defined($env{$name})) {
                   10707:     if (ref($env{$name})) {
1.25      albertel 10708:       #already have multiple values
1.258     albertel 10709:       push(@{ $env{$name} },$value);
1.25      albertel 10710:     } else {
                   10711:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10712:       my $first=$env{$name};
                   10713:       undef($env{$name});
                   10714:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10715:     }
                   10716:   } else {
1.258     albertel 10717:     $env{$name}=$value;
1.25      albertel 10718:   }
1.31      albertel 10719: }
1.149     albertel 10720: 
                   10721: =pod
                   10722: 
1.648     raeburn  10723: =item * &get_env_multiple($name) 
1.149     albertel 10724: 
1.258     albertel 10725: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10726: values may be defined and end up as an array ref.
                   10727: 
                   10728: returns an array of values
                   10729: 
                   10730: =cut
                   10731: 
                   10732: sub get_env_multiple {
                   10733:     my ($name) = @_;
                   10734:     my @values;
1.258     albertel 10735:     if (defined($env{$name})) {
1.149     albertel 10736:         # exists is it an array
1.258     albertel 10737:         if (ref($env{$name})) {
                   10738:             @values=@{ $env{$name} };
1.149     albertel 10739:         } else {
1.258     albertel 10740:             $values[0]=$env{$name};
1.149     albertel 10741:         }
                   10742:     }
                   10743:     return(@values);
                   10744: }
                   10745: 
1.660     raeburn  10746: sub ask_for_embedded_content {
                   10747:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10748:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10749:         %currsubfile,%unused,$rem);
1.1071    raeburn  10750:     my $counter = 0;
                   10751:     my $numnew = 0;
1.987     raeburn  10752:     my $numremref = 0;
                   10753:     my $numinvalid = 0;
                   10754:     my $numpathchg = 0;
                   10755:     my $numexisting = 0;
1.1071    raeburn  10756:     my $numunused = 0;
                   10757:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10758:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10759:     my $heading = &mt('Upload embedded files');
                   10760:     my $buttontext = &mt('Upload');
                   10761: 
1.1075.2.11  raeburn  10762:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10763:         if ($actionurl eq '/adm/dependencies') {
                   10764:             $navmap = Apache::lonnavmaps::navmap->new();
                   10765:         }
                   10766:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10767:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10768:     }
1.1075.2.35  raeburn  10769:     if (($actionurl eq '/adm/portfolio') ||
                   10770:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10771:         my $current_path='/';
                   10772:         if ($env{'form.currentpath'}) {
                   10773:             $current_path = $env{'form.currentpath'};
                   10774:         }
                   10775:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10776:             $udom = $cdom;
                   10777:             $uname = $cnum;
1.984     raeburn  10778:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10779:         } else {
                   10780:             $udom = $env{'user.domain'};
                   10781:             $uname = $env{'user.name'};
                   10782:             $url = '/userfiles/portfolio';
                   10783:         }
1.987     raeburn  10784:         $toplevel = $url.'/';
1.984     raeburn  10785:         $url .= $current_path;
                   10786:         $getpropath = 1;
1.987     raeburn  10787:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10788:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10789:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10790:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10791:         $toplevel = $url;
1.984     raeburn  10792:         if ($rest ne '') {
1.987     raeburn  10793:             $url .= $rest;
                   10794:         }
                   10795:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10796:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10797:             $url = $args->{'docs_url'};
                   10798:             $toplevel = $url;
1.1075.2.11  raeburn  10799:             if ($args->{'context'} eq 'paste') {
                   10800:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10801:                 ($path) =
                   10802:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10803:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10804:                 $fileloc =~ s{^/}{};
                   10805:             }
1.1071    raeburn  10806:         }
                   10807:     } elsif ($actionurl eq '/adm/dependencies') {
                   10808:         if ($env{'request.course.id'} ne '') {
                   10809:             if (ref($args) eq 'HASH') {
                   10810:                 $url = $args->{'docs_url'};
                   10811:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10812:                 $toplevel = $url;
                   10813:                 unless ($toplevel =~ m{^/}) {
                   10814:                     $toplevel = "/$url";
                   10815:                 }
1.1075.2.11  raeburn  10816:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10817:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10818:                     $path = $1;
                   10819:                 } else {
                   10820:                     ($path) =
                   10821:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10822:                 }
1.1075.2.79  raeburn  10823:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10824:                     $fileloc = $toplevel;
                   10825:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10826:                     my ($udom,$uname,$fname) =
                   10827:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10828:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10829:                 } else {
                   10830:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10831:                 }
1.1071    raeburn  10832:                 $fileloc =~ s{^/}{};
                   10833:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10834:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10835:             }
1.987     raeburn  10836:         }
1.1075.2.35  raeburn  10837:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10838:         $udom = $cdom;
                   10839:         $uname = $cnum;
                   10840:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10841:         $toplevel = $url;
                   10842:         $path = $url;
                   10843:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10844:         $fileloc =~ s{^/}{};
                   10845:     }
                   10846:     foreach my $file (keys(%{$allfiles})) {
                   10847:         my $embed_file;
                   10848:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10849:             $embed_file = $1;
                   10850:         } else {
                   10851:             $embed_file = $file;
                   10852:         }
1.1075.2.55  raeburn  10853:         my ($absolutepath,$cleaned_file);
                   10854:         if ($embed_file =~ m{^\w+://}) {
                   10855:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10856:             $newfiles{$cleaned_file} = 1;
                   10857:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10858:         } else {
1.1075.2.55  raeburn  10859:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10860:             if ($embed_file =~ m{^/}) {
                   10861:                 $absolutepath = $embed_file;
                   10862:             }
1.1075.2.47  raeburn  10863:             if ($cleaned_file =~ m{/}) {
                   10864:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10865:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10866:                 my $item = $fname;
                   10867:                 if ($path ne '') {
                   10868:                     $item = $path.'/'.$fname;
                   10869:                     $subdependencies{$path}{$fname} = 1;
                   10870:                 } else {
                   10871:                     $dependencies{$item} = 1;
                   10872:                 }
                   10873:                 if ($absolutepath) {
                   10874:                     $mapping{$item} = $absolutepath;
                   10875:                 } else {
                   10876:                     $mapping{$item} = $embed_file;
                   10877:                 }
                   10878:             } else {
                   10879:                 $dependencies{$embed_file} = 1;
                   10880:                 if ($absolutepath) {
1.1075.2.47  raeburn  10881:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10882:                 } else {
1.1075.2.47  raeburn  10883:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10884:                 }
                   10885:             }
1.984     raeburn  10886:         }
                   10887:     }
1.1071    raeburn  10888:     my $dirptr = 16384;
1.984     raeburn  10889:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10890:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10891:         if (($actionurl eq '/adm/portfolio') ||
                   10892:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10893:             my ($sublistref,$listerror) =
                   10894:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10895:             if (ref($sublistref) eq 'ARRAY') {
                   10896:                 foreach my $line (@{$sublistref}) {
                   10897:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10898:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10899:                 }
1.984     raeburn  10900:             }
1.987     raeburn  10901:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10902:             if (opendir(my $dir,$url.'/'.$path)) {
                   10903:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10904:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10905:             }
1.1075.2.11  raeburn  10906:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10907:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10908:                   ($args->{'context'} eq 'paste')) ||
                   10909:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10910:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10911:                 my $dir;
                   10912:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10913:                     $dir = $fileloc;
                   10914:                 } else {
                   10915:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10916:                 }
1.1071    raeburn  10917:                 if ($dir ne '') {
                   10918:                     my ($sublistref,$listerror) =
                   10919:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10920:                     if (ref($sublistref) eq 'ARRAY') {
                   10921:                         foreach my $line (@{$sublistref}) {
                   10922:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10923:                                 undef,$mtime)=split(/\&/,$line,12);
                   10924:                             unless (($testdir&$dirptr) ||
                   10925:                                     ($file_name =~ /^\.\.?$/)) {
                   10926:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10927:                             }
                   10928:                         }
                   10929:                     }
                   10930:                 }
1.984     raeburn  10931:             }
                   10932:         }
                   10933:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10934:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10935:                 my $item = $path.'/'.$file;
                   10936:                 unless ($mapping{$item} eq $item) {
                   10937:                     $pathchanges{$item} = 1;
                   10938:                 }
                   10939:                 $existing{$item} = 1;
                   10940:                 $numexisting ++;
                   10941:             } else {
                   10942:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10943:             }
                   10944:         }
1.1071    raeburn  10945:         if ($actionurl eq '/adm/dependencies') {
                   10946:             foreach my $path (keys(%currsubfile)) {
                   10947:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10948:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10949:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10950:                              next if (($rem ne '') &&
                   10951:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10952:                                        (ref($navmap) &&
                   10953:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10954:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10955:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10956:                              $unused{$path.'/'.$file} = 1; 
                   10957:                          }
                   10958:                     }
                   10959:                 }
                   10960:             }
                   10961:         }
1.984     raeburn  10962:     }
1.987     raeburn  10963:     my %currfile;
1.1075.2.35  raeburn  10964:     if (($actionurl eq '/adm/portfolio') ||
                   10965:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10966:         my ($dirlistref,$listerror) =
                   10967:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10968:         if (ref($dirlistref) eq 'ARRAY') {
                   10969:             foreach my $line (@{$dirlistref}) {
                   10970:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10971:                 $currfile{$file_name} = 1;
                   10972:             }
1.984     raeburn  10973:         }
1.987     raeburn  10974:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10975:         if (opendir(my $dir,$url)) {
1.987     raeburn  10976:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10977:             map {$currfile{$_} = 1;} @dir_list;
                   10978:         }
1.1075.2.11  raeburn  10979:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10980:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10981:               ($args->{'context'} eq 'paste')) ||
                   10982:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10983:         if ($env{'request.course.id'} ne '') {
                   10984:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10985:             if ($dir ne '') {
                   10986:                 my ($dirlistref,$listerror) =
                   10987:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10988:                 if (ref($dirlistref) eq 'ARRAY') {
                   10989:                     foreach my $line (@{$dirlistref}) {
                   10990:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10991:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10992:                         unless (($testdir&$dirptr) ||
                   10993:                                 ($file_name =~ /^\.\.?$/)) {
                   10994:                             $currfile{$file_name} = [$size,$mtime];
                   10995:                         }
                   10996:                     }
                   10997:                 }
                   10998:             }
                   10999:         }
1.984     raeburn  11000:     }
                   11001:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11002:         if (exists($currfile{$file})) {
1.987     raeburn  11003:             unless ($mapping{$file} eq $file) {
                   11004:                 $pathchanges{$file} = 1;
                   11005:             }
                   11006:             $existing{$file} = 1;
                   11007:             $numexisting ++;
                   11008:         } else {
1.984     raeburn  11009:             $newfiles{$file} = 1;
                   11010:         }
                   11011:     }
1.1071    raeburn  11012:     foreach my $file (keys(%currfile)) {
                   11013:         unless (($file eq $filename) ||
                   11014:                 ($file eq $filename.'.bak') ||
                   11015:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11016:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11017:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11018:                     next if (($rem ne '') &&
                   11019:                              (($env{"httpref.$rem".$file} ne '') ||
                   11020:                               (ref($navmap) &&
                   11021:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11022:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11023:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11024:                 }
1.1075.2.11  raeburn  11025:             }
1.1071    raeburn  11026:             $unused{$file} = 1;
                   11027:         }
                   11028:     }
1.1075.2.11  raeburn  11029:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11030:         ($args->{'context'} eq 'paste')) {
                   11031:         $counter = scalar(keys(%existing));
                   11032:         $numpathchg = scalar(keys(%pathchanges));
                   11033:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11034:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11035:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11036:         $counter = scalar(keys(%existing));
                   11037:         $numpathchg = scalar(keys(%pathchanges));
                   11038:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11039:     }
1.984     raeburn  11040:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11041:         if ($actionurl eq '/adm/dependencies') {
                   11042:             next if ($embed_file =~ m{^\w+://});
                   11043:         }
1.660     raeburn  11044:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11045:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11046:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11047:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11048:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11049:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11050:         }
1.1075.2.35  raeburn  11051:         $upload_output .= '</td>';
1.1071    raeburn  11052:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11053:             $upload_output.='<td align="right">'.
                   11054:                             '<span class="LC_info LC_fontsize_medium">'.
                   11055:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11056:             $numremref++;
1.660     raeburn  11057:         } elsif ($args->{'error_on_invalid_names'}
                   11058:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11059:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11060:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11061:             $numinvalid++;
1.660     raeburn  11062:         } else {
1.1075.2.35  raeburn  11063:             $upload_output .= '<td>'.
                   11064:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11065:                                                      $embed_file,\%mapping,
1.1071    raeburn  11066:                                                      $allfiles,$codebase,'upload');
                   11067:             $counter ++;
                   11068:             $numnew ++;
1.987     raeburn  11069:         }
                   11070:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11071:     }
                   11072:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11073:         if ($actionurl eq '/adm/dependencies') {
                   11074:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11075:             $modify_output .= &start_data_table_row().
                   11076:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11077:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11078:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11079:                               '<td>'.$size.'</td>'.
                   11080:                               '<td>'.$mtime.'</td>'.
                   11081:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11082:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11083:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11084:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11085:                               &embedded_file_element('upload_embedded',$counter,
                   11086:                                                      $embed_file,\%mapping,
                   11087:                                                      $allfiles,$codebase,'modify').
                   11088:                               '</div></td>'.
                   11089:                               &end_data_table_row()."\n";
                   11090:             $counter ++;
                   11091:         } else {
                   11092:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11093:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11094:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11095:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11096:                               &Apache::loncommon::end_data_table_row()."\n";
                   11097:         }
                   11098:     }
                   11099:     my $delidx = $counter;
                   11100:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11101:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11102:         $delete_output .= &start_data_table_row().
                   11103:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11104:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11105:                           '<td>'.$size.'</td>'.
                   11106:                           '<td>'.$mtime.'</td>'.
                   11107:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11108:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11109:                           &embedded_file_element('upload_embedded',$delidx,
                   11110:                                                  $oldfile,\%mapping,$allfiles,
                   11111:                                                  $codebase,'delete').'</td>'.
                   11112:                           &end_data_table_row()."\n"; 
                   11113:         $numunused ++;
                   11114:         $delidx ++;
1.987     raeburn  11115:     }
                   11116:     if ($upload_output) {
                   11117:         $upload_output = &start_data_table().
                   11118:                          $upload_output.
                   11119:                          &end_data_table()."\n";
                   11120:     }
1.1071    raeburn  11121:     if ($modify_output) {
                   11122:         $modify_output = &start_data_table().
                   11123:                          &start_data_table_header_row().
                   11124:                          '<th>'.&mt('File').'</th>'.
                   11125:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11126:                          '<th>'.&mt('Modified').'</th>'.
                   11127:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11128:                          &end_data_table_header_row().
                   11129:                          $modify_output.
                   11130:                          &end_data_table()."\n";
                   11131:     }
                   11132:     if ($delete_output) {
                   11133:         $delete_output = &start_data_table().
                   11134:                          &start_data_table_header_row().
                   11135:                          '<th>'.&mt('File').'</th>'.
                   11136:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11137:                          '<th>'.&mt('Modified').'</th>'.
                   11138:                          '<th>'.&mt('Delete?').'</th>'.
                   11139:                          &end_data_table_header_row().
                   11140:                          $delete_output.
                   11141:                          &end_data_table()."\n";
                   11142:     }
1.987     raeburn  11143:     my $applies = 0;
                   11144:     if ($numremref) {
                   11145:         $applies ++;
                   11146:     }
                   11147:     if ($numinvalid) {
                   11148:         $applies ++;
                   11149:     }
                   11150:     if ($numexisting) {
                   11151:         $applies ++;
                   11152:     }
1.1071    raeburn  11153:     if ($counter || $numunused) {
1.987     raeburn  11154:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11155:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11156:                   $state.'<h3>'.$heading.'</h3>'; 
                   11157:         if ($actionurl eq '/adm/dependencies') {
                   11158:             if ($numnew) {
                   11159:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11160:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11161:                            $upload_output.'<br />'."\n";
                   11162:             }
                   11163:             if ($numexisting) {
                   11164:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11165:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11166:                            $modify_output.'<br />'."\n";
                   11167:                            $buttontext = &mt('Save changes');
                   11168:             }
                   11169:             if ($numunused) {
                   11170:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11171:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11172:                            $delete_output.'<br />'."\n";
                   11173:                            $buttontext = &mt('Save changes');
                   11174:             }
                   11175:         } else {
                   11176:             $output .= $upload_output.'<br />'."\n";
                   11177:         }
                   11178:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11179:                    $counter.'" />'."\n";
                   11180:         if ($actionurl eq '/adm/dependencies') { 
                   11181:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11182:                        $numnew.'" />'."\n";
                   11183:         } elsif ($actionurl eq '') {
1.987     raeburn  11184:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11185:         }
                   11186:     } elsif ($applies) {
                   11187:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11188:         if ($applies > 1) {
                   11189:             $output .=  
1.1075.2.35  raeburn  11190:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11191:             if ($numremref) {
                   11192:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11193:             }
                   11194:             if ($numinvalid) {
                   11195:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11196:             }
                   11197:             if ($numexisting) {
                   11198:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11199:             }
                   11200:             $output .= '</ul><br />';
                   11201:         } elsif ($numremref) {
                   11202:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11203:         } elsif ($numinvalid) {
                   11204:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11205:         } elsif ($numexisting) {
                   11206:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11207:         }
                   11208:         $output .= $upload_output.'<br />';
                   11209:     }
                   11210:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11211:     $chgcount = $counter;
1.987     raeburn  11212:     if (keys(%pathchanges) > 0) {
                   11213:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11214:             if ($counter) {
1.987     raeburn  11215:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11216:                                                   $embed_file,\%mapping,
1.1071    raeburn  11217:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11218:             } else {
                   11219:                 $pathchange_output .= 
                   11220:                     &start_data_table_row().
                   11221:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11222:                     $chgcount.'" checked="checked" /></td>'.
                   11223:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11224:                     '<td>'.$embed_file.
                   11225:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11226:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11227:                     '</td>'.&end_data_table_row();
1.660     raeburn  11228:             }
1.987     raeburn  11229:             $numpathchg ++;
                   11230:             $chgcount ++;
1.660     raeburn  11231:         }
                   11232:     }
1.1075.2.35  raeburn  11233:     if (($counter) || ($numunused)) {
1.987     raeburn  11234:         if ($numpathchg) {
                   11235:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11236:                        $numpathchg.'" />'."\n";
                   11237:         }
                   11238:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11239:             ($actionurl eq '/adm/imsimport')) {
                   11240:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11241:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11242:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11243:         } elsif ($actionurl eq '/adm/dependencies') {
                   11244:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11245:         }
1.1075.2.35  raeburn  11246:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11247:     } elsif ($numpathchg) {
                   11248:         my %pathchange = ();
                   11249:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11250:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11251:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11252:         }
1.987     raeburn  11253:     }
1.1071    raeburn  11254:     return ($output,$counter,$numpathchg);
1.987     raeburn  11255: }
                   11256: 
1.1075.2.47  raeburn  11257: =pod
                   11258: 
                   11259: =item * clean_path($name)
                   11260: 
                   11261: Performs clean-up of directories, subdirectories and filename in an
                   11262: embedded object, referenced in an HTML file which is being uploaded
                   11263: to a course or portfolio, where
                   11264: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11265: checked.
                   11266: 
                   11267: Clean-up is similar to replacements in lonnet::clean_filename()
                   11268: except each / between sub-directory and next level is preserved.
                   11269: 
                   11270: =cut
                   11271: 
                   11272: sub clean_path {
                   11273:     my ($embed_file) = @_;
                   11274:     $embed_file =~s{^/+}{};
                   11275:     my @contents;
                   11276:     if ($embed_file =~ m{/}) {
                   11277:         @contents = split(/\//,$embed_file);
                   11278:     } else {
                   11279:         @contents = ($embed_file);
                   11280:     }
                   11281:     my $lastidx = scalar(@contents)-1;
                   11282:     for (my $i=0; $i<=$lastidx; $i++) {
                   11283:         $contents[$i]=~s{\\}{/}g;
                   11284:         $contents[$i]=~s/\s+/\_/g;
                   11285:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11286:         if ($i == $lastidx) {
                   11287:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11288:         }
                   11289:     }
                   11290:     if ($lastidx > 0) {
                   11291:         return join('/',@contents);
                   11292:     } else {
                   11293:         return $contents[0];
                   11294:     }
                   11295: }
                   11296: 
1.987     raeburn  11297: sub embedded_file_element {
1.1071    raeburn  11298:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11299:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11300:                    (ref($codebase) eq 'HASH'));
                   11301:     my $output;
1.1071    raeburn  11302:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11303:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11304:     }
                   11305:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11306:                &escape($embed_file).'" />';
                   11307:     unless (($context eq 'upload_embedded') && 
                   11308:             ($mapping->{$embed_file} eq $embed_file)) {
                   11309:         $output .='
                   11310:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11311:     }
                   11312:     my $attrib;
                   11313:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11314:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11315:     }
                   11316:     $output .=
                   11317:         "\n\t\t".
                   11318:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11319:         $attrib.'" />';
                   11320:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11321:         $output .=
                   11322:             "\n\t\t".
                   11323:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11324:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11325:     }
1.987     raeburn  11326:     return $output;
1.660     raeburn  11327: }
                   11328: 
1.1071    raeburn  11329: sub get_dependency_details {
                   11330:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11331:     my ($size,$mtime,$showsize,$showmtime);
                   11332:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11333:         if ($embed_file =~ m{/}) {
                   11334:             my ($path,$fname) = split(/\//,$embed_file);
                   11335:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11336:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11337:             }
                   11338:         } else {
                   11339:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11340:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11341:             }
                   11342:         }
                   11343:         $showsize = $size/1024.0;
                   11344:         $showsize = sprintf("%.1f",$showsize);
                   11345:         if ($mtime > 0) {
                   11346:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11347:         }
                   11348:     }
                   11349:     return ($showsize,$showmtime);
                   11350: }
                   11351: 
                   11352: sub ask_embedded_js {
                   11353:     return <<"END";
                   11354: <script type="text/javascript"">
                   11355: // <![CDATA[
                   11356: function toggleBrowse(counter) {
                   11357:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11358:     var fileid = document.getElementById('embedded_item_'+counter);
                   11359:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11360:     if (chkboxid.checked == true) {
                   11361:         uploaddivid.style.display='block';
                   11362:     } else {
                   11363:         uploaddivid.style.display='none';
                   11364:         fileid.value = '';
                   11365:     }
                   11366: }
                   11367: // ]]>
                   11368: </script>
                   11369: 
                   11370: END
                   11371: }
                   11372: 
1.661     raeburn  11373: sub upload_embedded {
                   11374:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11375:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11376:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11377:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11378:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11379:         my $orig_uploaded_filename =
                   11380:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11381:         foreach my $type ('orig','ref','attrib','codebase') {
                   11382:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11383:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11384:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11385:             }
                   11386:         }
1.661     raeburn  11387:         my ($path,$fname) =
                   11388:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11389:         # no path, whole string is fname
                   11390:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11391:         $fname = &Apache::lonnet::clean_filename($fname);
                   11392:         # See if there is anything left
                   11393:         next if ($fname eq '');
                   11394: 
                   11395:         # Check if file already exists as a file or directory.
                   11396:         my ($state,$msg);
                   11397:         if ($context eq 'portfolio') {
                   11398:             my $port_path = $dirpath;
                   11399:             if ($group ne '') {
                   11400:                 $port_path = "groups/$group/$port_path";
                   11401:             }
1.987     raeburn  11402:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11403:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11404:                                               $dir_root,$port_path,$disk_quota,
                   11405:                                               $current_disk_usage,$uname,$udom);
                   11406:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11407:                 || $state eq 'file_locked') {
1.661     raeburn  11408:                 $output .= $msg;
                   11409:                 next;
                   11410:             }
                   11411:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11412:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11413:             if ($state eq 'exists') {
                   11414:                 $output .= $msg;
                   11415:                 next;
                   11416:             }
                   11417:         }
                   11418:         # Check if extension is valid
                   11419:         if (($fname =~ /\.(\w+)$/) &&
                   11420:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11421:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11422:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11423:             next;
                   11424:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11425:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11426:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11427:             next;
                   11428:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11429:             $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  11430:             next;
                   11431:         }
                   11432:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11433:         my $subdir = $path;
                   11434:         $subdir =~ s{/+$}{};
1.661     raeburn  11435:         if ($context eq 'portfolio') {
1.984     raeburn  11436:             my $result;
                   11437:             if ($state eq 'existingfile') {
                   11438:                 $result=
                   11439:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11440:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11441:             } else {
1.984     raeburn  11442:                 $result=
                   11443:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11444:                                                     $dirpath.
1.1075.2.35  raeburn  11445:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11446:                 if ($result !~ m|^/uploaded/|) {
                   11447:                     $output .= '<span class="LC_error">'
                   11448:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11449:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11450:                                .'</span><br />';
                   11451:                     next;
                   11452:                 } else {
1.987     raeburn  11453:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11454:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11455:                 }
1.661     raeburn  11456:             }
1.1075.2.35  raeburn  11457:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11458:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11459:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11460:             my $result =
1.1075.2.35  raeburn  11461:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11462:             if ($result !~ m|^/uploaded/|) {
                   11463:                 $output .= '<span class="LC_error">'
                   11464:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11465:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11466:                            .'</span><br />';
                   11467:                     next;
                   11468:             } else {
                   11469:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11470:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11471:                 if ($context eq 'syllabus') {
                   11472:                     &Apache::lonnet::make_public_indefinitely($result);
                   11473:                 }
1.987     raeburn  11474:             }
1.661     raeburn  11475:         } else {
                   11476: # Save the file
                   11477:             my $target = $env{'form.embedded_item_'.$i};
                   11478:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11479:             my $dest = $fullpath.$fname;
                   11480:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11481:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11482:             my $count;
                   11483:             my $filepath = $dir_root;
1.1027    raeburn  11484:             foreach my $subdir (@parts) {
                   11485:                 $filepath .= "/$subdir";
                   11486:                 if (!-e $filepath) {
1.661     raeburn  11487:                     mkdir($filepath,0770);
                   11488:                 }
                   11489:             }
                   11490:             my $fh;
                   11491:             if (!open($fh,'>'.$dest)) {
                   11492:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11493:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11494:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11495:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11496:                            '</span><br />';
                   11497:             } else {
                   11498:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11499:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11500:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11501:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11502:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11503:                               '</span><br />';
                   11504:                 } else {
1.987     raeburn  11505:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11506:                                $url.'</span>').'<br />';
                   11507:                     unless ($context eq 'testbank') {
                   11508:                         $footer .= &mt('View embedded file: [_1]',
                   11509:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11510:                     }
                   11511:                 }
                   11512:                 close($fh);
                   11513:             }
                   11514:         }
                   11515:         if ($env{'form.embedded_ref_'.$i}) {
                   11516:             $pathchange{$i} = 1;
                   11517:         }
                   11518:     }
                   11519:     if ($output) {
                   11520:         $output = '<p>'.$output.'</p>';
                   11521:     }
                   11522:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11523:     $returnflag = 'ok';
1.1071    raeburn  11524:     my $numpathchgs = scalar(keys(%pathchange));
                   11525:     if ($numpathchgs > 0) {
1.987     raeburn  11526:         if ($context eq 'portfolio') {
                   11527:             $output .= '<p>'.&mt('or').'</p>';
                   11528:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11529:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11530:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11531:             $returnflag = 'modify_orightml';
                   11532:         }
                   11533:     }
1.1071    raeburn  11534:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11535: }
                   11536: 
                   11537: sub modify_html_form {
                   11538:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11539:     my $end = 0;
                   11540:     my $modifyform;
                   11541:     if ($context eq 'upload_embedded') {
                   11542:         return unless (ref($pathchange) eq 'HASH');
                   11543:         if ($env{'form.number_embedded_items'}) {
                   11544:             $end += $env{'form.number_embedded_items'};
                   11545:         }
                   11546:         if ($env{'form.number_pathchange_items'}) {
                   11547:             $end += $env{'form.number_pathchange_items'};
                   11548:         }
                   11549:         if ($end) {
                   11550:             for (my $i=0; $i<$end; $i++) {
                   11551:                 if ($i < $env{'form.number_embedded_items'}) {
                   11552:                     next unless($pathchange->{$i});
                   11553:                 }
                   11554:                 $modifyform .=
                   11555:                     &start_data_table_row().
                   11556:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11557:                     'checked="checked" /></td>'.
                   11558:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11559:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11560:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11561:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11562:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11563:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11564:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11565:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11566:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11567:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11568:                     &end_data_table_row();
1.1071    raeburn  11569:             }
1.987     raeburn  11570:         }
                   11571:     } else {
                   11572:         $modifyform = $pathchgtable;
                   11573:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11574:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11575:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11576:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11577:         }
                   11578:     }
                   11579:     if ($modifyform) {
1.1071    raeburn  11580:         if ($actionurl eq '/adm/dependencies') {
                   11581:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11582:         }
1.987     raeburn  11583:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11584:                '<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".
                   11585:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11586:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11587:                '</ol></p>'."\n".'<p>'.
                   11588:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11589:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11590:                &start_data_table()."\n".
                   11591:                &start_data_table_header_row().
                   11592:                '<th>'.&mt('Change?').'</th>'.
                   11593:                '<th>'.&mt('Current reference').'</th>'.
                   11594:                '<th>'.&mt('Required reference').'</th>'.
                   11595:                &end_data_table_header_row()."\n".
                   11596:                $modifyform.
                   11597:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11598:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11599:                '</form>'."\n";
                   11600:     }
                   11601:     return;
                   11602: }
                   11603: 
                   11604: sub modify_html_refs {
1.1075.2.35  raeburn  11605:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11606:     my $container;
                   11607:     if ($context eq 'portfolio') {
                   11608:         $container = $env{'form.container'};
                   11609:     } elsif ($context eq 'coursedoc') {
                   11610:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11611:     } elsif ($context eq 'manage_dependencies') {
                   11612:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11613:         $container = "/$container";
1.1075.2.35  raeburn  11614:     } elsif ($context eq 'syllabus') {
                   11615:         $container = $url;
1.987     raeburn  11616:     } else {
1.1027    raeburn  11617:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11618:     }
                   11619:     my (%allfiles,%codebase,$output,$content);
                   11620:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11621:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11622:         if (wantarray) {
                   11623:             return ('',0,0); 
                   11624:         } else {
                   11625:             return;
                   11626:         }
                   11627:     }
                   11628:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11629:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11630:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11631:             if (wantarray) {
                   11632:                 return ('',0,0);
                   11633:             } else {
                   11634:                 return;
                   11635:             }
                   11636:         } 
1.987     raeburn  11637:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11638:         if ($content eq '-1') {
                   11639:             if (wantarray) {
                   11640:                 return ('',0,0);
                   11641:             } else {
                   11642:                 return;
                   11643:             }
                   11644:         }
1.987     raeburn  11645:     } else {
1.1071    raeburn  11646:         unless ($container =~ /^\Q$dir_root\E/) {
                   11647:             if (wantarray) {
                   11648:                 return ('',0,0);
                   11649:             } else {
                   11650:                 return;
                   11651:             }
                   11652:         } 
1.1075.2.128  raeburn  11653:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11654:             $content = join('', <$fh>);
                   11655:             close($fh);
                   11656:         } else {
1.1071    raeburn  11657:             if (wantarray) {
                   11658:                 return ('',0,0);
                   11659:             } else {
                   11660:                 return;
                   11661:             }
1.987     raeburn  11662:         }
                   11663:     }
                   11664:     my ($count,$codebasecount) = (0,0);
                   11665:     my $mm = new File::MMagic;
                   11666:     my $mime_type = $mm->checktype_contents($content);
                   11667:     if ($mime_type eq 'text/html') {
                   11668:         my $parse_result = 
                   11669:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11670:                                                     \%codebase,\$content);
                   11671:         if ($parse_result eq 'ok') {
                   11672:             foreach my $i (@changes) {
                   11673:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11674:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11675:                 if ($allfiles{$ref}) {
                   11676:                     my $newname =  $orig;
                   11677:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11678:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11679:                     if ($attrib_regexp =~ /:/) {
                   11680:                         $attrib_regexp =~ s/\:/|/g;
                   11681:                     }
                   11682:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11683:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11684:                         $count += $numchg;
1.1075.2.35  raeburn  11685:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11686:                         delete($allfiles{$ref});
1.987     raeburn  11687:                     }
                   11688:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11689:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11690:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11691:                         $codebasecount ++;
                   11692:                     }
                   11693:                 }
                   11694:             }
1.1075.2.35  raeburn  11695:             my $skiprewrites;
1.987     raeburn  11696:             if ($count || $codebasecount) {
                   11697:                 my $saveresult;
1.1071    raeburn  11698:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11699:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11700:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11701:                     if ($url eq $container) {
                   11702:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11703:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11704:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11705:                                             $fname.'</span>').'</p>';
1.987     raeburn  11706:                     } else {
                   11707:                          $output = '<p class="LC_error">'.
                   11708:                                    &mt('Error: update failed for: [_1].',
                   11709:                                    '<span class="LC_filename">'.
                   11710:                                    $container.'</span>').'</p>';
                   11711:                     }
1.1075.2.35  raeburn  11712:                     if ($context eq 'syllabus') {
                   11713:                         unless ($saveresult eq 'ok') {
                   11714:                             $skiprewrites = 1;
                   11715:                         }
                   11716:                     }
1.987     raeburn  11717:                 } else {
1.1075.2.128  raeburn  11718:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11719:                         print $fh $content;
                   11720:                         close($fh);
                   11721:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11722:                                   $count,'<span class="LC_filename">'.
                   11723:                                   $container.'</span>').'</p>';
1.661     raeburn  11724:                     } else {
1.987     raeburn  11725:                          $output = '<p class="LC_error">'.
                   11726:                                    &mt('Error: could not update [_1].',
                   11727:                                    '<span class="LC_filename">'.
                   11728:                                    $container.'</span>').'</p>';
1.661     raeburn  11729:                     }
                   11730:                 }
                   11731:             }
1.1075.2.35  raeburn  11732:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11733:                 my ($actionurl,$state);
                   11734:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11735:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11736:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11737:                                               \%codebase,
                   11738:                                               {'context' => 'rewrites',
                   11739:                                                'ignore_remote_references' => 1,});
                   11740:                 if (ref($mapping) eq 'HASH') {
                   11741:                     my $rewrites = 0;
                   11742:                     foreach my $key (keys(%{$mapping})) {
                   11743:                         next if ($key =~ m{^https?://});
                   11744:                         my $ref = $mapping->{$key};
                   11745:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11746:                         my $attrib;
                   11747:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11748:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11749:                         }
                   11750:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11751:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11752:                             $rewrites += $numchg;
                   11753:                         }
                   11754:                     }
                   11755:                     if ($rewrites) {
                   11756:                         my $saveresult;
                   11757:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11758:                         if ($url eq $container) {
                   11759:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11760:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11761:                                             $count,'<span class="LC_filename">'.
                   11762:                                             $fname.'</span>').'</p>';
                   11763:                         } else {
                   11764:                             $output .= '<p class="LC_error">'.
                   11765:                                        &mt('Error: could not update links in [_1].',
                   11766:                                        '<span class="LC_filename">'.
                   11767:                                        $container.'</span>').'</p>';
                   11768: 
                   11769:                         }
                   11770:                     }
                   11771:                 }
                   11772:             }
1.987     raeburn  11773:         } else {
                   11774:             &logthis('Failed to parse '.$container.
                   11775:                      ' to modify references: '.$parse_result);
1.661     raeburn  11776:         }
                   11777:     }
1.1071    raeburn  11778:     if (wantarray) {
                   11779:         return ($output,$count,$codebasecount);
                   11780:     } else {
                   11781:         return $output;
                   11782:     }
1.661     raeburn  11783: }
                   11784: 
                   11785: sub check_for_existing {
                   11786:     my ($path,$fname,$element) = @_;
                   11787:     my ($state,$msg);
                   11788:     if (-d $path.'/'.$fname) {
                   11789:         $state = 'exists';
                   11790:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11791:     } elsif (-e $path.'/'.$fname) {
                   11792:         $state = 'exists';
                   11793:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11794:     }
                   11795:     if ($state eq 'exists') {
                   11796:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11797:     }
                   11798:     return ($state,$msg);
                   11799: }
                   11800: 
                   11801: sub check_for_upload {
                   11802:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11803:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11804:     my $filesize = length($env{'form.'.$element});
                   11805:     if (!$filesize) {
                   11806:         my $msg = '<span class="LC_error">'.
                   11807:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11808:                       '<span class="LC_filename">'.$fname.'</span>',
                   11809:                       $filesize).'<br />'.
1.1007    raeburn  11810:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11811:                   '</span>';
                   11812:         return ('zero_bytes',$msg);
                   11813:     }
                   11814:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11815:     my $getpropath = 1;
1.1021    raeburn  11816:     my ($dirlistref,$listerror) =
                   11817:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11818:     my $found_file = 0;
                   11819:     my $locked_file = 0;
1.991     raeburn  11820:     my @lockers;
                   11821:     my $navmap;
                   11822:     if ($env{'request.course.id'}) {
                   11823:         $navmap = Apache::lonnavmaps::navmap->new();
                   11824:     }
1.1021    raeburn  11825:     if (ref($dirlistref) eq 'ARRAY') {
                   11826:         foreach my $line (@{$dirlistref}) {
                   11827:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11828:             if ($file_name eq $fname){
                   11829:                 $file_name = $path.$file_name;
                   11830:                 if ($group ne '') {
                   11831:                     $file_name = $group.$file_name;
                   11832:                 }
                   11833:                 $found_file = 1;
                   11834:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11835:                     foreach my $lock (@lockers) {
                   11836:                         if (ref($lock) eq 'ARRAY') {
                   11837:                             my ($symb,$crsid) = @{$lock};
                   11838:                             if ($crsid eq $env{'request.course.id'}) {
                   11839:                                 if (ref($navmap)) {
                   11840:                                     my $res = $navmap->getBySymb($symb);
                   11841:                                     foreach my $part (@{$res->parts()}) { 
                   11842:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11843:                                         unless (($slot_status == $res->RESERVED) ||
                   11844:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11845:                                             $locked_file = 1;
                   11846:                                         }
1.991     raeburn  11847:                                     }
1.1021    raeburn  11848:                                 } else {
                   11849:                                     $locked_file = 1;
1.991     raeburn  11850:                                 }
                   11851:                             } else {
                   11852:                                 $locked_file = 1;
                   11853:                             }
                   11854:                         }
1.1021    raeburn  11855:                    }
                   11856:                 } else {
                   11857:                     my @info = split(/\&/,$rest);
                   11858:                     my $currsize = $info[6]/1000;
                   11859:                     if ($currsize < $filesize) {
                   11860:                         my $extra = $filesize - $currsize;
                   11861:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11862:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11863:                                       &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  11864:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11865:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11866:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11867:                             return ('will_exceed_quota',$msg);
                   11868:                         }
1.984     raeburn  11869:                     }
                   11870:                 }
1.661     raeburn  11871:             }
                   11872:         }
                   11873:     }
                   11874:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11875:         my $msg = '<p class="LC_warning">'.
                   11876:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11877:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11878:         return ('will_exceed_quota',$msg);
                   11879:     } elsif ($found_file) {
                   11880:         if ($locked_file) {
1.1075.2.69  raeburn  11881:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11882:             $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  11883:             $msg .= '</p>';
1.661     raeburn  11884:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11885:             return ('file_locked',$msg);
                   11886:         } else {
1.1075.2.69  raeburn  11887:             my $msg = '<p class="LC_error">';
1.984     raeburn  11888:             $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  11889:             $msg .= '</p>';
1.984     raeburn  11890:             return ('existingfile',$msg);
1.661     raeburn  11891:         }
                   11892:     }
                   11893: }
                   11894: 
1.987     raeburn  11895: sub check_for_traversal {
                   11896:     my ($path,$url,$toplevel) = @_;
                   11897:     my @parts=split(/\//,$path);
                   11898:     my $cleanpath;
                   11899:     my $fullpath = $url;
                   11900:     for (my $i=0;$i<@parts;$i++) {
                   11901:         next if ($parts[$i] eq '.');
                   11902:         if ($parts[$i] eq '..') {
                   11903:             $fullpath =~ s{([^/]+/)$}{};
                   11904:         } else {
                   11905:             $fullpath .= $parts[$i].'/';
                   11906:         }
                   11907:     }
                   11908:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11909:         $cleanpath = $1;
                   11910:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11911:         my $curr_toprel = $1;
                   11912:         my @parts = split(/\//,$curr_toprel);
                   11913:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11914:         my @urlparts = split(/\//,$url_toprel);
                   11915:         my $doubledots;
                   11916:         my $startdiff = -1;
                   11917:         for (my $i=0; $i<@urlparts; $i++) {
                   11918:             if ($startdiff == -1) {
                   11919:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11920:                     $startdiff = $i;
                   11921:                     $doubledots .= '../';
                   11922:                 }
                   11923:             } else {
                   11924:                 $doubledots .= '../';
                   11925:             }
                   11926:         }
                   11927:         if ($startdiff > -1) {
                   11928:             $cleanpath = $doubledots;
                   11929:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11930:                 $cleanpath .= $parts[$i].'/';
                   11931:             }
                   11932:         }
                   11933:     }
                   11934:     $cleanpath =~ s{(/)$}{};
                   11935:     return $cleanpath;
                   11936: }
1.31      albertel 11937: 
1.1053    raeburn  11938: sub is_archive_file {
                   11939:     my ($mimetype) = @_;
                   11940:     if (($mimetype eq 'application/octet-stream') ||
                   11941:         ($mimetype eq 'application/x-stuffit') ||
                   11942:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11943:         return 1;
                   11944:     }
                   11945:     return;
                   11946: }
                   11947: 
                   11948: sub decompress_form {
1.1065    raeburn  11949:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11950:     my %lt = &Apache::lonlocal::texthash (
                   11951:         this => 'This file is an archive file.',
1.1067    raeburn  11952:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11953:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11954:         youm => 'You may wish to extract its contents.',
                   11955:         extr => 'Extract contents',
1.1067    raeburn  11956:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11957:         proa => 'Process automatically?',
1.1053    raeburn  11958:         yes  => 'Yes',
                   11959:         no   => 'No',
1.1067    raeburn  11960:         fold => 'Title for folder containing movie',
                   11961:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11962:     );
1.1065    raeburn  11963:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11964:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11965:     my $info = &list_archive_contents($fileloc,\@paths);
                   11966:     if (@paths) {
                   11967:         foreach my $path (@paths) {
                   11968:             $path =~ s{^/}{};
1.1067    raeburn  11969:             if ($path =~ m{^([^/]+)/$}) {
                   11970:                 $topdir = $1;
                   11971:             }
1.1065    raeburn  11972:             if ($path =~ m{^([^/]+)/}) {
                   11973:                 $toplevel{$1} = $path;
                   11974:             } else {
                   11975:                 $toplevel{$path} = $path;
                   11976:             }
                   11977:         }
                   11978:     }
1.1067    raeburn  11979:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11980:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11981:                         "$topdir/media/",
                   11982:                         "$topdir/media/$topdir.mp4",
                   11983:                         "$topdir/media/FirstFrame.png",
                   11984:                         "$topdir/media/player.swf",
                   11985:                         "$topdir/media/swfobject.js",
                   11986:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11987:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11988:                          "$topdir/$topdir.mp4",
                   11989:                          "$topdir/$topdir\_config.xml",
                   11990:                          "$topdir/$topdir\_controller.swf",
                   11991:                          "$topdir/$topdir\_embed.css",
                   11992:                          "$topdir/$topdir\_First_Frame.png",
                   11993:                          "$topdir/$topdir\_player.html",
                   11994:                          "$topdir/$topdir\_Thumbnails.png",
                   11995:                          "$topdir/playerProductInstall.swf",
                   11996:                          "$topdir/scripts/",
                   11997:                          "$topdir/scripts/config_xml.js",
                   11998:                          "$topdir/scripts/handlebars.js",
                   11999:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12000:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12001:                          "$topdir/scripts/modernizr.js",
                   12002:                          "$topdir/scripts/player-min.js",
                   12003:                          "$topdir/scripts/swfobject.js",
                   12004:                          "$topdir/skins/",
                   12005:                          "$topdir/skins/configuration_express.xml",
                   12006:                          "$topdir/skins/express_show/",
                   12007:                          "$topdir/skins/express_show/player-min.css",
                   12008:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12009:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12010:                          "$topdir/$topdir.mp4",
                   12011:                          "$topdir/$topdir\_config.xml",
                   12012:                          "$topdir/$topdir\_controller.swf",
                   12013:                          "$topdir/$topdir\_embed.css",
                   12014:                          "$topdir/$topdir\_First_Frame.png",
                   12015:                          "$topdir/$topdir\_player.html",
                   12016:                          "$topdir/$topdir\_Thumbnails.png",
                   12017:                          "$topdir/playerProductInstall.swf",
                   12018:                          "$topdir/scripts/",
                   12019:                          "$topdir/scripts/config_xml.js",
                   12020:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12021:                          "$topdir/skins/",
                   12022:                          "$topdir/skins/configuration_express.xml",
                   12023:                          "$topdir/skins/express_show/",
                   12024:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12025:                          "$topdir/skins/express_show/spritesheet.png",
                   12026:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12027:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12028:         if (@diffs == 0) {
1.1075.2.59  raeburn  12029:             $is_camtasia = 6;
                   12030:         } else {
1.1075.2.81  raeburn  12031:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12032:             if (@diffs == 0) {
                   12033:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12034:             } else {
                   12035:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12036:                 if (@diffs == 0) {
                   12037:                     $is_camtasia = 8;
                   12038:                 }
1.1075.2.59  raeburn  12039:             }
1.1067    raeburn  12040:         }
                   12041:     }
                   12042:     my $output;
                   12043:     if ($is_camtasia) {
                   12044:         $output = <<"ENDCAM";
                   12045: <script type="text/javascript" language="Javascript">
                   12046: // <![CDATA[
                   12047: 
                   12048: function camtasiaToggle() {
                   12049:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12050:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12051:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12052:                 document.getElementById('camtasia_titles').style.display='block';
                   12053:             } else {
                   12054:                 document.getElementById('camtasia_titles').style.display='none';
                   12055:             }
                   12056:         }
                   12057:     }
                   12058:     return;
                   12059: }
                   12060: 
                   12061: // ]]>
                   12062: </script>
                   12063: <p>$lt{'camt'}</p>
                   12064: ENDCAM
1.1065    raeburn  12065:     } else {
1.1067    raeburn  12066:         $output = '<p>'.$lt{'this'};
                   12067:         if ($info eq '') {
                   12068:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12069:         } else {
                   12070:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12071:                        '<div><pre>'.$info.'</pre></div>';
                   12072:         }
1.1065    raeburn  12073:     }
1.1067    raeburn  12074:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12075:     my $duplicates;
                   12076:     my $num = 0;
                   12077:     if (ref($dirlist) eq 'ARRAY') {
                   12078:         foreach my $item (@{$dirlist}) {
                   12079:             if (ref($item) eq 'ARRAY') {
                   12080:                 if (exists($toplevel{$item->[0]})) {
                   12081:                     $duplicates .= 
                   12082:                         &start_data_table_row().
                   12083:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12084:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12085:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12086:                         'value="1" />'.&mt('Yes').'</label>'.
                   12087:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12088:                         '<td>'.$item->[0].'</td>';
                   12089:                     if ($item->[2]) {
                   12090:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12091:                     } else {
                   12092:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12093:                     }
                   12094:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12095:                                    '<td>'.
                   12096:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12097:                                    '</td>'.
                   12098:                                    &end_data_table_row();
                   12099:                     $num ++;
                   12100:                 }
                   12101:             }
                   12102:         }
                   12103:     }
                   12104:     my $itemcount;
                   12105:     if (@paths > 0) {
                   12106:         $itemcount = scalar(@paths);
                   12107:     } else {
                   12108:         $itemcount = 1;
                   12109:     }
1.1067    raeburn  12110:     if ($is_camtasia) {
                   12111:         $output .= $lt{'auto'}.'<br />'.
                   12112:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12113:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12114:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12115:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12116:                    $lt{'no'}.'</label></span><br />'.
                   12117:                    '<div id="camtasia_titles" style="display:block">'.
                   12118:                    &Apache::lonhtmlcommon::start_pick_box().
                   12119:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12120:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12121:                    &Apache::lonhtmlcommon::row_closure().
                   12122:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12123:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12124:                    &Apache::lonhtmlcommon::row_closure(1).
                   12125:                    &Apache::lonhtmlcommon::end_pick_box().
                   12126:                    '</div>';
                   12127:     }
1.1065    raeburn  12128:     $output .= 
                   12129:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12130:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12131:         "\n";
1.1065    raeburn  12132:     if ($duplicates ne '') {
                   12133:         $output .= '<p><span class="LC_warning">'.
                   12134:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12135:                    &start_data_table().
                   12136:                    &start_data_table_header_row().
                   12137:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12138:                    '<th>'.&mt('Name').'</th>'.
                   12139:                    '<th>'.&mt('Type').'</th>'.
                   12140:                    '<th>'.&mt('Size').'</th>'.
                   12141:                    '<th>'.&mt('Last modified').'</th>'.
                   12142:                    &end_data_table_header_row().
                   12143:                    $duplicates.
                   12144:                    &end_data_table().
                   12145:                    '</p>';
                   12146:     }
1.1067    raeburn  12147:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12148:     if (ref($hiddenelements) eq 'HASH') {
                   12149:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12150:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12151:         }
                   12152:     }
                   12153:     $output .= <<"END";
1.1067    raeburn  12154: <br />
1.1053    raeburn  12155: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12156: </form>
                   12157: $noextract
                   12158: END
                   12159:     return $output;
                   12160: }
                   12161: 
1.1065    raeburn  12162: sub decompression_utility {
                   12163:     my ($program) = @_;
                   12164:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12165:     my $location;
                   12166:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12167:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12168:                          '/usr/sbin/') {
                   12169:             if (-x $dir.$program) {
                   12170:                 $location = $dir.$program;
                   12171:                 last;
                   12172:             }
                   12173:         }
                   12174:     }
                   12175:     return $location;
                   12176: }
                   12177: 
                   12178: sub list_archive_contents {
                   12179:     my ($file,$pathsref) = @_;
                   12180:     my (@cmd,$output);
                   12181:     my $needsregexp;
                   12182:     if ($file =~ /\.zip$/) {
                   12183:         @cmd = (&decompression_utility('unzip'),"-l");
                   12184:         $needsregexp = 1;
                   12185:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12186:              ($file =~ /\.tgz$/)) {
                   12187:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12188:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12189:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12190:     } elsif ($file =~ m|\.tar$|) {
                   12191:         @cmd = (&decompression_utility('tar'),"-tf");
                   12192:     }
                   12193:     if (@cmd) {
                   12194:         undef($!);
                   12195:         undef($@);
                   12196:         if (open(my $fh,"-|", @cmd, $file)) {
                   12197:             while (my $line = <$fh>) {
                   12198:                 $output .= $line;
                   12199:                 chomp($line);
                   12200:                 my $item;
                   12201:                 if ($needsregexp) {
                   12202:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12203:                 } else {
                   12204:                     $item = $line;
                   12205:                 }
                   12206:                 if ($item ne '') {
                   12207:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12208:                         push(@{$pathsref},$item);
                   12209:                     } 
                   12210:                 }
                   12211:             }
                   12212:             close($fh);
                   12213:         }
                   12214:     }
                   12215:     return $output;
                   12216: }
                   12217: 
1.1053    raeburn  12218: sub decompress_uploaded_file {
                   12219:     my ($file,$dir) = @_;
                   12220:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12221:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12222:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12223:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12224:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12225:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12226:     my $decompressed = $env{'cgi.decompressed'};
                   12227:     &Apache::lonnet::delenv('cgi.file');
                   12228:     &Apache::lonnet::delenv('cgi.dir');
                   12229:     &Apache::lonnet::delenv('cgi.decompressed');
                   12230:     return ($decompressed,$result);
                   12231: }
                   12232: 
1.1055    raeburn  12233: sub process_decompression {
                   12234:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12235:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12236:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12237:                &mt('Unexpected file path.').'</p>'."\n";
                   12238:     }
                   12239:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12240:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12241:                &mt('Unexpected course context.').'</p>'."\n";
                   12242:     }
                   12243:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12244:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12245:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12246:     }
1.1055    raeburn  12247:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12248:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12249:         $error = &mt('Filename not a supported archive file type.').
                   12250:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12251:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12252:     } else {
                   12253:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12254:         if ($docuhome eq 'no_host') {
                   12255:             $error = &mt('Could not determine home server for course.');
                   12256:         } else {
                   12257:             my @ids=&Apache::lonnet::current_machine_ids();
                   12258:             my $currdir = "$dir_root/$destination";
                   12259:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12260:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12261:                        "$dir_root/$destination";
                   12262:             } else {
                   12263:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12264:                        "$dir_root/$docudom/$docuname/$destination";
                   12265:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12266:                     $error = &mt('Archive file not found.');
                   12267:                 }
                   12268:             }
1.1065    raeburn  12269:             my (@to_overwrite,@to_skip);
                   12270:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12271:                 my $total = $env{'form.archive_overwrite_total'};
                   12272:                 for (my $i=0; $i<$total; $i++) {
                   12273:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12274:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12275:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12276:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12277:                     }
                   12278:                 }
                   12279:             }
                   12280:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12281:             my $numoverwrite = scalar(@to_overwrite);
                   12282:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12283:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12284:             } elsif ($dir eq '') {
1.1055    raeburn  12285:                 $error = &mt('Directory containing archive file unavailable.');
                   12286:             } elsif (!$error) {
1.1065    raeburn  12287:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12288:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12289:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12290:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12291:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12292:                         ($decompressed,$display) =
                   12293:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12294:                         foreach my $item (@to_skip) {
                   12295:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12296:                                 if (-f "$dir/$tempdir/$item") {
                   12297:                                     unlink("$dir/$tempdir/$item");
                   12298:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12299:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12300:                                 }
                   12301:                             }
                   12302:                         }
                   12303:                         foreach my $item (@to_overwrite) {
                   12304:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12305:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12306:                                     if (-f "$dir/$item") {
                   12307:                                         unlink("$dir/$item");
                   12308:                                     } elsif (-d "$dir/$item") {
                   12309:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12310:                                     }
                   12311:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12312:                                 }
1.1065    raeburn  12313:                             }
                   12314:                         }
1.1075.2.128  raeburn  12315:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12316:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12317:                         }
1.1065    raeburn  12318:                     }
                   12319:                 } else {
                   12320:                     ($decompressed,$display) = 
                   12321:                         &decompress_uploaded_file($file,$dir);
                   12322:                 }
1.1055    raeburn  12323:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12324:                     $output = '<p class="LC_info">'.
                   12325:                               &mt('Files extracted successfully from archive.').
                   12326:                               '</p>'."\n";
1.1055    raeburn  12327:                     my ($warning,$result,@contents);
                   12328:                     my ($newdirlistref,$newlisterror) =
                   12329:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12330:                                                  $docuname,1);
                   12331:                     my (%is_dir,%changes,@newitems);
                   12332:                     my $dirptr = 16384;
1.1065    raeburn  12333:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12334:                         foreach my $dir_line (@{$newdirlistref}) {
                   12335:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12336:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12337:                                 push(@newitems,$item);
                   12338:                                 if ($dirptr&$testdir) {
                   12339:                                     $is_dir{$item} = 1;
                   12340:                                 }
                   12341:                                 $changes{$item} = 1;
                   12342:                             }
                   12343:                         }
                   12344:                     }
                   12345:                     if (keys(%changes) > 0) {
                   12346:                         foreach my $item (sort(@newitems)) {
                   12347:                             if ($changes{$item}) {
                   12348:                                 push(@contents,$item);
                   12349:                             }
                   12350:                         }
                   12351:                     }
                   12352:                     if (@contents > 0) {
1.1067    raeburn  12353:                         my $wantform;
                   12354:                         unless ($env{'form.autoextract_camtasia'}) {
                   12355:                             $wantform = 1;
                   12356:                         }
1.1056    raeburn  12357:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12358:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12359:                                                                 $currdir,\%is_dir,
                   12360:                                                                 \%children,\%parent,
1.1056    raeburn  12361:                                                                 \@contents,\%dirorder,
                   12362:                                                                 \%titles,$wantform);
1.1055    raeburn  12363:                         if ($datatable ne '') {
                   12364:                             $output .= &archive_options_form('decompressed',$datatable,
                   12365:                                                              $count,$hiddenelem);
1.1065    raeburn  12366:                             my $startcount = 6;
1.1055    raeburn  12367:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12368:                                                            \%titles,\%children);
1.1055    raeburn  12369:                         }
1.1067    raeburn  12370:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12371:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12372:                             my %displayed;
                   12373:                             my $total = 1;
                   12374:                             $env{'form.archive_directory'} = [];
                   12375:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12376:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12377:                                 $path =~ s{/$}{};
                   12378:                                 my $item;
                   12379:                                 if ($path ne '') {
                   12380:                                     $item = "$path/$titles{$i}";
                   12381:                                 } else {
                   12382:                                     $item = $titles{$i};
                   12383:                                 }
                   12384:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12385:                                 if ($item eq $contents[0]) {
                   12386:                                     push(@{$env{'form.archive_directory'}},$i);
                   12387:                                     $env{'form.archive_'.$i} = 'display';
                   12388:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12389:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12390:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12391:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12392:                                     $env{'form.archive_'.$i} = 'display';
                   12393:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12394:                                     $displayed{'web'} = $i;
                   12395:                                 } else {
1.1075.2.59  raeburn  12396:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12397:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12398:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12399:                                         push(@{$env{'form.archive_directory'}},$i);
                   12400:                                     }
                   12401:                                     $env{'form.archive_'.$i} = 'dependency';
                   12402:                                 }
                   12403:                                 $total ++;
                   12404:                             }
                   12405:                             for (my $i=1; $i<$total; $i++) {
                   12406:                                 next if ($i == $displayed{'web'});
                   12407:                                 next if ($i == $displayed{'folder'});
                   12408:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12409:                             }
                   12410:                             $env{'form.phase'} = 'decompress_cleanup';
                   12411:                             $env{'form.archivedelete'} = 1;
                   12412:                             $env{'form.archive_count'} = $total-1;
                   12413:                             $output .=
                   12414:                                 &process_extracted_files('coursedocs',$docudom,
                   12415:                                                          $docuname,$destination,
                   12416:                                                          $dir_root,$hiddenelem);
                   12417:                         }
1.1055    raeburn  12418:                     } else {
                   12419:                         $warning = &mt('No new items extracted from archive file.');
                   12420:                     }
                   12421:                 } else {
                   12422:                     $output = $display;
                   12423:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12424:                 }
                   12425:             }
                   12426:         }
                   12427:     }
                   12428:     if ($error) {
                   12429:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12430:                    $error.'</p>'."\n";
                   12431:     }
                   12432:     if ($warning) {
                   12433:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12434:     }
                   12435:     return $output;
                   12436: }
                   12437: 
                   12438: sub get_extracted {
1.1056    raeburn  12439:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12440:         $titles,$wantform) = @_;
1.1055    raeburn  12441:     my $count = 0;
                   12442:     my $depth = 0;
                   12443:     my $datatable;
1.1056    raeburn  12444:     my @hierarchy;
1.1055    raeburn  12445:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12446:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12447:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12448:     foreach my $item (@{$contents}) {
                   12449:         $count ++;
1.1056    raeburn  12450:         @{$dirorder->{$count}} = @hierarchy;
                   12451:         $titles->{$count} = $item;
1.1055    raeburn  12452:         &archive_hierarchy($depth,$count,$parent,$children);
                   12453:         if ($wantform) {
                   12454:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12455:                                        $currdir,$depth,$count);
                   12456:         }
                   12457:         if ($is_dir->{$item}) {
                   12458:             $depth ++;
1.1056    raeburn  12459:             push(@hierarchy,$count);
                   12460:             $parent->{$depth} = $count;
1.1055    raeburn  12461:             $datatable .=
                   12462:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12463:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12464:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12465:             $depth --;
1.1056    raeburn  12466:             pop(@hierarchy);
1.1055    raeburn  12467:         }
                   12468:     }
                   12469:     return ($count,$datatable);
                   12470: }
                   12471: 
                   12472: sub recurse_extracted_archive {
1.1056    raeburn  12473:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12474:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12475:     my $result='';
1.1056    raeburn  12476:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12477:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12478:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12479:         return $result;
                   12480:     }
                   12481:     my $dirptr = 16384;
                   12482:     my ($newdirlistref,$newlisterror) =
                   12483:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12484:     if (ref($newdirlistref) eq 'ARRAY') {
                   12485:         foreach my $dir_line (@{$newdirlistref}) {
                   12486:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12487:             unless ($item =~ /^\.+$/) {
                   12488:                 $$count ++;
1.1056    raeburn  12489:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12490:                 $titles->{$$count} = $item;
1.1055    raeburn  12491:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12492: 
1.1055    raeburn  12493:                 my $is_dir;
                   12494:                 if ($dirptr&$testdir) {
                   12495:                     $is_dir = 1;
                   12496:                 }
                   12497:                 if ($wantform) {
                   12498:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12499:                 }
                   12500:                 if ($is_dir) {
                   12501:                     $$depth ++;
1.1056    raeburn  12502:                     push(@{$hierarchy},$$count);
                   12503:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12504:                     $result .=
                   12505:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12506:                                                    $docuname,$depth,$count,
1.1056    raeburn  12507:                                                    $hierarchy,$dirorder,$children,
                   12508:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12509:                     $$depth --;
1.1056    raeburn  12510:                     pop(@{$hierarchy});
1.1055    raeburn  12511:                 }
                   12512:             }
                   12513:         }
                   12514:     }
                   12515:     return $result;
                   12516: }
                   12517: 
                   12518: sub archive_hierarchy {
                   12519:     my ($depth,$count,$parent,$children) =@_;
                   12520:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12521:         if (exists($parent->{$depth})) {
                   12522:              $children->{$parent->{$depth}} .= $count.':';
                   12523:         }
                   12524:     }
                   12525:     return;
                   12526: }
                   12527: 
                   12528: sub archive_row {
                   12529:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12530:     my ($name) = ($item =~ m{([^/]+)$});
                   12531:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12532:                                        'display'    => 'Add as file',
1.1055    raeburn  12533:                                        'dependency' => 'Include as dependency',
                   12534:                                        'discard'    => 'Discard',
                   12535:                                       );
                   12536:     if ($is_dir) {
1.1059    raeburn  12537:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12538:     }
1.1056    raeburn  12539:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12540:     my $offset = 0;
1.1055    raeburn  12541:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12542:         $offset ++;
1.1065    raeburn  12543:         if ($action ne 'display') {
                   12544:             $offset ++;
                   12545:         }  
1.1055    raeburn  12546:         $output .= '<td><span class="LC_nobreak">'.
                   12547:                    '<label><input type="radio" name="archive_'.$count.
                   12548:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12549:         my $text = $choices{$action};
                   12550:         if ($is_dir) {
                   12551:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12552:             if ($action eq 'display') {
1.1059    raeburn  12553:                 $text = &mt('Add as folder');
1.1055    raeburn  12554:             }
1.1056    raeburn  12555:         } else {
                   12556:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12557: 
                   12558:         }
                   12559:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12560:         if ($action eq 'dependency') {
                   12561:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12562:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12563:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12564:                        '<option value=""></option>'."\n".
                   12565:                        '</select>'."\n".
                   12566:                        '</div>';
1.1059    raeburn  12567:         } elsif ($action eq 'display') {
                   12568:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12569:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12570:                        '</div>';
1.1055    raeburn  12571:         }
1.1056    raeburn  12572:         $output .= '</td>';
1.1055    raeburn  12573:     }
                   12574:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12575:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12576:     for (my $i=0; $i<$depth; $i++) {
                   12577:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12578:     }
                   12579:     if ($is_dir) {
                   12580:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12581:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12582:     } else {
                   12583:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12584:     }
                   12585:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12586:                &end_data_table_row();
                   12587:     return $output;
                   12588: }
                   12589: 
                   12590: sub archive_options_form {
1.1065    raeburn  12591:     my ($form,$display,$count,$hiddenelem) = @_;
                   12592:     my %lt = &Apache::lonlocal::texthash(
                   12593:                perm => 'Permanently remove archive file?',
                   12594:                hows => 'How should each extracted item be incorporated in the course?',
                   12595:                cont => 'Content actions for all',
                   12596:                addf => 'Add as folder/file',
                   12597:                incd => 'Include as dependency for a displayed file',
                   12598:                disc => 'Discard',
                   12599:                no   => 'No',
                   12600:                yes  => 'Yes',
                   12601:                save => 'Save',
                   12602:     );
                   12603:     my $output = <<"END";
                   12604: <form name="$form" method="post" action="">
                   12605: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12606: <label>
                   12607:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12608: </label>
                   12609: &nbsp;
                   12610: <label>
                   12611:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12612: </span>
                   12613: </p>
                   12614: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12615: <br />$lt{'hows'}
                   12616: <div class="LC_columnSection">
                   12617:   <fieldset>
                   12618:     <legend>$lt{'cont'}</legend>
                   12619:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12620:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12621:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12622:   </fieldset>
                   12623: </div>
                   12624: END
                   12625:     return $output.
1.1055    raeburn  12626:            &start_data_table()."\n".
1.1065    raeburn  12627:            $display."\n".
1.1055    raeburn  12628:            &end_data_table()."\n".
                   12629:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12630:            $hiddenelem.
1.1065    raeburn  12631:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12632:            '</form>';
                   12633: }
                   12634: 
                   12635: sub archive_javascript {
1.1056    raeburn  12636:     my ($startcount,$numitems,$titles,$children) = @_;
                   12637:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12638:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12639:     my $scripttag = <<START;
                   12640: <script type="text/javascript">
                   12641: // <![CDATA[
                   12642: 
                   12643: function checkAll(form,prefix) {
                   12644:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12645:     for (var i=0; i < form.elements.length; i++) {
                   12646:         var id = form.elements[i].id;
                   12647:         if ((id != '') && (id != undefined)) {
                   12648:             if (idstr.test(id)) {
                   12649:                 if (form.elements[i].type == 'radio') {
                   12650:                     form.elements[i].checked = true;
1.1056    raeburn  12651:                     var nostart = i-$startcount;
1.1059    raeburn  12652:                     var offset = nostart%7;
                   12653:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12654:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12655:                 }
                   12656:             }
                   12657:         }
                   12658:     }
                   12659: }
                   12660: 
                   12661: function propagateCheck(form,count) {
                   12662:     if (count > 0) {
1.1059    raeburn  12663:         var startelement = $startcount + ((count-1) * 7);
                   12664:         for (var j=1; j<6; j++) {
                   12665:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12666:                 var item = startelement + j; 
                   12667:                 if (form.elements[item].type == 'radio') {
                   12668:                     if (form.elements[item].checked) {
                   12669:                         containerCheck(form,count,j);
                   12670:                         break;
                   12671:                     }
1.1055    raeburn  12672:                 }
                   12673:             }
                   12674:         }
                   12675:     }
                   12676: }
                   12677: 
                   12678: numitems = $numitems
1.1056    raeburn  12679: var titles = new Array(numitems);
                   12680: var parents = new Array(numitems);
1.1055    raeburn  12681: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12682:     parents[i] = new Array;
1.1055    raeburn  12683: }
1.1059    raeburn  12684: var maintitle = '$maintitle';
1.1055    raeburn  12685: 
                   12686: START
                   12687: 
1.1056    raeburn  12688:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12689:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12690:         for (my $i=0; $i<@contents; $i ++) {
                   12691:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12692:         }
                   12693:     }
                   12694: 
1.1056    raeburn  12695:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12696:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12697:     }
                   12698: 
1.1055    raeburn  12699:     $scripttag .= <<END;
                   12700: 
                   12701: function containerCheck(form,count,offset) {
                   12702:     if (count > 0) {
1.1056    raeburn  12703:         dependencyCheck(form,count,offset);
1.1059    raeburn  12704:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12705:         form.elements[item].checked = true;
                   12706:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12707:             if (parents[count].length > 0) {
                   12708:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12709:                     containerCheck(form,parents[count][j],offset);
                   12710:                 }
                   12711:             }
                   12712:         }
                   12713:     }
                   12714: }
                   12715: 
                   12716: function dependencyCheck(form,count,offset) {
                   12717:     if (count > 0) {
1.1059    raeburn  12718:         var chosen = (offset+$startcount)+7*(count-1);
                   12719:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12720:         var currtype = form.elements[depitem].type;
                   12721:         if (form.elements[chosen].value == 'dependency') {
                   12722:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12723:             form.elements[depitem].options.length = 0;
                   12724:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12725:             for (var i=1; i<=numitems; i++) {
                   12726:                 if (i == count) {
                   12727:                     continue;
                   12728:                 }
1.1059    raeburn  12729:                 var startelement = $startcount + (i-1) * 7;
                   12730:                 for (var j=1; j<6; j++) {
                   12731:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12732:                         var item = startelement + j;
                   12733:                         if (form.elements[item].type == 'radio') {
                   12734:                             if (form.elements[item].checked) {
                   12735:                                 if (form.elements[item].value == 'display') {
                   12736:                                     var n = form.elements[depitem].options.length;
                   12737:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12738:                                 }
                   12739:                             }
                   12740:                         }
                   12741:                     }
                   12742:                 }
                   12743:             }
                   12744:         } else {
                   12745:             document.getElementById('arc_depon_'+count).style.display='none';
                   12746:             form.elements[depitem].options.length = 0;
                   12747:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12748:         }
1.1059    raeburn  12749:         titleCheck(form,count,offset);
1.1056    raeburn  12750:     }
                   12751: }
                   12752: 
                   12753: function propagateSelect(form,count,offset) {
                   12754:     if (count > 0) {
1.1065    raeburn  12755:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12756:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12757:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12758:             if (parents[count].length > 0) {
                   12759:                 for (var j=0; j<parents[count].length; j++) {
                   12760:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12761:                 }
                   12762:             }
                   12763:         }
                   12764:     }
                   12765: }
1.1056    raeburn  12766: 
                   12767: function containerSelect(form,count,offset,picked) {
                   12768:     if (count > 0) {
1.1065    raeburn  12769:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12770:         if (form.elements[item].type == 'radio') {
                   12771:             if (form.elements[item].value == 'dependency') {
                   12772:                 if (form.elements[item+1].type == 'select-one') {
                   12773:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12774:                         if (form.elements[item+1].options[i].value == picked) {
                   12775:                             form.elements[item+1].selectedIndex = i;
                   12776:                             break;
                   12777:                         }
                   12778:                     }
                   12779:                 }
                   12780:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12781:                     if (parents[count].length > 0) {
                   12782:                         for (var j=0; j<parents[count].length; j++) {
                   12783:                             containerSelect(form,parents[count][j],offset,picked);
                   12784:                         }
                   12785:                     }
                   12786:                 }
                   12787:             }
                   12788:         }
                   12789:     }
                   12790: }
                   12791: 
1.1059    raeburn  12792: function titleCheck(form,count,offset) {
                   12793:     if (count > 0) {
                   12794:         var chosen = (offset+$startcount)+7*(count-1);
                   12795:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12796:         var currtype = form.elements[depitem].type;
                   12797:         if (form.elements[chosen].value == 'display') {
                   12798:             document.getElementById('arc_title_'+count).style.display='block';
                   12799:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12800:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12801:             }
                   12802:         } else {
                   12803:             document.getElementById('arc_title_'+count).style.display='none';
                   12804:             if (currtype == 'text') { 
                   12805:                 document.getElementById('archive_title_'+count).value='';
                   12806:             }
                   12807:         }
                   12808:     }
                   12809:     return;
                   12810: }
                   12811: 
1.1055    raeburn  12812: // ]]>
                   12813: </script>
                   12814: END
                   12815:     return $scripttag;
                   12816: }
                   12817: 
                   12818: sub process_extracted_files {
1.1067    raeburn  12819:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12820:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12821:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12822:     my @ids=&Apache::lonnet::current_machine_ids();
                   12823:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12824:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12825:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12826:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12827:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12828:         $pathtocheck = "$dir_root/$destination";
                   12829:         $dir = $dir_root;
                   12830:         $ishome = 1;
                   12831:     } else {
                   12832:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12833:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12834:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12835:     }
                   12836:     my $currdir = "$dir_root/$destination";
                   12837:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12838:     if ($env{'form.folderpath'}) {
                   12839:         my @items = split('&',$env{'form.folderpath'});
                   12840:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12841:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12842:             $containers{'0'}='page';
                   12843:         } else {
                   12844:             $containers{'0'}='sequence';
                   12845:         }
1.1055    raeburn  12846:     }
                   12847:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12848:     if ($numitems) {
                   12849:         for (my $i=1; $i<=$numitems; $i++) {
                   12850:             my $path = $env{'form.archive_content_'.$i};
                   12851:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12852:                 my $item = $1;
                   12853:                 $toplevelitems{$item} = $i;
                   12854:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12855:                     $is_dir{$item} = 1;
                   12856:                 }
                   12857:             }
                   12858:         }
                   12859:     }
1.1067    raeburn  12860:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12861:     if (keys(%toplevelitems) > 0) {
                   12862:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12863:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12864:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12865:     }
1.1066    raeburn  12866:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12867:     if ($numitems) {
                   12868:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12869:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12870:             my $path = $env{'form.archive_content_'.$i};
                   12871:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12872:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12873:                     if ($prefix ne '' && $path ne '') {
                   12874:                         if (-e $prefix.$path) {
1.1066    raeburn  12875:                             if ((@archdirs > 0) && 
                   12876:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12877:                                 $todeletedir{$prefix.$path} = 1;
                   12878:                             } else {
                   12879:                                 $todelete{$prefix.$path} = 1;
                   12880:                             }
1.1055    raeburn  12881:                         }
                   12882:                     }
                   12883:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12884:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12885:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12886:                     $docstitle = $env{'form.archive_title_'.$i};
                   12887:                     if ($docstitle eq '') {
                   12888:                         $docstitle = $title;
                   12889:                     }
1.1055    raeburn  12890:                     $outer = 0;
1.1056    raeburn  12891:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12892:                         if (@{$dirorder{$i}} > 0) {
                   12893:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12894:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12895:                                     $outer = $item;
                   12896:                                     last;
                   12897:                                 }
                   12898:                             }
                   12899:                         }
                   12900:                     }
                   12901:                     my ($errtext,$fatal) = 
                   12902:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12903:                                                '/'.$folders{$outer}.'.'.
                   12904:                                                $containers{$outer});
                   12905:                     next if ($fatal);
                   12906:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12907:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12908:                             $mapinner{$i} = time;
1.1055    raeburn  12909:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12910:                             $containers{$i} = 'sequence';
                   12911:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12912:                                       $folders{$i}.'.'.$containers{$i};
                   12913:                             my $newidx = &LONCAPA::map::getresidx();
                   12914:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12915:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12916:                             push(@LONCAPA::map::order,$newidx);
                   12917:                             my ($outtext,$errtext) =
                   12918:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12919:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12920:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12921:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12922:                             unless ($errtext) {
1.1075.2.128  raeburn  12923:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12924:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12925:                                             '</li>'."\n";
1.1067    raeburn  12926:                             }
1.1055    raeburn  12927:                         }
                   12928:                     } else {
                   12929:                         if ($context eq 'coursedocs') {
                   12930:                             my $newidx=&LONCAPA::map::getresidx();
                   12931:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12932:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12933:                                       $title;
1.1075.2.128  raeburn  12934:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12935:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12936:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12937:                                 }
1.1075.2.128  raeburn  12938:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12939:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12940:                                 }
                   12941:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12942:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12943:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12944:                                         unless ($ishome) {
                   12945:                                             my $fetch = "$newdest{$i}/$title";
                   12946:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12947:                                             $prompttofetch{$fetch} = 1;
                   12948:                                         }
                   12949:                                    }
                   12950:                                 }
                   12951:                                 $LONCAPA::map::resources[$newidx]=
                   12952:                                     $docstitle.':'.$url.':false:normal:res';
                   12953:                                 push(@LONCAPA::map::order, $newidx);
                   12954:                                 my ($outtext,$errtext)=
                   12955:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12956:                                                             $docuname.'/'.$folders{$outer}.
                   12957:                                                             '.'.$containers{$outer},1,1);
                   12958:                                 unless ($errtext) {
                   12959:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12960:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12961:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12962:                                                    '</li>'."\n";
                   12963:                                     }
1.1067    raeburn  12964:                                 }
1.1075.2.128  raeburn  12965:                             } else {
                   12966:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12967:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  12968:                             }
1.1055    raeburn  12969:                         }
                   12970:                     }
1.1075.2.11  raeburn  12971:                 }
                   12972:             } else {
1.1075.2.128  raeburn  12973:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12974:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  12975:             }
                   12976:         }
                   12977:         for (my $i=1; $i<=$numitems; $i++) {
                   12978:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12979:             my $path = $env{'form.archive_content_'.$i};
                   12980:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12981:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12982:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12983:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12984:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12985:                         my ($itemidx,$fullpath,$relpath);
                   12986:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12987:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12988:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12989:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12990:                                     $itemidx = $j;
1.1056    raeburn  12991:                                 }
                   12992:                             }
1.1075.2.11  raeburn  12993:                         }
                   12994:                         if ($itemidx eq '') {
                   12995:                             $itemidx =  0;
                   12996:                         }
                   12997:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12998:                             if ($mapinner{$referrer{$i}}) {
                   12999:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13000:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13001:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13002:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13003:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13004:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13005:                                             if (!-e $fullpath) {
                   13006:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13007:                                             }
                   13008:                                         }
1.1075.2.11  raeburn  13009:                                     } else {
                   13010:                                         last;
1.1056    raeburn  13011:                                     }
1.1075.2.11  raeburn  13012:                                 }
                   13013:                             }
                   13014:                         } elsif ($newdest{$referrer{$i}}) {
                   13015:                             $fullpath = $newdest{$referrer{$i}};
                   13016:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13017:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13018:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13019:                                     last;
                   13020:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13021:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13022:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13023:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13024:                                         if (!-e $fullpath) {
                   13025:                                             mkdir($fullpath,0755);
1.1056    raeburn  13026:                                         }
                   13027:                                     }
1.1075.2.11  raeburn  13028:                                 } else {
                   13029:                                     last;
1.1056    raeburn  13030:                                 }
1.1075.2.11  raeburn  13031:                             }
                   13032:                         }
                   13033:                         if ($fullpath ne '') {
                   13034:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13035:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13036:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13037:                                 }
1.1075.2.11  raeburn  13038:                             }
                   13039:                             if (-e "$fullpath/$title") {
                   13040:                                 my $showpath;
                   13041:                                 if ($relpath ne '') {
                   13042:                                     $showpath = "$relpath/$title";
                   13043:                                 } else {
                   13044:                                     $showpath = "/$title";
1.1056    raeburn  13045:                                 }
1.1075.2.128  raeburn  13046:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13047:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13048:                                            '</li>'."\n";
                   13049:                                 unless ($ishome) {
                   13050:                                     my $fetch = "$fullpath/$title";
                   13051:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13052:                                     $prompttofetch{$fetch} = 1;
                   13053:                                 }
1.1055    raeburn  13054:                             }
                   13055:                         }
                   13056:                     }
1.1075.2.11  raeburn  13057:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13058:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13059:                                     &HTML::Entities::encode($path,'<>&"'),
                   13060:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13061:                                 '<br />';
1.1055    raeburn  13062:                 }
                   13063:             } else {
1.1075.2.128  raeburn  13064:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13065:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13066:             }
                   13067:         }
                   13068:         if (keys(%todelete)) {
                   13069:             foreach my $key (keys(%todelete)) {
                   13070:                 unlink($key);
1.1066    raeburn  13071:             }
                   13072:         }
                   13073:         if (keys(%todeletedir)) {
                   13074:             foreach my $key (keys(%todeletedir)) {
                   13075:                 rmdir($key);
                   13076:             }
                   13077:         }
                   13078:         foreach my $dir (sort(keys(%is_dir))) {
                   13079:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13080:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13081:             }
                   13082:         }
1.1067    raeburn  13083:         if ($result ne '') {
                   13084:             $output .= '<ul>'."\n".
                   13085:                        $result."\n".
                   13086:                        '</ul>';
                   13087:         }
                   13088:         unless ($ishome) {
                   13089:             my $replicationfail;
                   13090:             foreach my $item (keys(%prompttofetch)) {
                   13091:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13092:                 unless ($fetchresult eq 'ok') {
                   13093:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13094:                 }
                   13095:             }
                   13096:             if ($replicationfail) {
                   13097:                 $output .= '<p class="LC_error">'.
                   13098:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13099:                            $replicationfail.
                   13100:                            '</ul></p>';
                   13101:             }
                   13102:         }
1.1055    raeburn  13103:     } else {
                   13104:         $warning = &mt('No items found in archive.');
                   13105:     }
                   13106:     if ($error) {
                   13107:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13108:                    $error.'</p>'."\n";
                   13109:     }
                   13110:     if ($warning) {
                   13111:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13112:     }
                   13113:     return $output;
                   13114: }
                   13115: 
1.1066    raeburn  13116: sub cleanup_empty_dirs {
                   13117:     my ($path) = @_;
                   13118:     if (($path ne '') && (-d $path)) {
                   13119:         if (opendir(my $dirh,$path)) {
                   13120:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13121:             my $numitems = 0;
                   13122:             foreach my $item (@dircontents) {
                   13123:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13124:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13125:                     if (-e "$path/$item") {
                   13126:                         $numitems ++;
                   13127:                     }
                   13128:                 } else {
                   13129:                     $numitems ++;
                   13130:                 }
                   13131:             }
                   13132:             if ($numitems == 0) {
                   13133:                 rmdir($path);
                   13134:             }
                   13135:             closedir($dirh);
                   13136:         }
                   13137:     }
                   13138:     return;
                   13139: }
                   13140: 
1.41      ng       13141: =pod
1.45      matthew  13142: 
1.1075.2.56  raeburn  13143: =item * &get_folder_hierarchy()
1.1068    raeburn  13144: 
                   13145: Provides hierarchy of names of folders/sub-folders containing the current
                   13146: item,
                   13147: 
                   13148: Inputs: 3
                   13149:      - $navmap - navmaps object
                   13150: 
                   13151:      - $map - url for map (either the trigger itself, or map containing
                   13152:                            the resource, which is the trigger).
                   13153: 
                   13154:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13155: 
                   13156: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13157: 
                   13158: =cut
                   13159: 
                   13160: sub get_folder_hierarchy {
                   13161:     my ($navmap,$map,$showitem) = @_;
                   13162:     my @pathitems;
                   13163:     if (ref($navmap)) {
                   13164:         my $mapres = $navmap->getResourceByUrl($map);
                   13165:         if (ref($mapres)) {
                   13166:             my $pcslist = $mapres->map_hierarchy();
                   13167:             if ($pcslist ne '') {
                   13168:                 my @pcs = split(/,/,$pcslist);
                   13169:                 foreach my $pc (@pcs) {
                   13170:                     if ($pc == 1) {
1.1075.2.38  raeburn  13171:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13172:                     } else {
                   13173:                         my $res = $navmap->getByMapPc($pc);
                   13174:                         if (ref($res)) {
                   13175:                             my $title = $res->compTitle();
                   13176:                             $title =~ s/\W+/_/g;
                   13177:                             if ($title ne '') {
                   13178:                                 push(@pathitems,$title);
                   13179:                             }
                   13180:                         }
                   13181:                     }
                   13182:                 }
                   13183:             }
1.1071    raeburn  13184:             if ($showitem) {
                   13185:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13186:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13187:                 } else {
                   13188:                     my $maptitle = $mapres->compTitle();
                   13189:                     $maptitle =~ s/\W+/_/g;
                   13190:                     if ($maptitle ne '') {
                   13191:                         push(@pathitems,$maptitle);
                   13192:                     }
1.1068    raeburn  13193:                 }
                   13194:             }
                   13195:         }
                   13196:     }
                   13197:     return @pathitems;
                   13198: }
                   13199: 
                   13200: =pod
                   13201: 
1.1015    raeburn  13202: =item * &get_turnedin_filepath()
                   13203: 
                   13204: Determines path in a user's portfolio file for storage of files uploaded
                   13205: to a specific essayresponse or dropbox item.
                   13206: 
                   13207: Inputs: 3 required + 1 optional.
                   13208: $symb is symb for resource, $uname and $udom are for current user (required).
                   13209: $caller is optional (can be "submission", if routine is called when storing
                   13210: an upoaded file when "Submit Answer" button was pressed).
                   13211: 
                   13212: Returns array containing $path and $multiresp. 
                   13213: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13214: than one file upload item.  Callers of routine should append partid as a 
                   13215: subdirectory to $path in cases where $multiresp is 1.
                   13216: 
                   13217: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13218: 
                   13219: =cut
                   13220: 
                   13221: sub get_turnedin_filepath {
                   13222:     my ($symb,$uname,$udom,$caller) = @_;
                   13223:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13224:     my $turnindir;
                   13225:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13226:     $turnindir = $userhash{'turnindir'};
                   13227:     my ($path,$multiresp);
                   13228:     if ($turnindir eq '') {
                   13229:         if ($caller eq 'submission') {
                   13230:             $turnindir = &mt('turned in');
                   13231:             $turnindir =~ s/\W+/_/g;
                   13232:             my %newhash = (
                   13233:                             'turnindir' => $turnindir,
                   13234:                           );
                   13235:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13236:         }
                   13237:     }
                   13238:     if ($turnindir ne '') {
                   13239:         $path = '/'.$turnindir.'/';
                   13240:         my ($multipart,$turnin,@pathitems);
                   13241:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13242:         if (defined($navmap)) {
                   13243:             my $mapres = $navmap->getResourceByUrl($map);
                   13244:             if (ref($mapres)) {
                   13245:                 my $pcslist = $mapres->map_hierarchy();
                   13246:                 if ($pcslist ne '') {
                   13247:                     foreach my $pc (split(/,/,$pcslist)) {
                   13248:                         my $res = $navmap->getByMapPc($pc);
                   13249:                         if (ref($res)) {
                   13250:                             my $title = $res->compTitle();
                   13251:                             $title =~ s/\W+/_/g;
                   13252:                             if ($title ne '') {
1.1075.2.48  raeburn  13253:                                 if (($pc > 1) && (length($title) > 12)) {
                   13254:                                     $title = substr($title,0,12);
                   13255:                                 }
1.1015    raeburn  13256:                                 push(@pathitems,$title);
                   13257:                             }
                   13258:                         }
                   13259:                     }
                   13260:                 }
                   13261:                 my $maptitle = $mapres->compTitle();
                   13262:                 $maptitle =~ s/\W+/_/g;
                   13263:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13264:                     if (length($maptitle) > 12) {
                   13265:                         $maptitle = substr($maptitle,0,12);
                   13266:                     }
1.1015    raeburn  13267:                     push(@pathitems,$maptitle);
                   13268:                 }
                   13269:                 unless ($env{'request.state'} eq 'construct') {
                   13270:                     my $res = $navmap->getBySymb($symb);
                   13271:                     if (ref($res)) {
                   13272:                         my $partlist = $res->parts();
                   13273:                         my $totaluploads = 0;
                   13274:                         if (ref($partlist) eq 'ARRAY') {
                   13275:                             foreach my $part (@{$partlist}) {
                   13276:                                 my @types = $res->responseType($part);
                   13277:                                 my @ids = $res->responseIds($part);
                   13278:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13279:                                     if ($types[$i] eq 'essay') {
                   13280:                                         my $partid = $part.'_'.$ids[$i];
                   13281:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13282:                                             $totaluploads ++;
                   13283:                                         }
                   13284:                                     }
                   13285:                                 }
                   13286:                             }
                   13287:                             if ($totaluploads > 1) {
                   13288:                                 $multiresp = 1;
                   13289:                             }
                   13290:                         }
                   13291:                     }
                   13292:                 }
                   13293:             } else {
                   13294:                 return;
                   13295:             }
                   13296:         } else {
                   13297:             return;
                   13298:         }
                   13299:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13300:         $restitle =~ s/\W+/_/g;
                   13301:         if ($restitle eq '') {
                   13302:             $restitle = ($resurl =~ m{/[^/]+$});
                   13303:             if ($restitle eq '') {
                   13304:                 $restitle = time;
                   13305:             }
                   13306:         }
1.1075.2.48  raeburn  13307:         if (length($restitle) > 12) {
                   13308:             $restitle = substr($restitle,0,12);
                   13309:         }
1.1015    raeburn  13310:         push(@pathitems,$restitle);
                   13311:         $path .= join('/',@pathitems);
                   13312:     }
                   13313:     return ($path,$multiresp);
                   13314: }
                   13315: 
                   13316: =pod
                   13317: 
1.464     albertel 13318: =back
1.41      ng       13319: 
1.112     bowersj2 13320: =head1 CSV Upload/Handling functions
1.38      albertel 13321: 
1.41      ng       13322: =over 4
                   13323: 
1.648     raeburn  13324: =item * &upfile_store($r)
1.41      ng       13325: 
                   13326: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13327: needs $env{'form.upfile'}
1.41      ng       13328: returns $datatoken to be put into hidden field
                   13329: 
                   13330: =cut
1.31      albertel 13331: 
                   13332: sub upfile_store {
                   13333:     my $r=shift;
1.258     albertel 13334:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13335:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13336:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13337:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13338: 
1.1075.2.128  raeburn  13339:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13340:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13341:                                      time.'_'.$$);
                   13342:     return if ($datatoken eq '');
                   13343: 
1.31      albertel 13344:     {
1.158     raeburn  13345:         my $datafile = $r->dir_config('lonDaemons').
                   13346:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13347:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13348:             print $fh $env{'form.upfile'};
1.158     raeburn  13349:             close($fh);
                   13350:         }
1.31      albertel 13351:     }
                   13352:     return $datatoken;
                   13353: }
                   13354: 
1.56      matthew  13355: =pod
                   13356: 
1.1075.2.128  raeburn  13357: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13358: 
                   13359: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13360: $datatoken is the name to assign to the temporary file.
1.258     albertel 13361: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13362: 
                   13363: =cut
1.31      albertel 13364: 
                   13365: sub load_tmp_file {
1.1075.2.128  raeburn  13366:     my ($r,$datatoken) = @_;
                   13367:     return if ($datatoken eq '');
1.31      albertel 13368:     my @studentdata=();
                   13369:     {
1.158     raeburn  13370:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13371:                               '/tmp/'.$datatoken.'.tmp';
                   13372:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13373:             @studentdata=<$fh>;
                   13374:             close($fh);
                   13375:         }
1.31      albertel 13376:     }
1.258     albertel 13377:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13378: }
                   13379: 
1.1075.2.128  raeburn  13380: sub valid_datatoken {
                   13381:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13382:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13383:         return $datatoken;
                   13384:     }
                   13385:     return;
                   13386: }
                   13387: 
1.56      matthew  13388: =pod
                   13389: 
1.648     raeburn  13390: =item * &upfile_record_sep()
1.41      ng       13391: 
                   13392: Separate uploaded file into records
                   13393: returns array of records,
1.258     albertel 13394: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13395: 
                   13396: =cut
1.31      albertel 13397: 
                   13398: sub upfile_record_sep {
1.258     albertel 13399:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13400:     } else {
1.248     albertel 13401: 	my @records;
1.258     albertel 13402: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13403: 	    if ($line=~/^\s*$/) { next; }
                   13404: 	    push(@records,$line);
                   13405: 	}
                   13406: 	return @records;
1.31      albertel 13407:     }
                   13408: }
                   13409: 
1.56      matthew  13410: =pod
                   13411: 
1.648     raeburn  13412: =item * &record_sep($record)
1.41      ng       13413: 
1.258     albertel 13414: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13415: 
                   13416: =cut
                   13417: 
1.263     www      13418: sub takeleft {
                   13419:     my $index=shift;
                   13420:     return substr('0000'.$index,-4,4);
                   13421: }
                   13422: 
1.31      albertel 13423: sub record_sep {
                   13424:     my $record=shift;
                   13425:     my %components=();
1.258     albertel 13426:     if ($env{'form.upfiletype'} eq 'xml') {
                   13427:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13428:         my $i=0;
1.356     albertel 13429:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13430:             $field=~s/^(\"|\')//;
                   13431:             $field=~s/(\"|\')$//;
1.263     www      13432:             $components{&takeleft($i)}=$field;
1.31      albertel 13433:             $i++;
                   13434:         }
1.258     albertel 13435:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13436:         my $i=0;
1.356     albertel 13437:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13438:             $field=~s/^(\"|\')//;
                   13439:             $field=~s/(\"|\')$//;
1.263     www      13440:             $components{&takeleft($i)}=$field;
1.31      albertel 13441:             $i++;
                   13442:         }
                   13443:     } else {
1.561     www      13444:         my $separator=',';
1.480     banghart 13445:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13446:             $separator=';';
1.480     banghart 13447:         }
1.31      albertel 13448:         my $i=0;
1.561     www      13449: # the character we are looking for to indicate the end of a quote or a record 
                   13450:         my $looking_for=$separator;
                   13451: # do not add the characters to the fields
                   13452:         my $ignore=0;
                   13453: # we just encountered a separator (or the beginning of the record)
                   13454:         my $just_found_separator=1;
                   13455: # store the field we are working on here
                   13456:         my $field='';
                   13457: # work our way through all characters in record
                   13458:         foreach my $character ($record=~/(.)/g) {
                   13459:             if ($character eq $looking_for) {
                   13460:                if ($character ne $separator) {
                   13461: # Found the end of a quote, again looking for separator
                   13462:                   $looking_for=$separator;
                   13463:                   $ignore=1;
                   13464:                } else {
                   13465: # Found a separator, store away what we got
                   13466:                   $components{&takeleft($i)}=$field;
                   13467: 	          $i++;
                   13468:                   $just_found_separator=1;
                   13469:                   $ignore=0;
                   13470:                   $field='';
                   13471:                }
                   13472:                next;
                   13473:             }
                   13474: # single or double quotation marks after a separator indicate beginning of a quote
                   13475: # we are now looking for the end of the quote and need to ignore separators
                   13476:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13477:                $looking_for=$character;
                   13478:                next;
                   13479:             }
                   13480: # ignore would be true after we reached the end of a quote
                   13481:             if ($ignore) { next; }
                   13482:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13483:             $field.=$character;
                   13484:             $just_found_separator=0; 
1.31      albertel 13485:         }
1.561     www      13486: # catch the very last entry, since we never encountered the separator
                   13487:         $components{&takeleft($i)}=$field;
1.31      albertel 13488:     }
                   13489:     return %components;
                   13490: }
                   13491: 
1.144     matthew  13492: ######################################################
                   13493: ######################################################
                   13494: 
1.56      matthew  13495: =pod
                   13496: 
1.648     raeburn  13497: =item * &upfile_select_html()
1.41      ng       13498: 
1.144     matthew  13499: Return HTML code to select a file from the users machine and specify 
                   13500: the file type.
1.41      ng       13501: 
                   13502: =cut
                   13503: 
1.144     matthew  13504: ######################################################
                   13505: ######################################################
1.31      albertel 13506: sub upfile_select_html {
1.144     matthew  13507:     my %Types = (
                   13508:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13509:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13510:                  space => &mt('Space separated'),
                   13511:                  tab   => &mt('Tabulator separated'),
                   13512: #                 xml   => &mt('HTML/XML'),
                   13513:                  );
                   13514:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13515:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13516:     foreach my $type (sort(keys(%Types))) {
                   13517:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13518:     }
                   13519:     $Str .= "</select>\n";
                   13520:     return $Str;
1.31      albertel 13521: }
                   13522: 
1.301     albertel 13523: sub get_samples {
                   13524:     my ($records,$toget) = @_;
                   13525:     my @samples=({});
                   13526:     my $got=0;
                   13527:     foreach my $rec (@$records) {
                   13528: 	my %temp = &record_sep($rec);
                   13529: 	if (! grep(/\S/, values(%temp))) { next; }
                   13530: 	if (%temp) {
                   13531: 	    $samples[$got]=\%temp;
                   13532: 	    $got++;
                   13533: 	    if ($got == $toget) { last; }
                   13534: 	}
                   13535:     }
                   13536:     return \@samples;
                   13537: }
                   13538: 
1.144     matthew  13539: ######################################################
                   13540: ######################################################
                   13541: 
1.56      matthew  13542: =pod
                   13543: 
1.648     raeburn  13544: =item * &csv_print_samples($r,$records)
1.41      ng       13545: 
                   13546: Prints a table of sample values from each column uploaded $r is an
                   13547: Apache Request ref, $records is an arrayref from
                   13548: &Apache::loncommon::upfile_record_sep
                   13549: 
                   13550: =cut
                   13551: 
1.144     matthew  13552: ######################################################
                   13553: ######################################################
1.31      albertel 13554: sub csv_print_samples {
                   13555:     my ($r,$records) = @_;
1.662     bisitz   13556:     my $samples = &get_samples($records,5);
1.301     albertel 13557: 
1.594     raeburn  13558:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13559:               &start_data_table_header_row());
1.356     albertel 13560:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13561:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13562:     $r->print(&end_data_table_header_row());
1.301     albertel 13563:     foreach my $hash (@$samples) {
1.594     raeburn  13564: 	$r->print(&start_data_table_row());
1.356     albertel 13565: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13566: 	    $r->print('<td>');
1.356     albertel 13567: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13568: 	    $r->print('</td>');
                   13569: 	}
1.594     raeburn  13570: 	$r->print(&end_data_table_row());
1.31      albertel 13571:     }
1.594     raeburn  13572:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13573: }
                   13574: 
1.144     matthew  13575: ######################################################
                   13576: ######################################################
                   13577: 
1.56      matthew  13578: =pod
                   13579: 
1.648     raeburn  13580: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13581: 
                   13582: Prints a table to create associations between values and table columns.
1.144     matthew  13583: 
1.41      ng       13584: $r is an Apache Request ref,
                   13585: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13586: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13587: 
                   13588: =cut
                   13589: 
1.144     matthew  13590: ######################################################
                   13591: ######################################################
1.31      albertel 13592: sub csv_print_select_table {
                   13593:     my ($r,$records,$d) = @_;
1.301     albertel 13594:     my $i=0;
                   13595:     my $samples = &get_samples($records,1);
1.144     matthew  13596:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13597: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13598:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13599:               '<th>'.&mt('Column').'</th>'.
                   13600:               &end_data_table_header_row()."\n");
1.356     albertel 13601:     foreach my $array_ref (@$d) {
                   13602: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13603: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13604: 
1.875     bisitz   13605: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13606: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13607: 	$r->print('<option value="none"></option>');
1.356     albertel 13608: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13609: 	    $r->print('<option value="'.$sample.'"'.
                   13610:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13611:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13612: 	}
1.594     raeburn  13613: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13614: 	$i++;
                   13615:     }
1.594     raeburn  13616:     $r->print(&end_data_table());
1.31      albertel 13617:     $i--;
                   13618:     return $i;
                   13619: }
1.56      matthew  13620: 
1.144     matthew  13621: ######################################################
                   13622: ######################################################
                   13623: 
1.56      matthew  13624: =pod
1.31      albertel 13625: 
1.648     raeburn  13626: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13627: 
                   13628: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13629: 
                   13630: $r is an Apache Request ref,
                   13631: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13632: $d is an array of 2 element arrays (internal name, displayed name)
                   13633: 
                   13634: =cut
                   13635: 
1.144     matthew  13636: ######################################################
                   13637: ######################################################
1.31      albertel 13638: sub csv_samples_select_table {
                   13639:     my ($r,$records,$d) = @_;
                   13640:     my $i=0;
1.144     matthew  13641:     #
1.662     bisitz   13642:     my $max_samples = 5;
                   13643:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13644:     $r->print(&start_data_table().
                   13645:               &start_data_table_header_row().'<th>'.
                   13646:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13647:               &end_data_table_header_row());
1.301     albertel 13648: 
                   13649:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13650: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13651: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13652: 	foreach my $option (@$d) {
                   13653: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13654: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13655:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13656:                       $display.'</option>');
1.31      albertel 13657: 	}
                   13658: 	$r->print('</select></td><td>');
1.662     bisitz   13659: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13660: 	    if (defined($samples->[$line]{$key})) { 
                   13661: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13662: 	    }
                   13663: 	}
1.594     raeburn  13664: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13665: 	$i++;
                   13666:     }
1.594     raeburn  13667:     $r->print(&end_data_table());
1.31      albertel 13668:     $i--;
                   13669:     return($i);
1.115     matthew  13670: }
                   13671: 
1.144     matthew  13672: ######################################################
                   13673: ######################################################
                   13674: 
1.115     matthew  13675: =pod
                   13676: 
1.648     raeburn  13677: =item * &clean_excel_name($name)
1.115     matthew  13678: 
                   13679: Returns a replacement for $name which does not contain any illegal characters.
                   13680: 
                   13681: =cut
                   13682: 
1.144     matthew  13683: ######################################################
                   13684: ######################################################
1.115     matthew  13685: sub clean_excel_name {
                   13686:     my ($name) = @_;
                   13687:     $name =~ s/[:\*\?\/\\]//g;
                   13688:     if (length($name) > 31) {
                   13689:         $name = substr($name,0,31);
                   13690:     }
                   13691:     return $name;
1.25      albertel 13692: }
1.84      albertel 13693: 
1.85      albertel 13694: =pod
                   13695: 
1.648     raeburn  13696: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13697: 
                   13698: Returns either 1 or undef
                   13699: 
                   13700: 1 if the part is to be hidden, undef if it is to be shown
                   13701: 
                   13702: Arguments are:
                   13703: 
                   13704: $id the id of the part to be checked
                   13705: $symb, optional the symb of the resource to check
                   13706: $udom, optional the domain of the user to check for
                   13707: $uname, optional the username of the user to check for
                   13708: 
                   13709: =cut
1.84      albertel 13710: 
                   13711: sub check_if_partid_hidden {
                   13712:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13713:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13714: 					 $symb,$udom,$uname);
1.141     albertel 13715:     my $truth=1;
                   13716:     #if the string starts with !, then the list is the list to show not hide
                   13717:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13718:     my @hiddenlist=split(/,/,$hiddenparts);
                   13719:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13720: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13721:     }
1.141     albertel 13722:     return !$truth;
1.84      albertel 13723: }
1.127     matthew  13724: 
1.138     matthew  13725: 
                   13726: ############################################################
                   13727: ############################################################
                   13728: 
                   13729: =pod
                   13730: 
1.157     matthew  13731: =back 
                   13732: 
1.138     matthew  13733: =head1 cgi-bin script and graphing routines
                   13734: 
1.157     matthew  13735: =over 4
                   13736: 
1.648     raeburn  13737: =item * &get_cgi_id()
1.138     matthew  13738: 
                   13739: Inputs: none
                   13740: 
                   13741: Returns an id which can be used to pass environment variables
                   13742: to various cgi-bin scripts.  These environment variables will
                   13743: be removed from the users environment after a given time by
                   13744: the routine &Apache::lonnet::transfer_profile_to_env.
                   13745: 
                   13746: =cut
                   13747: 
                   13748: ############################################################
                   13749: ############################################################
1.152     albertel 13750: my $uniq=0;
1.136     matthew  13751: sub get_cgi_id {
1.154     albertel 13752:     $uniq=($uniq+1)%100000;
1.280     albertel 13753:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13754: }
                   13755: 
1.127     matthew  13756: ############################################################
                   13757: ############################################################
                   13758: 
                   13759: =pod
                   13760: 
1.648     raeburn  13761: =item * &DrawBarGraph()
1.127     matthew  13762: 
1.138     matthew  13763: Facilitates the plotting of data in a (stacked) bar graph.
                   13764: Puts plot definition data into the users environment in order for 
                   13765: graph.png to plot it.  Returns an <img> tag for the plot.
                   13766: The bars on the plot are labeled '1','2',...,'n'.
                   13767: 
                   13768: Inputs:
                   13769: 
                   13770: =over 4
                   13771: 
                   13772: =item $Title: string, the title of the plot
                   13773: 
                   13774: =item $xlabel: string, text describing the X-axis of the plot
                   13775: 
                   13776: =item $ylabel: string, text describing the Y-axis of the plot
                   13777: 
                   13778: =item $Max: scalar, the maximum Y value to use in the plot
                   13779: If $Max is < any data point, the graph will not be rendered.
                   13780: 
1.140     matthew  13781: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13782: they are plotted.  If undefined, default values will be used.
                   13783: 
1.178     matthew  13784: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13785: 
1.138     matthew  13786: =item @Values: An array of array references.  Each array reference holds data
                   13787: to be plotted in a stacked bar chart.
                   13788: 
1.239     matthew  13789: =item If the final element of @Values is a hash reference the key/value
                   13790: pairs will be added to the graph definition.
                   13791: 
1.138     matthew  13792: =back
                   13793: 
                   13794: Returns:
                   13795: 
                   13796: An <img> tag which references graph.png and the appropriate identifying
                   13797: information for the plot.
                   13798: 
1.127     matthew  13799: =cut
                   13800: 
                   13801: ############################################################
                   13802: ############################################################
1.134     matthew  13803: sub DrawBarGraph {
1.178     matthew  13804:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13805:     #
                   13806:     if (! defined($colors)) {
                   13807:         $colors = ['#33ff00', 
                   13808:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13809:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13810:                   ]; 
                   13811:     }
1.228     matthew  13812:     my $extra_settings = {};
                   13813:     if (ref($Values[-1]) eq 'HASH') {
                   13814:         $extra_settings = pop(@Values);
                   13815:     }
1.127     matthew  13816:     #
1.136     matthew  13817:     my $identifier = &get_cgi_id();
                   13818:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13819:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13820:         return '';
                   13821:     }
1.225     matthew  13822:     #
                   13823:     my @Labels;
                   13824:     if (defined($labels)) {
                   13825:         @Labels = @$labels;
                   13826:     } else {
                   13827:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13828:             push(@Labels,$i+1);
1.225     matthew  13829:         }
                   13830:     }
                   13831:     #
1.129     matthew  13832:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13833:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13834:     my %ValuesHash;
                   13835:     my $NumSets=1;
                   13836:     foreach my $array (@Values) {
                   13837:         next if (! ref($array));
1.136     matthew  13838:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13839:             join(',',@$array);
1.129     matthew  13840:     }
1.127     matthew  13841:     #
1.136     matthew  13842:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13843:     if ($NumBars < 3) {
                   13844:         $width = 120+$NumBars*32;
1.220     matthew  13845:         $xskip = 1;
1.225     matthew  13846:         $bar_width = 30;
                   13847:     } elsif ($NumBars < 5) {
                   13848:         $width = 120+$NumBars*20;
                   13849:         $xskip = 1;
                   13850:         $bar_width = 20;
1.220     matthew  13851:     } elsif ($NumBars < 10) {
1.136     matthew  13852:         $width = 120+$NumBars*15;
                   13853:         $xskip = 1;
                   13854:         $bar_width = 15;
                   13855:     } elsif ($NumBars <= 25) {
                   13856:         $width = 120+$NumBars*11;
                   13857:         $xskip = 5;
                   13858:         $bar_width = 8;
                   13859:     } elsif ($NumBars <= 50) {
                   13860:         $width = 120+$NumBars*8;
                   13861:         $xskip = 5;
                   13862:         $bar_width = 4;
                   13863:     } else {
                   13864:         $width = 120+$NumBars*8;
                   13865:         $xskip = 5;
                   13866:         $bar_width = 4;
                   13867:     }
                   13868:     #
1.137     matthew  13869:     $Max = 1 if ($Max < 1);
                   13870:     if ( int($Max) < $Max ) {
                   13871:         $Max++;
                   13872:         $Max = int($Max);
                   13873:     }
1.127     matthew  13874:     $Title  = '' if (! defined($Title));
                   13875:     $xlabel = '' if (! defined($xlabel));
                   13876:     $ylabel = '' if (! defined($ylabel));
1.369     www      13877:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13878:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13879:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13880:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13881:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13882:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13883:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13884:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13885:     $ValuesHash{$id.'.height'}   = $height;
                   13886:     $ValuesHash{$id.'.width'}    = $width;
                   13887:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13888:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13889:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13890:     #
1.228     matthew  13891:     # Deal with other parameters
                   13892:     while (my ($key,$value) = each(%$extra_settings)) {
                   13893:         $ValuesHash{$id.'.'.$key} = $value;
                   13894:     }
                   13895:     #
1.646     raeburn  13896:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13897:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13898: }
                   13899: 
                   13900: ############################################################
                   13901: ############################################################
                   13902: 
                   13903: =pod
                   13904: 
1.648     raeburn  13905: =item * &DrawXYGraph()
1.137     matthew  13906: 
1.138     matthew  13907: Facilitates the plotting of data in an XY graph.
                   13908: Puts plot definition data into the users environment in order for 
                   13909: graph.png to plot it.  Returns an <img> tag for the plot.
                   13910: 
                   13911: Inputs:
                   13912: 
                   13913: =over 4
                   13914: 
                   13915: =item $Title: string, the title of the plot
                   13916: 
                   13917: =item $xlabel: string, text describing the X-axis of the plot
                   13918: 
                   13919: =item $ylabel: string, text describing the Y-axis of the plot
                   13920: 
                   13921: =item $Max: scalar, the maximum Y value to use in the plot
                   13922: If $Max is < any data point, the graph will not be rendered.
                   13923: 
                   13924: =item $colors: Array ref containing the hex color codes for the data to be 
                   13925: plotted in.  If undefined, default values will be used.
                   13926: 
                   13927: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13928: 
                   13929: =item $Ydata: Array ref containing Array refs.  
1.185     www      13930: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13931: 
                   13932: =item %Values: hash indicating or overriding any default values which are 
                   13933: passed to graph.png.  
                   13934: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13935: 
                   13936: =back
                   13937: 
                   13938: Returns:
                   13939: 
                   13940: An <img> tag which references graph.png and the appropriate identifying
                   13941: information for the plot.
                   13942: 
1.137     matthew  13943: =cut
                   13944: 
                   13945: ############################################################
                   13946: ############################################################
                   13947: sub DrawXYGraph {
                   13948:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13949:     #
                   13950:     # Create the identifier for the graph
                   13951:     my $identifier = &get_cgi_id();
                   13952:     my $id = 'cgi.'.$identifier;
                   13953:     #
                   13954:     $Title  = '' if (! defined($Title));
                   13955:     $xlabel = '' if (! defined($xlabel));
                   13956:     $ylabel = '' if (! defined($ylabel));
                   13957:     my %ValuesHash = 
                   13958:         (
1.369     www      13959:          $id.'.title'  => &escape($Title),
                   13960:          $id.'.xlabel' => &escape($xlabel),
                   13961:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13962:          $id.'.y_max_value'=> $Max,
                   13963:          $id.'.labels'     => join(',',@$Xlabels),
                   13964:          $id.'.PlotType'   => 'XY',
                   13965:          );
                   13966:     #
                   13967:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13968:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13969:     }
                   13970:     #
                   13971:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13972:         return '';
                   13973:     }
                   13974:     my $NumSets=1;
1.138     matthew  13975:     foreach my $array (@{$Ydata}){
1.137     matthew  13976:         next if (! ref($array));
                   13977:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13978:     }
1.138     matthew  13979:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13980:     #
                   13981:     # Deal with other parameters
                   13982:     while (my ($key,$value) = each(%Values)) {
                   13983:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13984:     }
                   13985:     #
1.646     raeburn  13986:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13987:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13988: }
                   13989: 
                   13990: ############################################################
                   13991: ############################################################
                   13992: 
                   13993: =pod
                   13994: 
1.648     raeburn  13995: =item * &DrawXYYGraph()
1.138     matthew  13996: 
                   13997: Facilitates the plotting of data in an XY graph with two Y axes.
                   13998: Puts plot definition data into the users environment in order for 
                   13999: graph.png to plot it.  Returns an <img> tag for the plot.
                   14000: 
                   14001: Inputs:
                   14002: 
                   14003: =over 4
                   14004: 
                   14005: =item $Title: string, the title of the plot
                   14006: 
                   14007: =item $xlabel: string, text describing the X-axis of the plot
                   14008: 
                   14009: =item $ylabel: string, text describing the Y-axis of the plot
                   14010: 
                   14011: =item $colors: Array ref containing the hex color codes for the data to be 
                   14012: plotted in.  If undefined, default values will be used.
                   14013: 
                   14014: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14015: 
                   14016: =item $Ydata1: The first data set
                   14017: 
                   14018: =item $Min1: The minimum value of the left Y-axis
                   14019: 
                   14020: =item $Max1: The maximum value of the left Y-axis
                   14021: 
                   14022: =item $Ydata2: The second data set
                   14023: 
                   14024: =item $Min2: The minimum value of the right Y-axis
                   14025: 
                   14026: =item $Max2: The maximum value of the left Y-axis
                   14027: 
                   14028: =item %Values: hash indicating or overriding any default values which are 
                   14029: passed to graph.png.  
                   14030: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14031: 
                   14032: =back
                   14033: 
                   14034: Returns:
                   14035: 
                   14036: An <img> tag which references graph.png and the appropriate identifying
                   14037: information for the plot.
1.136     matthew  14038: 
                   14039: =cut
                   14040: 
                   14041: ############################################################
                   14042: ############################################################
1.137     matthew  14043: sub DrawXYYGraph {
                   14044:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14045:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14046:     #
                   14047:     # Create the identifier for the graph
                   14048:     my $identifier = &get_cgi_id();
                   14049:     my $id = 'cgi.'.$identifier;
                   14050:     #
                   14051:     $Title  = '' if (! defined($Title));
                   14052:     $xlabel = '' if (! defined($xlabel));
                   14053:     $ylabel = '' if (! defined($ylabel));
                   14054:     my %ValuesHash = 
                   14055:         (
1.369     www      14056:          $id.'.title'  => &escape($Title),
                   14057:          $id.'.xlabel' => &escape($xlabel),
                   14058:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14059:          $id.'.labels' => join(',',@$Xlabels),
                   14060:          $id.'.PlotType' => 'XY',
                   14061:          $id.'.NumSets' => 2,
1.137     matthew  14062:          $id.'.two_axes' => 1,
                   14063:          $id.'.y1_max_value' => $Max1,
                   14064:          $id.'.y1_min_value' => $Min1,
                   14065:          $id.'.y2_max_value' => $Max2,
                   14066:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14067:          );
                   14068:     #
1.137     matthew  14069:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14070:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14071:     }
                   14072:     #
                   14073:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14074:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14075:         return '';
                   14076:     }
                   14077:     my $NumSets=1;
1.137     matthew  14078:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14079:         next if (! ref($array));
                   14080:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14081:     }
                   14082:     #
                   14083:     # Deal with other parameters
                   14084:     while (my ($key,$value) = each(%Values)) {
                   14085:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14086:     }
                   14087:     #
1.646     raeburn  14088:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14089:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14090: }
                   14091: 
                   14092: ############################################################
                   14093: ############################################################
                   14094: 
                   14095: =pod
                   14096: 
1.157     matthew  14097: =back 
                   14098: 
1.139     matthew  14099: =head1 Statistics helper routines?  
                   14100: 
                   14101: Bad place for them but what the hell.
                   14102: 
1.157     matthew  14103: =over 4
                   14104: 
1.648     raeburn  14105: =item * &chartlink()
1.139     matthew  14106: 
                   14107: Returns a link to the chart for a specific student.  
                   14108: 
                   14109: Inputs:
                   14110: 
                   14111: =over 4
                   14112: 
                   14113: =item $linktext: The text of the link
                   14114: 
                   14115: =item $sname: The students username
                   14116: 
                   14117: =item $sdomain: The students domain
                   14118: 
                   14119: =back
                   14120: 
1.157     matthew  14121: =back
                   14122: 
1.139     matthew  14123: =cut
                   14124: 
                   14125: ############################################################
                   14126: ############################################################
                   14127: sub chartlink {
                   14128:     my ($linktext, $sname, $sdomain) = @_;
                   14129:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14130:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14131:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14132:        '">'.$linktext.'</a>';
1.153     matthew  14133: }
                   14134: 
                   14135: #######################################################
                   14136: #######################################################
                   14137: 
                   14138: =pod
                   14139: 
                   14140: =head1 Course Environment Routines
1.157     matthew  14141: 
                   14142: =over 4
1.153     matthew  14143: 
1.648     raeburn  14144: =item * &restore_course_settings()
1.153     matthew  14145: 
1.648     raeburn  14146: =item * &store_course_settings()
1.153     matthew  14147: 
                   14148: Restores/Store indicated form parameters from the course environment.
                   14149: Will not overwrite existing values of the form parameters.
                   14150: 
                   14151: Inputs: 
                   14152: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14153: 
                   14154: a hash ref describing the data to be stored.  For example:
                   14155:    
                   14156: %Save_Parameters = ('Status' => 'scalar',
                   14157:     'chartoutputmode' => 'scalar',
                   14158:     'chartoutputdata' => 'scalar',
                   14159:     'Section' => 'array',
1.373     raeburn  14160:     'Group' => 'array',
1.153     matthew  14161:     'StudentData' => 'array',
                   14162:     'Maps' => 'array');
                   14163: 
                   14164: Returns: both routines return nothing
                   14165: 
1.631     raeburn  14166: =back
                   14167: 
1.153     matthew  14168: =cut
                   14169: 
                   14170: #######################################################
                   14171: #######################################################
                   14172: sub store_course_settings {
1.496     albertel 14173:     return &store_settings($env{'request.course.id'},@_);
                   14174: }
                   14175: 
                   14176: sub store_settings {
1.153     matthew  14177:     # save to the environment
                   14178:     # appenv the same items, just to be safe
1.300     albertel 14179:     my $udom  = $env{'user.domain'};
                   14180:     my $uname = $env{'user.name'};
1.496     albertel 14181:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14182:     my %SaveHash;
                   14183:     my %AppHash;
                   14184:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14185:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14186:         my $envname = 'environment.'.$basename;
1.258     albertel 14187:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14188:             # Save this value away
                   14189:             if ($type eq 'scalar' &&
1.258     albertel 14190:                 (! exists($env{$envname}) || 
                   14191:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14192:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14193:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14194:             } elsif ($type eq 'array') {
                   14195:                 my $stored_form;
1.258     albertel 14196:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14197:                     $stored_form = join(',',
                   14198:                                         map {
1.369     www      14199:                                             &escape($_);
1.258     albertel 14200:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14201:                 } else {
                   14202:                     $stored_form = 
1.369     www      14203:                         &escape($env{'form.'.$setting});
1.153     matthew  14204:                 }
                   14205:                 # Determine if the array contents are the same.
1.258     albertel 14206:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14207:                     $SaveHash{$basename} = $stored_form;
                   14208:                     $AppHash{$envname}   = $stored_form;
                   14209:                 }
                   14210:             }
                   14211:         }
                   14212:     }
                   14213:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14214:                                           $udom,$uname);
1.153     matthew  14215:     if ($put_result !~ /^(ok|delayed)/) {
                   14216:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14217:                                  'got error:'.$put_result);
                   14218:     }
                   14219:     # Make sure these settings stick around in this session, too
1.646     raeburn  14220:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14221:     return;
                   14222: }
                   14223: 
                   14224: sub restore_course_settings {
1.499     albertel 14225:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14226: }
                   14227: 
                   14228: sub restore_settings {
                   14229:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14230:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14231:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14232:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14233:             '.'.$setting;
1.258     albertel 14234:         if (exists($env{$envname})) {
1.153     matthew  14235:             if ($type eq 'scalar') {
1.258     albertel 14236:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14237:             } elsif ($type eq 'array') {
1.258     albertel 14238:                 $env{'form.'.$setting} = [ 
1.153     matthew  14239:                                            map { 
1.369     www      14240:                                                &unescape($_); 
1.258     albertel 14241:                                            } split(',',$env{$envname})
1.153     matthew  14242:                                            ];
                   14243:             }
                   14244:         }
                   14245:     }
1.127     matthew  14246: }
                   14247: 
1.618     raeburn  14248: #######################################################
                   14249: #######################################################
                   14250: 
                   14251: =pod
                   14252: 
                   14253: =head1 Domain E-mail Routines  
                   14254: 
                   14255: =over 4
                   14256: 
1.648     raeburn  14257: =item * &build_recipient_list()
1.618     raeburn  14258: 
1.1075.2.44  raeburn  14259: Build recipient lists for following types of e-mail:
1.766     raeburn  14260: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14261: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14262: module change checking, student/employee ID conflict checks, as
                   14263: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14264: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14265: 
                   14266: Inputs:
1.1075.2.44  raeburn  14267: defmail (scalar - email address of default recipient),
                   14268: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14269: requestsmail, updatesmail, or idconflictsmail).
                   14270: 
1.619     raeburn  14271: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14272: 
                   14273: origmail (scalar - email address of recipient from loncapa.conf,
                   14274: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14275: 
1.1075.2.139  raeburn  14276: $requname username of requester (if mailing type is helpdeskmail)
                   14277: 
                   14278: $requdom domain of requester (if mailing type is helpdeskmail)
                   14279: 
                   14280: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14281: 
1.655     raeburn  14282: Returns: comma separated list of addresses to which to send e-mail.
                   14283: 
                   14284: =back
1.618     raeburn  14285: 
                   14286: =cut
                   14287: 
                   14288: ############################################################
                   14289: ############################################################
                   14290: sub build_recipient_list {
1.1075.2.139  raeburn  14291:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14292:     my @recipients;
1.1075.2.122  raeburn  14293:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14294:     my %domconfig =
1.1075.2.122  raeburn  14295:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14296:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14297:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14298:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14299:                 my @contacts = ('adminemail','supportemail');
                   14300:                 foreach my $item (@contacts) {
                   14301:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14302:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14303:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14304:                             push(@recipients,$addr);
                   14305:                         }
1.619     raeburn  14306:                     }
1.1075.2.122  raeburn  14307:                 }
                   14308:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14309:                 if ($mailing eq 'helpdeskmail') {
                   14310:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14311:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14312:                         my @ok_bccs;
                   14313:                         foreach my $bcc (@bccs) {
                   14314:                             $bcc =~ s/^\s+//g;
                   14315:                             $bcc =~ s/\s+$//g;
                   14316:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14317:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14318:                                     push(@ok_bccs,$bcc);
                   14319:                                 }
                   14320:                             }
                   14321:                         }
                   14322:                         if (@ok_bccs > 0) {
                   14323:                             $allbcc = join(', ',@ok_bccs);
                   14324:                         }
                   14325:                     }
                   14326:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14327:                 }
                   14328:             }
1.766     raeburn  14329:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14330:             $lastresort = $origmail;
1.618     raeburn  14331:         }
1.1075.2.139  raeburn  14332:         if ($mailing eq 'helpdeskmail') {
                   14333:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14334:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14335:                 my ($inststatus,$inststatus_checked);
                   14336:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14337:                     ($env{'user.domain'} ne 'public')) {
                   14338:                     $inststatus_checked = 1;
                   14339:                     $inststatus = $env{'environment.inststatus'};
                   14340:                 }
                   14341:                 unless ($inststatus_checked) {
                   14342:                     if (($requname ne '') && ($requdom ne '')) {
                   14343:                         if (($requname =~ /^$match_username$/) &&
                   14344:                             ($requdom =~ /^$match_domain$/) &&
                   14345:                             (&Apache::lonnet::domain($requdom))) {
                   14346:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14347:                                                                       $requdom);
                   14348:                             unless ($requhome eq 'no_host') {
                   14349:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14350:                                 $inststatus = $userenv{'inststatus'};
                   14351:                                 $inststatus_checked = 1;
                   14352:                             }
                   14353:                         }
                   14354:                     }
                   14355:                 }
                   14356:                 unless ($inststatus_checked) {
                   14357:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14358:                         my %srch = (srchby     => 'email',
                   14359:                                     srchdomain => $defdom,
                   14360:                                     srchterm   => $reqemail,
                   14361:                                     srchtype   => 'exact');
                   14362:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14363:                         foreach my $uname (keys(%srch_results)) {
                   14364:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14365:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14366:                                 $inststatus_checked = 1;
                   14367:                                 last;
                   14368:                             }
                   14369:                         }
                   14370:                         unless ($inststatus_checked) {
                   14371:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14372:                             if ($dirsrchres eq 'ok') {
                   14373:                                 foreach my $uname (keys(%srch_results)) {
                   14374:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14375:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14376:                                         $inststatus_checked = 1;
                   14377:                                         last;
                   14378:                                     }
                   14379:                                 }
                   14380:                             }
                   14381:                         }
                   14382:                     }
                   14383:                 }
                   14384:                 if ($inststatus ne '') {
                   14385:                     foreach my $status (split(/\:/,$inststatus)) {
                   14386:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14387:                             my @contacts = ('adminemail','supportemail');
                   14388:                             foreach my $item (@contacts) {
                   14389:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14390:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14391:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14392:                                         push(@recipients,$addr);
                   14393:                                     }
                   14394:                                 }
                   14395:                             }
                   14396:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14397:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14398:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14399:                                 my @ok_bccs;
                   14400:                                 foreach my $bcc (@bccs) {
                   14401:                                     $bcc =~ s/^\s+//g;
                   14402:                                     $bcc =~ s/\s+$//g;
                   14403:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14404:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14405:                                             push(@ok_bccs,$bcc);
                   14406:                                         }
                   14407:                                     }
                   14408:                                 }
                   14409:                                 if (@ok_bccs > 0) {
                   14410:                                     $allbcc = join(', ',@ok_bccs);
                   14411:                                 }
                   14412:                             }
                   14413:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14414:                             last;
                   14415:                         }
                   14416:                     }
                   14417:                 }
                   14418:             }
                   14419:         }
1.619     raeburn  14420:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14421:         $lastresort = $origmail;
                   14422:     }
1.1075.2.128  raeburn  14423:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14424:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14425:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14426:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14427:             my %what = (
                   14428:                           perlvar => 1,
                   14429:                        );
                   14430:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14431:             if ($primary) {
                   14432:                 my $gotaddr;
                   14433:                 my ($result,$returnhash) =
                   14434:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14435:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14436:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14437:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14438:                         $gotaddr = 1;
                   14439:                     }
                   14440:                 }
                   14441:                 unless ($gotaddr) {
                   14442:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14443:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14444:                     unless ($uintdom eq $intdom) {
                   14445:                         my %domconfig =
                   14446:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14447:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14448:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14449:                                 my @contacts = ('adminemail','supportemail');
                   14450:                                 foreach my $item (@contacts) {
                   14451:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14452:                                         my $addr = $domconfig{'contacts'}{$item};
                   14453:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14454:                                             push(@recipients,$addr);
                   14455:                                         }
                   14456:                                     }
                   14457:                                 }
                   14458:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14459:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14460:                                 }
                   14461:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14462:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14463:                                     my @ok_bccs;
                   14464:                                     foreach my $bcc (@bccs) {
                   14465:                                         $bcc =~ s/^\s+//g;
                   14466:                                         $bcc =~ s/\s+$//g;
                   14467:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14468:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14469:                                                 push(@ok_bccs,$bcc);
                   14470:                                             }
                   14471:                                         }
                   14472:                                     }
                   14473:                                     if (@ok_bccs > 0) {
                   14474:                                         $allbcc = join(', ',@ok_bccs);
                   14475:                                     }
                   14476:                                 }
                   14477:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14478:                             }
                   14479:                         }
                   14480:                     }
                   14481:                 }
                   14482:             }
                   14483:         }
1.618     raeburn  14484:     }
1.688     raeburn  14485:     if (defined($defmail)) {
                   14486:         if ($defmail ne '') {
                   14487:             push(@recipients,$defmail);
                   14488:         }
1.618     raeburn  14489:     }
                   14490:     if ($otheremails) {
1.619     raeburn  14491:         my @others;
                   14492:         if ($otheremails =~ /,/) {
                   14493:             @others = split(/,/,$otheremails);
1.618     raeburn  14494:         } else {
1.619     raeburn  14495:             push(@others,$otheremails);
                   14496:         }
                   14497:         foreach my $addr (@others) {
                   14498:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14499:                 push(@recipients,$addr);
                   14500:             }
1.618     raeburn  14501:         }
                   14502:     }
1.1075.2.128  raeburn  14503:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14504:         if ((!@recipients) && ($lastresort ne '')) {
                   14505:             push(@recipients,$lastresort);
                   14506:         }
                   14507:     } elsif ($lastresort ne '') {
                   14508:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14509:             push(@recipients,$lastresort);
                   14510:         }
                   14511:     }
                   14512:     my $recipientlist = join(',',@recipients);
                   14513:     if (wantarray) {
                   14514:         return ($recipientlist,$allbcc,$addtext);
                   14515:     } else {
                   14516:         return $recipientlist;
                   14517:     }
1.618     raeburn  14518: }
                   14519: 
1.127     matthew  14520: ############################################################
                   14521: ############################################################
1.154     albertel 14522: 
1.655     raeburn  14523: =pod
                   14524: 
                   14525: =head1 Course Catalog Routines
                   14526: 
                   14527: =over 4
                   14528: 
                   14529: =item * &gather_categories()
                   14530: 
                   14531: Converts category definitions - keys of categories hash stored in  
                   14532: coursecategories in configuration.db on the primary library server in a 
                   14533: domain - to an array.  Also generates javascript and idx hash used to 
                   14534: generate Domain Coordinator interface for editing Course Categories.
                   14535: 
                   14536: Inputs:
1.663     raeburn  14537: 
1.655     raeburn  14538: categories (reference to hash of category definitions).
1.663     raeburn  14539: 
1.655     raeburn  14540: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14541:       categories and subcategories).
1.663     raeburn  14542: 
1.655     raeburn  14543: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14544:       editing Course Categories).
1.663     raeburn  14545: 
1.655     raeburn  14546: jsarray (reference to array of categories used to create Javascript arrays for
                   14547:          Domain Coordinator interface for editing Course Categories).
                   14548: 
                   14549: Returns: nothing
                   14550: 
                   14551: Side effects: populates cats, idx and jsarray. 
                   14552: 
                   14553: =cut
                   14554: 
                   14555: sub gather_categories {
                   14556:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14557:     my %counters;
                   14558:     my $num = 0;
                   14559:     foreach my $item (keys(%{$categories})) {
                   14560:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14561:         if ($container eq '' && $depth == 0) {
                   14562:             $cats->[$depth][$categories->{$item}] = $cat;
                   14563:         } else {
                   14564:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14565:         }
                   14566:         my ($escitem,$tail) = split(/:/,$item,2);
                   14567:         if ($counters{$tail} eq '') {
                   14568:             $counters{$tail} = $num;
                   14569:             $num ++;
                   14570:         }
                   14571:         if (ref($idx) eq 'HASH') {
                   14572:             $idx->{$item} = $counters{$tail};
                   14573:         }
                   14574:         if (ref($jsarray) eq 'ARRAY') {
                   14575:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14576:         }
                   14577:     }
                   14578:     return;
                   14579: }
                   14580: 
                   14581: =pod
                   14582: 
                   14583: =item * &extract_categories()
                   14584: 
                   14585: Used to generate breadcrumb trails for course categories.
                   14586: 
                   14587: Inputs:
1.663     raeburn  14588: 
1.655     raeburn  14589: categories (reference to hash of category definitions).
1.663     raeburn  14590: 
1.655     raeburn  14591: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14592:       categories and subcategories).
1.663     raeburn  14593: 
1.655     raeburn  14594: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14595: 
1.655     raeburn  14596: allitems (reference to hash - key is category key 
                   14597:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14598: 
1.655     raeburn  14599: idx (reference to hash of counters used in Domain Coordinator interface for
                   14600:       editing Course Categories).
1.663     raeburn  14601: 
1.655     raeburn  14602: jsarray (reference to array of categories used to create Javascript arrays for
                   14603:          Domain Coordinator interface for editing Course Categories).
                   14604: 
1.665     raeburn  14605: subcats (reference to hash of arrays containing all subcategories within each 
                   14606:          category, -recursive)
                   14607: 
1.1075.2.132  raeburn  14608: maxd (reference to hash used to hold max depth for all top-level categories).
                   14609: 
1.655     raeburn  14610: Returns: nothing
                   14611: 
                   14612: Side effects: populates trails and allitems hash references.
                   14613: 
                   14614: =cut
                   14615: 
                   14616: sub extract_categories {
1.1075.2.132  raeburn  14617:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14618:     if (ref($categories) eq 'HASH') {
                   14619:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14620:         if (ref($cats->[0]) eq 'ARRAY') {
                   14621:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14622:                 my $name = $cats->[0][$i];
                   14623:                 my $item = &escape($name).'::0';
                   14624:                 my $trailstr;
                   14625:                 if ($name eq 'instcode') {
                   14626:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14627:                 } elsif ($name eq 'communities') {
                   14628:                     $trailstr = &mt('Communities');
1.655     raeburn  14629:                 } else {
                   14630:                     $trailstr = $name;
                   14631:                 }
                   14632:                 if ($allitems->{$item} eq '') {
                   14633:                     push(@{$trails},$trailstr);
                   14634:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14635:                 }
                   14636:                 my @parents = ($name);
                   14637:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14638:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14639:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14640:                         if (ref($subcats) eq 'HASH') {
                   14641:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14642:                         }
1.1075.2.132  raeburn  14643:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14644:                     }
                   14645:                 } else {
                   14646:                     if (ref($subcats) eq 'HASH') {
                   14647:                         $subcats->{$item} = [];
1.655     raeburn  14648:                     }
1.1075.2.132  raeburn  14649:                     if (ref($maxd) eq 'HASH') {
                   14650:                         $maxd->{$name} = 1;
                   14651:                     }
1.655     raeburn  14652:                 }
                   14653:             }
                   14654:         }
                   14655:     }
                   14656:     return;
                   14657: }
                   14658: 
                   14659: =pod
                   14660: 
1.1075.2.56  raeburn  14661: =item * &recurse_categories()
1.655     raeburn  14662: 
                   14663: Recursively used to generate breadcrumb trails for course categories.
                   14664: 
                   14665: Inputs:
1.663     raeburn  14666: 
1.655     raeburn  14667: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14668:       categories and subcategories).
1.663     raeburn  14669: 
1.655     raeburn  14670: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14671: 
                   14672: category (current course category, for which breadcrumb trail is being generated).
                   14673: 
                   14674: trails (reference to array of breadcrumb trails for each category).
                   14675: 
1.655     raeburn  14676: allitems (reference to hash - key is category key
                   14677:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14678: 
1.655     raeburn  14679: parents (array containing containers directories for current category, 
                   14680:          back to top level). 
                   14681: 
                   14682: Returns: nothing
                   14683: 
                   14684: Side effects: populates trails and allitems hash references
                   14685: 
                   14686: =cut
                   14687: 
                   14688: sub recurse_categories {
1.1075.2.132  raeburn  14689:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14690:     my $shallower = $depth - 1;
                   14691:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14692:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14693:             my $name = $cats->[$depth]{$category}[$k];
                   14694:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14695:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14696:             if ($allitems->{$item} eq '') {
                   14697:                 push(@{$trails},$trailstr);
                   14698:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14699:             }
                   14700:             my $deeper = $depth+1;
                   14701:             push(@{$parents},$category);
1.665     raeburn  14702:             if (ref($subcats) eq 'HASH') {
                   14703:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14704:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14705:                     my $higher;
                   14706:                     if ($j > 0) {
                   14707:                         $higher = &escape($parents->[$j]).':'.
                   14708:                                   &escape($parents->[$j-1]).':'.$j;
                   14709:                     } else {
                   14710:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14711:                     }
                   14712:                     push(@{$subcats->{$higher}},$subcat);
                   14713:                 }
                   14714:             }
                   14715:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14716:                                 $subcats,$maxd);
1.655     raeburn  14717:             pop(@{$parents});
                   14718:         }
                   14719:     } else {
                   14720:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14721:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14722:         if ($allitems->{$item} eq '') {
                   14723:             push(@{$trails},$trailstr);
                   14724:             $allitems->{$item} = scalar(@{$trails})-1;
                   14725:         }
1.1075.2.132  raeburn  14726:         if (ref($maxd) eq 'HASH') {
                   14727:             if ($depth > $maxd->{$parents->[0]}) {
                   14728:                 $maxd->{$parents->[0]} = $depth;
                   14729:             }
                   14730:         }
1.655     raeburn  14731:     }
                   14732:     return;
                   14733: }
                   14734: 
1.663     raeburn  14735: =pod
                   14736: 
1.1075.2.56  raeburn  14737: =item * &assign_categories_table()
1.663     raeburn  14738: 
                   14739: Create a datatable for display of hierarchical categories in a domain,
                   14740: with checkboxes to allow a course to be categorized. 
                   14741: 
                   14742: Inputs:
                   14743: 
                   14744: cathash - reference to hash of categories defined for the domain (from
                   14745:           configuration.db)
                   14746: 
                   14747: currcat - scalar with an & separated list of categories assigned to a course. 
                   14748: 
1.919     raeburn  14749: type    - scalar contains course type (Course or Community).
                   14750: 
1.1075.2.117  raeburn  14751: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14752:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14753: 
1.663     raeburn  14754: Returns: $output (markup to be displayed) 
                   14755: 
                   14756: =cut
                   14757: 
                   14758: sub assign_categories_table {
1.1075.2.117  raeburn  14759:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14760:     my $output;
                   14761:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14762:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14763:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14764:         $maxdepth = scalar(@cats);
                   14765:         if (@cats > 0) {
                   14766:             my $itemcount = 0;
                   14767:             if (ref($cats[0]) eq 'ARRAY') {
                   14768:                 my @currcategories;
                   14769:                 if ($currcat ne '') {
                   14770:                     @currcategories = split('&',$currcat);
                   14771:                 }
1.919     raeburn  14772:                 my $table;
1.663     raeburn  14773:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14774:                     my $parent = $cats[0][$i];
1.919     raeburn  14775:                     next if ($parent eq 'instcode');
                   14776:                     if ($type eq 'Community') {
                   14777:                         next unless ($parent eq 'communities');
                   14778:                     } else {
                   14779:                         next if ($parent eq 'communities');
                   14780:                     }
1.663     raeburn  14781:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14782:                     my $item = &escape($parent).'::0';
                   14783:                     my $checked = '';
                   14784:                     if (@currcategories > 0) {
                   14785:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14786:                             $checked = ' checked="checked"';
1.663     raeburn  14787:                         }
                   14788:                     }
1.919     raeburn  14789:                     my $parent_title = $parent;
                   14790:                     if ($parent eq 'communities') {
                   14791:                         $parent_title = &mt('Communities');
                   14792:                     }
                   14793:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14794:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14795:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14796:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14797:                     my $depth = 1;
                   14798:                     push(@path,$parent);
1.1075.2.117  raeburn  14799:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14800:                     pop(@path);
1.919     raeburn  14801:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14802:                     $itemcount ++;
                   14803:                 }
1.919     raeburn  14804:                 if ($itemcount) {
                   14805:                     $output = &Apache::loncommon::start_data_table().
                   14806:                               $table.
                   14807:                               &Apache::loncommon::end_data_table();
                   14808:                 }
1.663     raeburn  14809:             }
                   14810:         }
                   14811:     }
                   14812:     return $output;
                   14813: }
                   14814: 
                   14815: =pod
                   14816: 
1.1075.2.56  raeburn  14817: =item * &assign_category_rows()
1.663     raeburn  14818: 
                   14819: Create a datatable row for display of nested categories in a domain,
                   14820: with checkboxes to allow a course to be categorized,called recursively.
                   14821: 
                   14822: Inputs:
                   14823: 
                   14824: itemcount - track row number for alternating colors
                   14825: 
                   14826: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14827:       categories and subcategories.
                   14828: 
                   14829: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14830: 
                   14831: parent - parent of current category item
                   14832: 
                   14833: path - Array containing all categories back up through the hierarchy from the
                   14834:        current category to the top level.
                   14835: 
                   14836: currcategories - reference to array of current categories assigned to the course
                   14837: 
1.1075.2.117  raeburn  14838: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14839:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14840: 
1.663     raeburn  14841: Returns: $output (markup to be displayed).
                   14842: 
                   14843: =cut
                   14844: 
                   14845: sub assign_category_rows {
1.1075.2.117  raeburn  14846:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14847:     my ($text,$name,$item,$chgstr);
                   14848:     if (ref($cats) eq 'ARRAY') {
                   14849:         my $maxdepth = scalar(@{$cats});
                   14850:         if (ref($cats->[$depth]) eq 'HASH') {
                   14851:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14852:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14853:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14854:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14855:                 for (my $j=0; $j<$numchildren; $j++) {
                   14856:                     $name = $cats->[$depth]{$parent}[$j];
                   14857:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14858:                     my $deeper = $depth+1;
                   14859:                     my $checked = '';
                   14860:                     if (ref($currcategories) eq 'ARRAY') {
                   14861:                         if (@{$currcategories} > 0) {
                   14862:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14863:                                 $checked = ' checked="checked"';
1.663     raeburn  14864:                             }
                   14865:                         }
                   14866:                     }
1.664     raeburn  14867:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14868:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14869:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14870:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14871:                              '</td><td>';
1.663     raeburn  14872:                     if (ref($path) eq 'ARRAY') {
                   14873:                         push(@{$path},$name);
1.1075.2.117  raeburn  14874:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14875:                         pop(@{$path});
                   14876:                     }
                   14877:                     $text .= '</td></tr>';
                   14878:                 }
                   14879:                 $text .= '</table></td>';
                   14880:             }
                   14881:         }
                   14882:     }
                   14883:     return $text;
                   14884: }
                   14885: 
1.1075.2.69  raeburn  14886: =pod
                   14887: 
                   14888: =back
                   14889: 
                   14890: =cut
                   14891: 
1.655     raeburn  14892: ############################################################
                   14893: ############################################################
                   14894: 
                   14895: 
1.443     albertel 14896: sub commit_customrole {
1.664     raeburn  14897:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14898:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14899:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14900:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14901:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14902:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14903:                  '</b><br />';
                   14904:     return $output;
                   14905: }
                   14906: 
                   14907: sub commit_standardrole {
1.1075.2.31  raeburn  14908:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14909:     my ($output,$logmsg,$linefeed);
                   14910:     if ($context eq 'auto') {
                   14911:         $linefeed = "\n";
                   14912:     } else {
                   14913:         $linefeed = "<br />\n";
                   14914:     }  
1.443     albertel 14915:     if ($three eq 'st') {
1.541     raeburn  14916:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14917:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14918:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14919:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14920:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14921:         } else {
1.541     raeburn  14922:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14923:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14924:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14925:             if ($context eq 'auto') {
                   14926:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14927:             } else {
                   14928:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14929:                &mt('Add to classlist').': <b>ok</b>';
                   14930:             }
                   14931:             $output .= $linefeed;
1.443     albertel 14932:         }
                   14933:     } else {
                   14934:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14935:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14936:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14937:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14938:         if ($context eq 'auto') {
                   14939:             $output .= $result.$linefeed;
                   14940:         } else {
                   14941:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14942:         }
1.443     albertel 14943:     }
                   14944:     return $output;
                   14945: }
                   14946: 
                   14947: sub commit_studentrole {
1.1075.2.31  raeburn  14948:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14949:         $credits) = @_;
1.626     raeburn  14950:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14951:     if ($context eq 'auto') {
                   14952:         $linefeed = "\n";
                   14953:     } else {
                   14954:         $linefeed = '<br />'."\n";
                   14955:     }
1.443     albertel 14956:     if (defined($one) && defined($two)) {
                   14957:         my $cid=$one.'_'.$two;
                   14958:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14959:         my $secchange = 0;
                   14960:         my $expire_role_result;
                   14961:         my $modify_section_result;
1.628     raeburn  14962:         if ($oldsec ne '-1') { 
                   14963:             if ($oldsec ne $sec) {
1.443     albertel 14964:                 $secchange = 1;
1.628     raeburn  14965:                 my $now = time;
1.443     albertel 14966:                 my $uurl='/'.$cid;
                   14967:                 $uurl=~s/\_/\//g;
                   14968:                 if ($oldsec) {
                   14969:                     $uurl.='/'.$oldsec;
                   14970:                 }
1.626     raeburn  14971:                 $oldsecurl = $uurl;
1.628     raeburn  14972:                 $expire_role_result = 
1.652     raeburn  14973:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14974:                 if ($env{'request.course.sec'} ne '') { 
                   14975:                     if ($expire_role_result eq 'refused') {
                   14976:                         my @roles = ('st');
                   14977:                         my @statuses = ('previous');
                   14978:                         my @roledoms = ($one);
                   14979:                         my $withsec = 1;
                   14980:                         my %roleshash = 
                   14981:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14982:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14983:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14984:                             my ($oldstart,$oldend) = 
                   14985:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14986:                             if ($oldend > 0 && $oldend <= $now) {
                   14987:                                 $expire_role_result = 'ok';
                   14988:                             }
                   14989:                         }
                   14990:                     }
                   14991:                 }
1.443     albertel 14992:                 $result = $expire_role_result;
                   14993:             }
                   14994:         }
                   14995:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14996:             $modify_section_result = 
                   14997:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14998:                                                            undef,undef,undef,$sec,
                   14999:                                                            $end,$start,'','',$cid,
                   15000:                                                            '',$context,$credits);
1.443     albertel 15001:             if ($modify_section_result =~ /^ok/) {
                   15002:                 if ($secchange == 1) {
1.628     raeburn  15003:                     if ($sec eq '') {
                   15004:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15005:                     } else {
                   15006:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15007:                     }
1.443     albertel 15008:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15009:                     if ($sec eq '') {
                   15010:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15011:                     } else {
                   15012:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15013:                     }
1.443     albertel 15014:                 } else {
1.628     raeburn  15015:                     if ($sec eq '') {
                   15016:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15017:                     } else {
                   15018:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15019:                     }
1.443     albertel 15020:                 }
                   15021:             } else {
1.628     raeburn  15022:                 if ($secchange) {       
                   15023:                     $$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;
                   15024:                 } else {
                   15025:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15026:                 }
1.443     albertel 15027:             }
                   15028:             $result = $modify_section_result;
                   15029:         } elsif ($secchange == 1) {
1.628     raeburn  15030:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15031:                 $$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  15032:             } else {
                   15033:                 $$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;
                   15034:             }
1.626     raeburn  15035:             if ($expire_role_result eq 'refused') {
                   15036:                 my $newsecurl = '/'.$cid;
                   15037:                 $newsecurl =~ s/\_/\//g;
                   15038:                 if ($sec ne '') {
                   15039:                     $newsecurl.='/'.$sec;
                   15040:                 }
                   15041:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15042:                     if ($sec eq '') {
                   15043:                         $$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;
                   15044:                     } else {
                   15045:                         $$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;
                   15046:                     }
                   15047:                 }
                   15048:             }
1.443     albertel 15049:         }
                   15050:     } else {
1.626     raeburn  15051:         $$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 15052:         $result = "error: incomplete course id\n";
                   15053:     }
                   15054:     return $result;
                   15055: }
                   15056: 
1.1075.2.25  raeburn  15057: sub show_role_extent {
                   15058:     my ($scope,$context,$role) = @_;
                   15059:     $scope =~ s{^/}{};
                   15060:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15061:     push(@courseroles,'co');
                   15062:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15063:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15064:         $scope =~ s{/}{_};
                   15065:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15066:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15067:         my ($audom,$auname) = split(/\//,$scope);
                   15068:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15069:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15070:     } else {
                   15071:         $scope =~ s{/$}{};
                   15072:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15073:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15074:     }
                   15075: }
                   15076: 
1.443     albertel 15077: ############################################################
                   15078: ############################################################
                   15079: 
1.566     albertel 15080: sub check_clone {
1.578     raeburn  15081:     my ($args,$linefeed) = @_;
1.566     albertel 15082:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15083:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15084:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15085:     my $clonemsg;
                   15086:     my $can_clone = 0;
1.944     raeburn  15087:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15088:     if ($lctype ne 'community') {
                   15089:         $lctype = 'course';
                   15090:     }
1.566     albertel 15091:     if ($clonehome eq 'no_host') {
1.944     raeburn  15092:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15093:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15094:         } else {
                   15095:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15096:         }     
1.566     albertel 15097:     } else {
                   15098: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15099:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15100:             if ($clonedesc{'type'} ne 'Community') {
                   15101:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15102:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15103:             }
                   15104:         }
1.1075.2.119  raeburn  15105: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15106:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15107: 	    $can_clone = 1;
                   15108: 	} else {
1.1075.2.95  raeburn  15109: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15110: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15111:             if ($clonehash{'cloners'} eq '') {
                   15112:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15113:                 if ($domdefs{'canclone'}) {
                   15114:                     unless ($domdefs{'canclone'} eq 'none') {
                   15115:                         if ($domdefs{'canclone'} eq 'domain') {
                   15116:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15117:                                 $can_clone = 1;
                   15118:                             }
                   15119:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15120:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15121:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15122:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15123:                                 $can_clone = 1;
                   15124:                             }
                   15125:                         }
                   15126:                     }
1.908     raeburn  15127:                 }
1.1075.2.95  raeburn  15128:             } else {
                   15129: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15130:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15131:                     $can_clone = 1;
1.1075.2.95  raeburn  15132:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15133:                     $can_clone = 1;
1.1075.2.96  raeburn  15134:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15135:                     $can_clone = 1;
1.1075.2.95  raeburn  15136:                 }
                   15137:                 unless ($can_clone) {
1.1075.2.96  raeburn  15138:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15139:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15140:                         my (%gotdomdefaults,%gotcodedefaults);
                   15141:                         foreach my $cloner (@cloners) {
                   15142:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15143:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15144:                                 my (%codedefaults,@code_order);
                   15145:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15146:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15147:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15148:                                     }
                   15149:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15150:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15151:                                     }
                   15152:                                 } else {
                   15153:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15154:                                                                             \%codedefaults,
                   15155:                                                                             \@code_order);
                   15156:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15157:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15158:                                 }
                   15159:                                 if (@code_order > 0) {
                   15160:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15161:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15162:                                                                                 $args->{'crscode'})) {
                   15163:                                         $can_clone = 1;
                   15164:                                         last;
                   15165:                                     }
                   15166:                                 }
                   15167:                             }
                   15168:                         }
                   15169:                     }
1.1075.2.96  raeburn  15170:                 }
                   15171:             }
                   15172:             unless ($can_clone) {
                   15173:                 my $ccrole = 'cc';
                   15174:                 if ($args->{'crstype'} eq 'Community') {
                   15175:                     $ccrole = 'co';
                   15176:                 }
                   15177:                 my %roleshash =
                   15178:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15179:                                                   $args->{'ccdomain'},
                   15180:                                                   'userroles',['active'],[$ccrole],
                   15181:                                                   [$args->{'clonedomain'}]);
                   15182:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15183:                     $can_clone = 1;
                   15184:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15185:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15186:                     $can_clone = 1;
1.1075.2.95  raeburn  15187:                 }
                   15188:             }
                   15189:             unless ($can_clone) {
                   15190:                 if ($args->{'crstype'} eq 'Community') {
                   15191:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   15192:                 } else {
                   15193:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.578     raeburn  15194: 	        }
1.566     albertel 15195: 	    }
1.578     raeburn  15196:         }
1.566     albertel 15197:     }
                   15198:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15199: }
                   15200: 
1.444     albertel 15201: sub construct_course {
1.1075.2.119  raeburn  15202:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15203:         $cnum,$category,$coderef) = @_;
1.444     albertel 15204:     my $outcome;
1.541     raeburn  15205:     my $linefeed =  '<br />'."\n";
                   15206:     if ($context eq 'auto') {
                   15207:         $linefeed = "\n";
                   15208:     }
1.566     albertel 15209: 
                   15210: #
                   15211: # Are we cloning?
                   15212: #
                   15213:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15214:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15215: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15216: 	if ($context ne 'auto') {
1.578     raeburn  15217:             if ($clonemsg ne '') {
                   15218: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15219:             }
1.566     albertel 15220: 	}
                   15221: 	$outcome .= $clonemsg.$linefeed;
                   15222: 
                   15223:         if (!$can_clone) {
                   15224: 	    return (0,$outcome);
                   15225: 	}
                   15226:     }
                   15227: 
1.444     albertel 15228: #
                   15229: # Open course
                   15230: #
                   15231:     my $crstype = lc($args->{'crstype'});
                   15232:     my %cenv=();
                   15233:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15234:                                              $args->{'cdescr'},
                   15235:                                              $args->{'curl'},
                   15236:                                              $args->{'course_home'},
                   15237:                                              $args->{'nonstandard'},
                   15238:                                              $args->{'crscode'},
                   15239:                                              $args->{'ccuname'}.':'.
                   15240:                                              $args->{'ccdomain'},
1.882     raeburn  15241:                                              $args->{'crstype'},
1.885     raeburn  15242:                                              $cnum,$context,$category);
1.444     albertel 15243: 
                   15244:     # Note: The testing routines depend on this being output; see 
                   15245:     # Utils::Course. This needs to at least be output as a comment
                   15246:     # if anyone ever decides to not show this, and Utils::Course::new
                   15247:     # will need to be suitably modified.
1.541     raeburn  15248:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  15249:     if ($$courseid =~ /^error:/) {
                   15250:         return (0,$outcome);
                   15251:     }
                   15252: 
1.444     albertel 15253: #
                   15254: # Check if created correctly
                   15255: #
1.479     albertel 15256:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15257:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15258:     if ($crsuhome eq 'no_host') {
                   15259:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15260:         return (0,$outcome);
                   15261:     }
1.541     raeburn  15262:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15263: 
1.444     albertel 15264: #
1.566     albertel 15265: # Do the cloning
                   15266: #   
                   15267:     if ($can_clone && $cloneid) {
                   15268: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15269: 	if ($context ne 'auto') {
                   15270: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15271: 	}
                   15272: 	$outcome .= $clonemsg.$linefeed;
                   15273: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15274: # Copy all files
1.637     www      15275: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15276: # Restore URL
1.566     albertel 15277: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15278: # Restore title
1.566     albertel 15279: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15280: # Restore creation date, creator and creation context.
                   15281:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15282:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15283:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15284: # Mark as cloned
1.566     albertel 15285: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15286: # Need to clone grading mode
                   15287:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15288:         $cenv{'grading'}=$newenv{'grading'};
                   15289: # Do not clone these environment entries
                   15290:         &Apache::lonnet::del('environment',
                   15291:                   ['default_enrollment_start_date',
                   15292:                    'default_enrollment_end_date',
                   15293:                    'question.email',
                   15294:                    'policy.email',
                   15295:                    'comment.email',
                   15296:                    'pch.users.denied',
1.725     raeburn  15297:                    'plc.users.denied',
                   15298:                    'hidefromcat',
1.1075.2.36  raeburn  15299:                    'checkforpriv',
1.1075.2.59  raeburn  15300:                    'categories',
                   15301:                    'internal.uniquecode'],
1.638     www      15302:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15303:         if ($args->{'textbook'}) {
                   15304:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15305:         }
1.444     albertel 15306:     }
1.566     albertel 15307: 
1.444     albertel 15308: #
                   15309: # Set environment (will override cloned, if existing)
                   15310: #
                   15311:     my @sections = ();
                   15312:     my @xlists = ();
                   15313:     if ($args->{'crstype'}) {
                   15314:         $cenv{'type'}=$args->{'crstype'};
                   15315:     }
                   15316:     if ($args->{'crsid'}) {
                   15317:         $cenv{'courseid'}=$args->{'crsid'};
                   15318:     }
                   15319:     if ($args->{'crscode'}) {
                   15320:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15321:     }
                   15322:     if ($args->{'crsquota'} ne '') {
                   15323:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15324:     } else {
                   15325:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15326:     }
                   15327:     if ($args->{'ccuname'}) {
                   15328:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15329:                                         ':'.$args->{'ccdomain'};
                   15330:     } else {
                   15331:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15332:     }
1.1075.2.31  raeburn  15333:     if ($args->{'defaultcredits'}) {
                   15334:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15335:     }
1.444     albertel 15336:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15337:     if ($args->{'crssections'}) {
                   15338:         $cenv{'internal.sectionnums'} = '';
                   15339:         if ($args->{'crssections'} =~ m/,/) {
                   15340:             @sections = split/,/,$args->{'crssections'};
                   15341:         } else {
                   15342:             $sections[0] = $args->{'crssections'};
                   15343:         }
                   15344:         if (@sections > 0) {
                   15345:             foreach my $item (@sections) {
                   15346:                 my ($sec,$gp) = split/:/,$item;
                   15347:                 my $class = $args->{'crscode'}.$sec;
                   15348:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15349:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15350:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15351:                     push(@badclasses,$class);
1.444     albertel 15352:                 }
                   15353:             }
                   15354:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15355:         }
                   15356:     }
                   15357: # do not hide course coordinator from staff listing, 
                   15358: # even if privileged
                   15359:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15360: # add course coordinator's domain to domains to check for privileged users
                   15361: # if different to course domain
                   15362:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15363:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15364:     }
1.444     albertel 15365: # add crosslistings
                   15366:     if ($args->{'crsxlist'}) {
                   15367:         $cenv{'internal.crosslistings'}='';
                   15368:         if ($args->{'crsxlist'} =~ m/,/) {
                   15369:             @xlists = split/,/,$args->{'crsxlist'};
                   15370:         } else {
                   15371:             $xlists[0] = $args->{'crsxlist'};
                   15372:         }
                   15373:         if (@xlists > 0) {
                   15374:             foreach my $item (@xlists) {
                   15375:                 my ($xl,$gp) = split/:/,$item;
                   15376:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15377:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15378:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15379:                     push(@badclasses,$xl);
1.444     albertel 15380:                 }
                   15381:             }
                   15382:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15383:         }
                   15384:     }
                   15385:     if ($args->{'autoadds'}) {
                   15386:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15387:     }
                   15388:     if ($args->{'autodrops'}) {
                   15389:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15390:     }
                   15391: # check for notification of enrollment changes
                   15392:     my @notified = ();
                   15393:     if ($args->{'notify_owner'}) {
                   15394:         if ($args->{'ccuname'} ne '') {
                   15395:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15396:         }
                   15397:     }
                   15398:     if ($args->{'notify_dc'}) {
                   15399:         if ($uname ne '') { 
1.630     raeburn  15400:             push(@notified,$uname.':'.$udom);
1.444     albertel 15401:         }
                   15402:     }
                   15403:     if (@notified > 0) {
                   15404:         my $notifylist;
                   15405:         if (@notified > 1) {
                   15406:             $notifylist = join(',',@notified);
                   15407:         } else {
                   15408:             $notifylist = $notified[0];
                   15409:         }
                   15410:         $cenv{'internal.notifylist'} = $notifylist;
                   15411:     }
                   15412:     if (@badclasses > 0) {
                   15413:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15414:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15415:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15416:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15417:         );
1.1075.2.119  raeburn  15418:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15419:                            &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  15420:         if ($context eq 'auto') {
                   15421:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15422:         } else {
1.566     albertel 15423:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15424:         }
                   15425:         foreach my $item (@badclasses) {
1.541     raeburn  15426:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15427:                 $outcome .= " - $item\n";
1.541     raeburn  15428:             } else {
1.1075.2.119  raeburn  15429:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15430:             }
1.1075.2.119  raeburn  15431:         }
                   15432:         if ($context eq 'auto') {
                   15433:             $outcome .= $linefeed;
                   15434:         } else {
                   15435:             $outcome .= "</ul><br /><br /></div>\n";
                   15436:         }
1.444     albertel 15437:     }
                   15438:     if ($args->{'no_end_date'}) {
                   15439:         $args->{'endaccess'} = 0;
                   15440:     }
                   15441:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15442:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15443:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15444:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15445:     if ($args->{'showphotos'}) {
                   15446:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15447:     }
                   15448:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15449:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15450:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15451:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15452:             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'); 
                   15453:             if ($context eq 'auto') {
                   15454:                 $outcome .= $krb_msg;
                   15455:             } else {
1.566     albertel 15456:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15457:             }
                   15458:             $outcome .= $linefeed;
1.444     albertel 15459:         }
                   15460:     }
                   15461:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15462:        if ($args->{'setpolicy'}) {
                   15463:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15464:        }
                   15465:        if ($args->{'setcontent'}) {
                   15466:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15467:        }
1.1075.2.110  raeburn  15468:        if ($args->{'setcomment'}) {
                   15469:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15470:        }
1.444     albertel 15471:     }
                   15472:     if ($args->{'reshome'}) {
                   15473: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15474: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15475:     }
                   15476: #
                   15477: # course has keyed access
                   15478: #
                   15479:     if ($args->{'setkeys'}) {
                   15480:        $cenv{'keyaccess'}='yes';
                   15481:     }
                   15482: # if specified, key authority is not course, but user
                   15483: # only active if keyaccess is yes
                   15484:     if ($args->{'keyauth'}) {
1.487     albertel 15485: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15486: 	$user = &LONCAPA::clean_username($user);
                   15487: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15488: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15489: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15490: 	}
                   15491:     }
                   15492: 
1.1075.2.59  raeburn  15493: #
                   15494: #  generate and store uniquecode (available to course requester), if course should have one.
                   15495: #
                   15496:     if ($args->{'uniquecode'}) {
                   15497:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15498:         if ($code) {
                   15499:             $cenv{'internal.uniquecode'} = $code;
                   15500:             my %crsinfo =
                   15501:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15502:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15503:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15504:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15505:             }
                   15506:             if (ref($coderef)) {
                   15507:                 $$coderef = $code;
                   15508:             }
                   15509:         }
                   15510:     }
                   15511: 
1.444     albertel 15512:     if ($args->{'disresdis'}) {
                   15513:         $cenv{'pch.roles.denied'}='st';
                   15514:     }
                   15515:     if ($args->{'disablechat'}) {
                   15516:         $cenv{'plc.roles.denied'}='st';
                   15517:     }
                   15518: 
                   15519:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15520:     # course
                   15521:     $cenv{'course.helper.not.run'} = 1;
                   15522:     #
                   15523:     # Use new Randomseed
                   15524:     #
                   15525:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15526:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15527:     #
                   15528:     # The encryption code and receipt prefix for this course
                   15529:     #
                   15530:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15531:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15532:     #
                   15533:     # By default, use standard grading
                   15534:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15535: 
1.541     raeburn  15536:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15537:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15538: #
                   15539: # Open all assignments
                   15540: #
                   15541:     if ($args->{'openall'}) {
1.1075.2.141.  .4(raebu 15542:20):        my $opendate = time;
                   15543:20):        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15544:20):            $opendate = $args->{'openallfrom'};
                   15545:20):        }
1.444     albertel 15546:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.141.  .4(raebu 15547:20):        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15548:                            $storeunder.'.type' => 'date_start');
1.1075.2.141.  .4(raebu 15549:20):        $outcome .= &mt('All assignments open starting [_1]',
                   15550:20):                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15551:20):                    &Apache::lonnet::cput
                   15552:20):                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15553:    }
                   15554: #
                   15555: # Set first page
                   15556: #
                   15557:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15558: 	    || ($cloneid)) {
1.445     albertel 15559: 	use LONCAPA::map;
1.444     albertel 15560: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15561: 
                   15562: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15563:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15564: 
1.444     albertel 15565:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15566:         my $title; my $url;
                   15567:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15568: 	    $title=&mt('Syllabus');
1.444     albertel 15569:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15570:         } else {
1.963     raeburn  15571:             $title=&mt('Table of Contents');
1.444     albertel 15572:             $url='/adm/navmaps';
                   15573:         }
1.445     albertel 15574: 
                   15575:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15576: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15577: 
                   15578: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15579:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15580:     }
1.566     albertel 15581: 
                   15582:     return (1,$outcome);
1.444     albertel 15583: }
                   15584: 
1.1075.2.59  raeburn  15585: sub make_unique_code {
                   15586:     my ($cdom,$cnum) = @_;
                   15587:     # get lock on uniquecodes db
                   15588:     my $lockhash = {
                   15589:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15590:                                                   ':'.$env{'user.domain'},
                   15591:                    };
                   15592:     my $tries = 0;
                   15593:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15594:     my ($code,$error);
                   15595: 
                   15596:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15597:         $tries ++;
                   15598:         sleep 1;
                   15599:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15600:     }
                   15601:     if ($gotlock eq 'ok') {
                   15602:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15603:         my $gotcode;
                   15604:         my $attempts = 0;
                   15605:         while ((!$gotcode) && ($attempts < 100)) {
                   15606:             $code = &generate_code();
                   15607:             if (!exists($currcodes{$code})) {
                   15608:                 $gotcode = 1;
                   15609:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15610:                     $error = 'nostore';
                   15611:                 }
                   15612:             }
                   15613:             $attempts ++;
                   15614:         }
                   15615:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15616:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15617:     } else {
                   15618:         $error = 'nolock';
                   15619:     }
                   15620:     return ($code,$error);
                   15621: }
                   15622: 
                   15623: sub generate_code {
                   15624:     my $code;
                   15625:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15626:     for (my $i=0; $i<6; $i++) {
                   15627:         my $lettnum = int (rand 2);
                   15628:         my $item = '';
                   15629:         if ($lettnum) {
                   15630:             $item = $letts[int( rand(18) )];
                   15631:         } else {
                   15632:             $item = 1+int( rand(8) );
                   15633:         }
                   15634:         $code .= $item;
                   15635:     }
                   15636:     return $code;
                   15637: }
                   15638: 
1.444     albertel 15639: ############################################################
                   15640: ############################################################
                   15641: 
1.953     droeschl 15642: #SD
                   15643: # only Community and Course, or anything else?
1.378     raeburn  15644: sub course_type {
                   15645:     my ($cid) = @_;
                   15646:     if (!defined($cid)) {
                   15647:         $cid = $env{'request.course.id'};
                   15648:     }
1.404     albertel 15649:     if (defined($env{'course.'.$cid.'.type'})) {
                   15650:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15651:     } else {
                   15652:         return 'Course';
1.377     raeburn  15653:     }
                   15654: }
1.156     albertel 15655: 
1.406     raeburn  15656: sub group_term {
                   15657:     my $crstype = &course_type();
                   15658:     my %names = (
                   15659:                   'Course' => 'group',
1.865     raeburn  15660:                   'Community' => 'group',
1.406     raeburn  15661:                 );
                   15662:     return $names{$crstype};
                   15663: }
                   15664: 
1.902     raeburn  15665: sub course_types {
1.1075.2.59  raeburn  15666:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15667:     my %typename = (
                   15668:                          official   => 'Official course',
                   15669:                          unofficial => 'Unofficial course',
                   15670:                          community  => 'Community',
1.1075.2.59  raeburn  15671:                          textbook   => 'Textbook course',
1.902     raeburn  15672:                    );
                   15673:     return (\@types,\%typename);
                   15674: }
                   15675: 
1.156     albertel 15676: sub icon {
                   15677:     my ($file)=@_;
1.505     albertel 15678:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15679:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15680:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15681:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15682: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15683: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15684: 	            $curfext.".gif") {
                   15685: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15686: 		$curfext.".gif";
                   15687: 	}
                   15688:     }
1.249     albertel 15689:     return &lonhttpdurl($iconname);
1.154     albertel 15690: } 
1.84      albertel 15691: 
1.575     albertel 15692: sub lonhttpdurl {
1.692     www      15693: #
                   15694: # Had been used for "small fry" static images on separate port 8080.
                   15695: # Modify here if lightweight http functionality desired again.
                   15696: # Currently eliminated due to increasing firewall issues.
                   15697: #
1.575     albertel 15698:     my ($url)=@_;
1.692     www      15699:     return $url;
1.215     albertel 15700: }
                   15701: 
1.213     albertel 15702: sub connection_aborted {
                   15703:     my ($r)=@_;
                   15704:     $r->print(" ");$r->rflush();
                   15705:     my $c = $r->connection;
                   15706:     return $c->aborted();
                   15707: }
                   15708: 
1.221     foxr     15709: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15710: #    strings as 'strings'.
                   15711: sub escape_single {
1.221     foxr     15712:     my ($input) = @_;
1.223     albertel 15713:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15714:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15715:     return $input;
                   15716: }
1.223     albertel 15717: 
1.222     foxr     15718: #  Same as escape_single, but escape's "'s  This 
                   15719: #  can be used for  "strings"
                   15720: sub escape_double {
                   15721:     my ($input) = @_;
                   15722:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15723:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15724:     return $input;
                   15725: }
1.223     albertel 15726:  
1.222     foxr     15727: #   Escapes the last element of a full URL.
                   15728: sub escape_url {
                   15729:     my ($url)   = @_;
1.238     raeburn  15730:     my @urlslices = split(/\//, $url,-1);
1.369     www      15731:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15732:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15733: }
1.462     albertel 15734: 
1.820     raeburn  15735: sub compare_arrays {
                   15736:     my ($arrayref1,$arrayref2) = @_;
                   15737:     my (@difference,%count);
                   15738:     @difference = ();
                   15739:     %count = ();
                   15740:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15741:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15742:         foreach my $element (keys(%count)) {
                   15743:             if ($count{$element} == 1) {
                   15744:                 push(@difference,$element);
                   15745:             }
                   15746:         }
                   15747:     }
                   15748:     return @difference;
                   15749: }
                   15750: 
1.817     bisitz   15751: # -------------------------------------------------------- Initialize user login
1.462     albertel 15752: sub init_user_environment {
1.463     albertel 15753:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15754:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15755: 
                   15756:     my $public=($username eq 'public' && $domain eq 'public');
                   15757: 
                   15758: # See if old ID present, if so, remove
                   15759: 
1.1062    raeburn  15760:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15761:     my $now=time;
                   15762: 
                   15763:     if ($public) {
                   15764: 	my $max_public=100;
                   15765: 	my $oldest;
                   15766: 	my $oldest_time=0;
                   15767: 	for(my $next=1;$next<=$max_public;$next++) {
                   15768: 	    if (-e $lonids."/publicuser_$next.id") {
                   15769: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15770: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15771: 		    $oldest_time=$mtime;
                   15772: 		    $oldest=$next;
                   15773: 		}
                   15774: 	    } else {
                   15775: 		$cookie="publicuser_$next";
                   15776: 		last;
                   15777: 	    }
                   15778: 	}
                   15779: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15780:     } else {
1.463     albertel 15781: 	# if this isn't a robot, kill any existing non-robot sessions
                   15782: 	if (!$args->{'robot'}) {
                   15783: 	    opendir(DIR,$lonids);
                   15784: 	    while ($filename=readdir(DIR)) {
                   15785: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15786:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15787:                             &GDBM_READER(),0640)) {
                   15788:                         my $linkedfile;
                   15789:                         if (exists($oldenv{'user.linkedenv'})) {
                   15790:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15791:                         }
                   15792:                         untie(%oldenv);
                   15793:                         if (unlink("$lonids/$filename")) {
                   15794:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15795:                                 if (-l "$lonids/$linkedfile.id") {
                   15796:                                     unlink("$lonids/$linkedfile.id");
                   15797:                                 }
                   15798:                             }
                   15799:                         }
                   15800:                     } else {
                   15801:                         unlink($lonids.'/'.$filename);
                   15802:                     }
1.463     albertel 15803: 		}
1.462     albertel 15804: 	    }
1.463     albertel 15805: 	    closedir(DIR);
1.1075.2.84  raeburn  15806: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15807:             my $namespace = 'nohist_courseeditor';
                   15808:             my $lockingkey = 'paste'."\0".'locked_num';
                   15809:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15810:                                                 $domain,$username);
                   15811:             if (exists($lockhash{$lockingkey})) {
                   15812:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15813:                 unless ($delresult eq 'ok') {
                   15814:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15815:                 }
                   15816:             }
1.462     albertel 15817: 	}
                   15818: # Give them a new cookie
1.463     albertel 15819: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15820: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15821: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15822:     
                   15823: # Initialize roles
                   15824: 
1.1062    raeburn  15825: 	($userroles,$firstaccenv,$timerintenv) = 
                   15826:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15827:     }
                   15828: # ------------------------------------ Check browser type and MathML capability
                   15829: 
1.1075.2.77  raeburn  15830:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15831:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15832: 
                   15833: # ------------------------------------------------------------- Get environment
                   15834: 
                   15835:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15836:     my ($tmp) = keys(%userenv);
                   15837:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15838:     } else {
                   15839: 	undef(%userenv);
                   15840:     }
                   15841:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15842: 	$form->{'interface'}=$userenv{'interface'};
                   15843:     }
                   15844:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15845: 
                   15846: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15847:     foreach my $option ('interface','localpath','localres') {
                   15848:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15849:     }
                   15850: # --------------------------------------------------------- Write first profile
                   15851: 
                   15852:     {
                   15853: 	my %initial_env = 
                   15854: 	    ("user.name"          => $username,
                   15855: 	     "user.domain"        => $domain,
                   15856: 	     "user.home"          => $authhost,
                   15857: 	     "browser.type"       => $clientbrowser,
                   15858: 	     "browser.version"    => $clientversion,
                   15859: 	     "browser.mathml"     => $clientmathml,
                   15860: 	     "browser.unicode"    => $clientunicode,
                   15861: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15862:              "browser.mobile"     => $clientmobile,
                   15863:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15864:              "browser.osversion"  => $clientosversion,
1.462     albertel 15865: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15866: 	     "request.course.fn"  => '',
                   15867: 	     "request.course.uri" => '',
                   15868: 	     "request.course.sec" => '',
                   15869: 	     "request.role"       => 'cm',
                   15870: 	     "request.role.adv"   => $env{'user.adv'},
                   15871: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15872: 
                   15873:         if ($form->{'localpath'}) {
                   15874: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15875: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15876:         }
                   15877: 	
                   15878: 	if ($form->{'interface'}) {
                   15879: 	    $form->{'interface'}=~s/\W//gs;
                   15880: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15881: 	    $env{'browser.interface'}=$form->{'interface'};
                   15882: 	}
                   15883: 
1.1075.2.54  raeburn  15884:         if ($form->{'iptoken'}) {
                   15885:             my $lonhost = $r->dir_config('lonHostID');
                   15886:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15887:             $env{'user.noloadbalance'} = $lonhost;
                   15888:         }
                   15889: 
1.1075.2.120  raeburn  15890:         if ($form->{'noloadbalance'}) {
                   15891:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15892:             my $hosthere = $form->{'noloadbalance'};
                   15893:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15894:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15895:                 $env{'user.noloadbalance'} = $hosthere;
                   15896:             }
                   15897:         }
                   15898: 
1.1016    raeburn  15899:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15900:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15901:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15902: 
1.1075.2.125  raeburn  15903:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15904:                 $userenv{'availabletools.'.$tool} = 
                   15905:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15906:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15907:             }
1.724     raeburn  15908: 
1.1075.2.125  raeburn  15909:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15910:                 $userenv{'canrequest.'.$crstype} =
                   15911:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15912:                                                       'reload','requestcourses',
                   15913:                                                       \%userenv,\%domdef,\%is_adv);
                   15914:             }
1.765     raeburn  15915: 
1.1075.2.125  raeburn  15916:             $userenv{'canrequest.author'} =
                   15917:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15918:                                                   'reload','requestauthor',
                   15919:                                                   \%userenv,\%domdef,\%is_adv);
                   15920:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15921:                                                  $domain,$username);
                   15922:             my $reqstatus = $reqauthor{'author_status'};
                   15923:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15924:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15925:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15926:                                                       $reqauthor{'author'}{'timestamp'};
                   15927:                 }
1.1075.2.14  raeburn  15928:             }
                   15929:         }
                   15930: 
1.462     albertel 15931: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15932: 
1.462     albertel 15933: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15934: 		 &GDBM_WRCREAT(),0640)) {
                   15935: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15936: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15937: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15938:             if (ref($firstaccenv) eq 'HASH') {
                   15939:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15940:             }
                   15941:             if (ref($timerintenv) eq 'HASH') {
                   15942:                 &_add_to_env(\%disk_env,$timerintenv);
                   15943:             }
1.463     albertel 15944: 	    if (ref($args->{'extra_env'})) {
                   15945: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15946: 	    }
1.462     albertel 15947: 	    untie(%disk_env);
                   15948: 	} else {
1.705     tempelho 15949: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15950: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15951: 	    return 'error: '.$!;
                   15952: 	}
                   15953:     }
                   15954:     $env{'request.role'}='cm';
                   15955:     $env{'request.role.adv'}=$env{'user.adv'};
                   15956:     $env{'browser.type'}=$clientbrowser;
                   15957: 
                   15958:     return $cookie;
                   15959: 
                   15960: }
                   15961: 
                   15962: sub _add_to_env {
                   15963:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15964:     if (ref($env_data) eq 'HASH') {
                   15965:         while (my ($key,$value) = each(%$env_data)) {
                   15966: 	    $idf->{$prefix.$key} = $value;
                   15967: 	    $env{$prefix.$key}   = $value;
                   15968:         }
1.462     albertel 15969:     }
                   15970: }
                   15971: 
1.685     tempelho 15972: # --- Get the symbolic name of a problem and the url
                   15973: sub get_symb {
                   15974:     my ($request,$silent) = @_;
1.726     raeburn  15975:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15976:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15977:     if ($symb eq '') {
                   15978:         if (!$silent) {
1.1071    raeburn  15979:             if (ref($request)) { 
                   15980:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15981:             }
1.685     tempelho 15982:             return ();
                   15983:         }
                   15984:     }
                   15985:     &Apache::lonenc::check_decrypt(\$symb);
                   15986:     return ($symb);
                   15987: }
                   15988: 
                   15989: # --------------------------------------------------------------Get annotation
                   15990: 
                   15991: sub get_annotation {
                   15992:     my ($symb,$enc) = @_;
                   15993: 
                   15994:     my $key = $symb;
                   15995:     if (!$enc) {
                   15996:         $key =
                   15997:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15998:     }
                   15999:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16000:     return $annotation{$key};
                   16001: }
                   16002: 
                   16003: sub clean_symb {
1.731     raeburn  16004:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16005: 
                   16006:     &Apache::lonenc::check_decrypt(\$symb);
                   16007:     my $enc = $env{'request.enc'};
1.731     raeburn  16008:     if ($delete_enc) {
1.730     raeburn  16009:         delete($env{'request.enc'});
                   16010:     }
1.685     tempelho 16011: 
                   16012:     return ($symb,$enc);
                   16013: }
1.462     albertel 16014: 
1.1075.2.69  raeburn  16015: ############################################################
                   16016: ############################################################
                   16017: 
                   16018: =pod
                   16019: 
                   16020: =head1 Routines for building display used to search for courses
                   16021: 
                   16022: 
                   16023: =over 4
                   16024: 
                   16025: =item * &build_filters()
                   16026: 
                   16027: Create markup for a table used to set filters to use when selecting
                   16028: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16029: and quotacheck.pl
                   16030: 
                   16031: 
                   16032: Inputs:
                   16033: 
                   16034: filterlist - anonymous array of fields to include as potential filters
                   16035: 
                   16036: crstype - course type
                   16037: 
                   16038: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16039:               to pop-open a course selector (will contain "extra element").
                   16040: 
                   16041: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16042: 
                   16043: filter - anonymous hash of criteria and their values
                   16044: 
                   16045: action - form action
                   16046: 
                   16047: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16048: 
                   16049: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16050: 
                   16051: cloneruname - username of owner of new course who wants to clone
                   16052: 
                   16053: clonerudom - domain of owner of new course who wants to clone
                   16054: 
                   16055: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16056: 
                   16057: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16058: 
                   16059: codedom - domain
                   16060: 
                   16061: formname - value of form element named "form".
                   16062: 
                   16063: fixeddom - domain, if fixed.
                   16064: 
                   16065: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16066: 
                   16067: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16068: 
                   16069: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16070: 
                   16071: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16072: 
                   16073: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16074: 
                   16075: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16076: 
                   16077: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16078: 
                   16079: 
                   16080: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16081: 
                   16082: 
                   16083: Side Effects: None
                   16084: 
                   16085: =cut
                   16086: 
                   16087: # ---------------------------------------------- search for courses based on last activity etc.
                   16088: 
                   16089: sub build_filters {
                   16090:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16091:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16092:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16093:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16094:         $clonetext,$clonewarning) = @_;
                   16095:     my ($list,$jscript);
                   16096:     my $onchange = 'javascript:updateFilters(this)';
                   16097:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16098:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16099:         $typeselectform,$instcodetitle);
                   16100:     if ($formname eq '') {
                   16101:         $formname = $caller;
                   16102:     }
                   16103:     foreach my $item (@{$filterlist}) {
                   16104:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16105:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16106:             if ($item eq 'domainfilter') {
                   16107:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16108:             } elsif ($item eq 'coursefilter') {
                   16109:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16110:             } elsif ($item eq 'ownerfilter') {
                   16111:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16112:             } elsif ($item eq 'ownerdomfilter') {
                   16113:                 $filter->{'ownerdomfilter'} =
                   16114:                     &LONCAPA::clean_domain($filter->{$item});
                   16115:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16116:                                                        'ownerdomfilter',1);
                   16117:             } elsif ($item eq 'personfilter') {
                   16118:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16119:             } elsif ($item eq 'persondomfilter') {
                   16120:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16121:                                                         'persondomfilter',1);
                   16122:             } else {
                   16123:                 $filter->{$item} =~ s/\W//g;
                   16124:             }
                   16125:             if (!$filter->{$item}) {
                   16126:                 $filter->{$item} = '';
                   16127:             }
                   16128:         }
                   16129:         if ($item eq 'domainfilter') {
                   16130:             my $allow_blank = 1;
                   16131:             if ($formname eq 'portform') {
                   16132:                 $allow_blank=0;
                   16133:             } elsif ($formname eq 'studentform') {
                   16134:                 $allow_blank=0;
                   16135:             }
                   16136:             if ($fixeddom) {
                   16137:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16138:                                     ' value="'.$codedom.'" />'.
                   16139:                                     &Apache::lonnet::domain($codedom,'description');
                   16140:             } else {
                   16141:                 $domainselectform = &select_dom_form($filter->{$item},
                   16142:                                                      'domainfilter',
                   16143:                                                       $allow_blank,'',$onchange);
                   16144:             }
                   16145:         } else {
                   16146:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16147:         }
                   16148:     }
                   16149: 
                   16150:     # last course activity filter and selection
                   16151:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16152: 
                   16153:     # course created filter and selection
                   16154:     if (exists($filter->{'createdfilter'})) {
                   16155:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16156:     }
                   16157: 
                   16158:     my %lt = &Apache::lonlocal::texthash(
                   16159:                 'cac' => "$crstype Activity",
                   16160:                 'ccr' => "$crstype Created",
                   16161:                 'cde' => "$crstype Title",
                   16162:                 'cdo' => "$crstype Domain",
                   16163:                 'ins' => 'Institutional Code',
                   16164:                 'inc' => 'Institutional Categorization',
                   16165:                 'cow' => "$crstype Owner/Co-owner",
                   16166:                 'cop' => "$crstype Personnel Includes",
                   16167:                 'cog' => 'Type',
                   16168:              );
                   16169: 
                   16170:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16171:         my $typeval = 'Course';
                   16172:         if ($crstype eq 'Community') {
                   16173:             $typeval = 'Community';
                   16174:         }
                   16175:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16176:     } else {
                   16177:         $typeselectform =  '<select name="type" size="1"';
                   16178:         if ($onchange) {
                   16179:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16180:         }
                   16181:         $typeselectform .= '>'."\n";
                   16182:         foreach my $posstype ('Course','Community') {
                   16183:             $typeselectform.='<option value="'.$posstype.'"'.
                   16184:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16185:         }
                   16186:         $typeselectform.="</select>";
                   16187:     }
                   16188: 
                   16189:     my ($cloneableonlyform,$cloneabletitle);
                   16190:     if (exists($filter->{'cloneableonly'})) {
                   16191:         my $cloneableon = '';
                   16192:         my $cloneableoff = ' checked="checked"';
                   16193:         if ($filter->{'cloneableonly'}) {
                   16194:             $cloneableon = $cloneableoff;
                   16195:             $cloneableoff = '';
                   16196:         }
                   16197:         $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>';
                   16198:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16199:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16200:         } else {
                   16201:             $cloneabletitle = &mt('Cloneable by you');
                   16202:         }
                   16203:     }
                   16204:     my $officialjs;
                   16205:     if ($crstype eq 'Course') {
                   16206:         if (exists($filter->{'instcodefilter'})) {
                   16207: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16208: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16209:             if ($codedom) {
                   16210:                 $officialjs = 1;
                   16211:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16212:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16213:                                                                   $officialjs,$codetitlesref);
                   16214:                 if ($jscript) {
                   16215:                     $jscript = '<script type="text/javascript">'."\n".
                   16216:                                '// <![CDATA['."\n".
                   16217:                                $jscript."\n".
                   16218:                                '// ]]>'."\n".
                   16219:                                '</script>'."\n";
                   16220:                 }
                   16221:             }
                   16222:             if ($instcodeform eq '') {
                   16223:                 $instcodeform =
                   16224:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16225:                     $list->{'instcodefilter'}.'" />';
                   16226:                 $instcodetitle = $lt{'ins'};
                   16227:             } else {
                   16228:                 $instcodetitle = $lt{'inc'};
                   16229:             }
                   16230:             if ($fixeddom) {
                   16231:                 $instcodetitle .= '<br />('.$codedom.')';
                   16232:             }
                   16233:         }
                   16234:     }
                   16235:     my $output = qq|
                   16236: <form method="post" name="filterpicker" action="$action">
                   16237: <input type="hidden" name="form" value="$formname" />
                   16238: |;
                   16239:     if ($formname eq 'modifycourse') {
                   16240:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16241:                    '<input type="hidden" name="prevphase" value="'.
                   16242:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16243:     } elsif ($formname eq 'quotacheck') {
                   16244:         $output .= qq|
                   16245: <input type="hidden" name="sortby" value="" />
                   16246: <input type="hidden" name="sortorder" value="" />
                   16247: |;
                   16248:     } else {
1.1075.2.69  raeburn  16249:         my $name_input;
                   16250:         if ($cnameelement ne '') {
                   16251:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16252:                           $cnameelement.'" />';
                   16253:         }
                   16254:         $output .= qq|
                   16255: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16256: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16257: $name_input
                   16258: $roleelement
                   16259: $multelement
                   16260: $typeelement
                   16261: |;
                   16262:         if ($formname eq 'portform') {
                   16263:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16264:         }
                   16265:     }
                   16266:     if ($fixeddom) {
                   16267:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16268:     }
                   16269:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16270:     if ($sincefilterform) {
                   16271:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16272:                   .$sincefilterform
                   16273:                   .&Apache::lonhtmlcommon::row_closure();
                   16274:     }
                   16275:     if ($createdfilterform) {
                   16276:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16277:                   .$createdfilterform
                   16278:                   .&Apache::lonhtmlcommon::row_closure();
                   16279:     }
                   16280:     if ($domainselectform) {
                   16281:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16282:                   .$domainselectform
                   16283:                   .&Apache::lonhtmlcommon::row_closure();
                   16284:     }
                   16285:     if ($typeselectform) {
                   16286:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16287:             $output .= $typeselectform;
                   16288:         } else {
                   16289:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16290:                       .$typeselectform
                   16291:                       .&Apache::lonhtmlcommon::row_closure();
                   16292:         }
                   16293:     }
                   16294:     if ($instcodeform) {
                   16295:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16296:                   .$instcodeform
                   16297:                   .&Apache::lonhtmlcommon::row_closure();
                   16298:     }
                   16299:     if (exists($filter->{'ownerfilter'})) {
                   16300:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16301:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16302:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16303:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16304:                    $ownerdomselectform.'</td></tr></table>'.
                   16305:                    &Apache::lonhtmlcommon::row_closure();
                   16306:     }
                   16307:     if (exists($filter->{'personfilter'})) {
                   16308:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16309:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16310:                    '<input type="text" name="personfilter" size="20" value="'.
                   16311:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16312:                    $persondomselectform.'</td></tr></table>'.
                   16313:                    &Apache::lonhtmlcommon::row_closure();
                   16314:     }
                   16315:     if (exists($filter->{'coursefilter'})) {
                   16316:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16317:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16318:                   .$list->{'coursefilter'}.'" />'
                   16319:                   .&Apache::lonhtmlcommon::row_closure();
                   16320:     }
                   16321:     if ($cloneableonlyform) {
                   16322:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16323:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16324:     }
                   16325:     if (exists($filter->{'descriptfilter'})) {
                   16326:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16327:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16328:                   .$list->{'descriptfilter'}.'" />'
                   16329:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16330:     }
                   16331:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16332:                '<input type="hidden" name="updater" value="" />'."\n".
                   16333:                '<input type="submit" name="gosearch" value="'.
                   16334:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16335:     return $jscript.$clonewarning.$output;
                   16336: }
                   16337: 
                   16338: =pod
                   16339: 
                   16340: =item * &timebased_select_form()
                   16341: 
                   16342: Create markup for a dropdown list used to select a time-based
                   16343: filter e.g., Course Activity, Course Created, when searching for courses
                   16344: or communities
                   16345: 
                   16346: Inputs:
                   16347: 
                   16348: item - name of form element (sincefilter or createdfilter)
                   16349: 
                   16350: filter - anonymous hash of criteria and their values
                   16351: 
                   16352: Returns: HTML for a select box contained a blank, then six time selections,
                   16353:          with value set in incoming form variables currently selected.
                   16354: 
                   16355: Side Effects: None
                   16356: 
                   16357: =cut
                   16358: 
                   16359: sub timebased_select_form {
                   16360:     my ($item,$filter) = @_;
                   16361:     if (ref($filter) eq 'HASH') {
                   16362:         $filter->{$item} =~ s/[^\d-]//g;
                   16363:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16364:         return &select_form(
                   16365:                             $filter->{$item},
                   16366:                             $item,
                   16367:                             {      '-1' => '',
                   16368:                                 '86400' => &mt('today'),
                   16369:                                '604800' => &mt('last week'),
                   16370:                               '2592000' => &mt('last month'),
                   16371:                               '7776000' => &mt('last three months'),
                   16372:                              '15552000' => &mt('last six months'),
                   16373:                              '31104000' => &mt('last year'),
                   16374:                     'select_form_order' =>
                   16375:                            ['-1','86400','604800','2592000','7776000',
                   16376:                             '15552000','31104000']});
                   16377:     }
                   16378: }
                   16379: 
                   16380: =pod
                   16381: 
                   16382: =item * &js_changer()
                   16383: 
                   16384: Create script tag containing Javascript used to submit course search form
                   16385: when course type or domain is changed, and also to hide 'Searching ...' on
                   16386: page load completion for page showing search result.
                   16387: 
                   16388: Inputs: None
                   16389: 
                   16390: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16391: 
                   16392: Side Effects: None
                   16393: 
                   16394: =cut
                   16395: 
                   16396: sub js_changer {
                   16397:     return <<ENDJS;
                   16398: <script type="text/javascript">
                   16399: // <![CDATA[
                   16400: function updateFilters(caller) {
                   16401:     if (typeof(caller) != "undefined") {
                   16402:         document.filterpicker.updater.value = caller.name;
                   16403:     }
                   16404:     document.filterpicker.submit();
                   16405: }
                   16406: 
                   16407: function hideSearching() {
                   16408:     if (document.getElementById('searching')) {
                   16409:         document.getElementById('searching').style.display = 'none';
                   16410:     }
                   16411:     return;
                   16412: }
                   16413: 
                   16414: // ]]>
                   16415: </script>
                   16416: 
                   16417: ENDJS
                   16418: }
                   16419: 
                   16420: =pod
                   16421: 
                   16422: =item * &search_courses()
                   16423: 
                   16424: Process selected filters form course search form and pass to lonnet::courseiddump
                   16425: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16426: 
                   16427: Inputs:
                   16428: 
                   16429: dom - domain being searched
                   16430: 
                   16431: type - course type ('Course' or 'Community' or '.' if any).
                   16432: 
                   16433: filter - anonymous hash of criteria and their values
                   16434: 
                   16435: numtitles - for institutional codes - number of categories
                   16436: 
                   16437: cloneruname - optional username of new course owner
                   16438: 
                   16439: clonerudom - optional domain of new course owner
                   16440: 
1.1075.2.95  raeburn  16441: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16442:             (used when DC is using course creation form)
                   16443: 
                   16444: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16445: 
1.1075.2.95  raeburn  16446: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16447:            (and so can clone automatically)
                   16448: 
                   16449: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16450: 
                   16451: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16452:               courses to clone
1.1075.2.69  raeburn  16453: 
                   16454: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16455: 
                   16456: 
                   16457: Side Effects: None
                   16458: 
                   16459: =cut
                   16460: 
                   16461: 
                   16462: sub search_courses {
1.1075.2.95  raeburn  16463:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16464:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16465:     my (%courses,%showcourses,$cloner);
                   16466:     if (($filter->{'ownerfilter'} ne '') ||
                   16467:         ($filter->{'ownerdomfilter'} ne '')) {
                   16468:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16469:                                        $filter->{'ownerdomfilter'};
                   16470:     }
                   16471:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16472:         if (!$filter->{$item}) {
                   16473:             $filter->{$item}='.';
                   16474:         }
                   16475:     }
                   16476:     my $now = time;
                   16477:     my $timefilter =
                   16478:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16479:     my ($createdbefore,$createdafter);
                   16480:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16481:         $createdbefore = $now;
                   16482:         $createdafter = $now-$filter->{'createdfilter'};
                   16483:     }
                   16484:     my ($instcodefilter,$regexpok);
                   16485:     if ($numtitles) {
                   16486:         if ($env{'form.official'} eq 'on') {
                   16487:             $instcodefilter =
                   16488:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16489:             $regexpok = 1;
                   16490:         } elsif ($env{'form.official'} eq 'off') {
                   16491:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16492:             unless ($instcodefilter eq '') {
                   16493:                 $regexpok = -1;
                   16494:             }
                   16495:         }
                   16496:     } else {
                   16497:         $instcodefilter = $filter->{'instcodefilter'};
                   16498:     }
                   16499:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16500:     if ($type eq '') { $type = '.'; }
                   16501: 
                   16502:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16503:         $cloner = $cloneruname.':'.$clonerudom;
                   16504:     }
                   16505:     %courses = &Apache::lonnet::courseiddump($dom,
                   16506:                                              $filter->{'descriptfilter'},
                   16507:                                              $timefilter,
                   16508:                                              $instcodefilter,
                   16509:                                              $filter->{'combownerfilter'},
                   16510:                                              $filter->{'coursefilter'},
                   16511:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16512:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16513:                                              $filter->{'cloneableonly'},
                   16514:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16515:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16516:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16517:         my $ccrole;
                   16518:         if ($type eq 'Community') {
                   16519:             $ccrole = 'co';
                   16520:         } else {
                   16521:             $ccrole = 'cc';
                   16522:         }
                   16523:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16524:                                                      $filter->{'persondomfilter'},
                   16525:                                                      'userroles',undef,
                   16526:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16527:                                                      $dom);
                   16528:         foreach my $role (keys(%rolehash)) {
                   16529:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16530:             my $cid = $cdom.'_'.$cnum;
                   16531:             if (exists($courses{$cid})) {
                   16532:                 if (ref($courses{$cid}) eq 'HASH') {
                   16533:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16534:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16535:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16536:                         }
                   16537:                     } else {
                   16538:                         $courses{$cid}{roles} = [$courserole];
                   16539:                     }
                   16540:                     $showcourses{$cid} = $courses{$cid};
                   16541:                 }
                   16542:             }
                   16543:         }
                   16544:         %courses = %showcourses;
                   16545:     }
                   16546:     return %courses;
                   16547: }
                   16548: 
                   16549: =pod
                   16550: 
                   16551: =back
                   16552: 
1.1075.2.88  raeburn  16553: =head1 Routines for version requirements for current course.
                   16554: 
                   16555: =over 4
                   16556: 
                   16557: =item * &check_release_required()
                   16558: 
                   16559: Compares required LON-CAPA version with version on server, and
                   16560: if required version is newer looks for a server with the required version.
                   16561: 
                   16562: Looks first at servers in user's owen domain; if none suitable, looks at
                   16563: servers in course's domain are permitted to host sessions for user's domain.
                   16564: 
                   16565: Inputs:
                   16566: 
                   16567: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16568: 
                   16569: $courseid - Course ID of current course
                   16570: 
                   16571: $rolecode - User's current role in course (for switchserver query string).
                   16572: 
                   16573: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16574: 
                   16575: 
                   16576: Returns:
                   16577: 
                   16578: $switchserver - query string tp append to /adm/switchserver call (if
                   16579:                 current server's LON-CAPA version is too old.
                   16580: 
                   16581: $warning - Message is displayed if no suitable server could be found.
                   16582: 
                   16583: =cut
                   16584: 
                   16585: sub check_release_required {
                   16586:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16587:     my ($switchserver,$warning);
                   16588:     if ($required ne '') {
                   16589:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16590:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16591:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16592:             my $otherserver;
                   16593:             if (($major eq '' && $minor eq '') ||
                   16594:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16595:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16596:                 my $switchlcrev =
                   16597:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16598:                                                            $userdomserver);
                   16599:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16600:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16601:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16602:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16603:                     if ($cdom ne $env{'user.domain'}) {
                   16604:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16605:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16606:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16607:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16608:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16609:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16610:                         my $canhost =
                   16611:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16612:                                                               $coursedomserver,
                   16613:                                                               $remoterev,
                   16614:                                                               $udomdefaults{'remotesessions'},
                   16615:                                                               $defdomdefaults{'hostedsessions'});
                   16616: 
                   16617:                         if ($canhost) {
                   16618:                             $otherserver = $coursedomserver;
                   16619:                         } else {
                   16620:                             $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.");
                   16621:                         }
                   16622:                     } else {
                   16623:                         $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).");
                   16624:                     }
                   16625:                 } else {
                   16626:                     $otherserver = $userdomserver;
                   16627:                 }
                   16628:             }
                   16629:             if ($otherserver ne '') {
                   16630:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16631:             }
                   16632:         }
                   16633:     }
                   16634:     return ($switchserver,$warning);
                   16635: }
                   16636: 
                   16637: =pod
                   16638: 
                   16639: =item * &check_release_result()
                   16640: 
                   16641: Inputs:
                   16642: 
                   16643: $switchwarning - Warning message if no suitable server found to host session.
                   16644: 
                   16645: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16646:                 and current role.
                   16647: 
                   16648: Returns: HTML to display with information about requirement to switch server.
                   16649:          Either displaying warning with link to Roles/Courses screen or
                   16650:          display link to switchserver.
                   16651: 
1.1075.2.69  raeburn  16652: =cut
                   16653: 
1.1075.2.88  raeburn  16654: sub check_release_result {
                   16655:     my ($switchwarning,$switchserver) = @_;
                   16656:     my $output = &start_page('Selected course unavailable on this server').
                   16657:                  '<p class="LC_warning">';
                   16658:     if ($switchwarning) {
                   16659:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16660:         if (&show_course()) {
                   16661:             $output .= &mt('Display courses');
                   16662:         } else {
                   16663:             $output .= &mt('Display roles');
                   16664:         }
                   16665:         $output .= '</a>';
                   16666:     } elsif ($switchserver) {
                   16667:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16668:                    '<br />'.
                   16669:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16670:                    &mt('Switch Server').
                   16671:                    '</a>';
                   16672:     }
                   16673:     $output .= '</p>'.&end_page();
                   16674:     return $output;
                   16675: }
                   16676: 
                   16677: =pod
                   16678: 
                   16679: =item * &needs_coursereinit()
                   16680: 
                   16681: Determine if course contents stored for user's session needs to be
                   16682: refreshed, because content has changed since "Big Hash" last tied.
                   16683: 
                   16684: Check for change is made if time last checked is more than 10 minutes ago
                   16685: (by default).
                   16686: 
                   16687: Inputs:
                   16688: 
                   16689: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16690: 
                   16691: $interval (optional) - Time which may elapse (in s) between last check for content
                   16692:                        change in current course. (default: 600 s).
                   16693: 
                   16694: Returns: an array; first element is:
                   16695: 
                   16696: =over 4
                   16697: 
                   16698: 'switch' - if content updates mean user's session
                   16699:            needs to be switched to a server running a newer LON-CAPA version
                   16700: 
                   16701: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16702:            on current server hosting user's session
                   16703: 
                   16704: ''       - if no action required.
                   16705: 
                   16706: =back
                   16707: 
                   16708: If first item element is 'switch':
                   16709: 
                   16710: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16711: 
                   16712: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16713:                               and current role.
                   16714: 
                   16715: otherwise: no other elements returned.
                   16716: 
                   16717: =back
                   16718: 
                   16719: =cut
                   16720: 
                   16721: sub needs_coursereinit {
                   16722:     my ($loncaparev,$interval) = @_;
                   16723:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16724:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16725:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16726:     my $now = time;
                   16727:     if ($interval eq '') {
                   16728:         $interval = 600;
                   16729:     }
                   16730:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16731:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16732:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16733:         if ($lastchange > $env{'request.course.tied'}) {
                   16734:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16735:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16736:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16737:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16738:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16739:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16740:                     my ($switchserver,$switchwarning) =
                   16741:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16742:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16743:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16744:                         return ('switch',$switchwarning,$switchserver);
                   16745:                     }
                   16746:                 }
                   16747:             }
                   16748:             return ('update');
                   16749:         }
                   16750:     }
                   16751:     return ();
                   16752: }
1.1075.2.69  raeburn  16753: 
1.1075.2.11  raeburn  16754: sub update_content_constraints {
                   16755:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16756:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16757:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16758:     my %checkresponsetypes;
                   16759:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16760:         my ($item,$name,$value) = split(/:/,$key);
                   16761:         if ($item eq 'resourcetag') {
                   16762:             if ($name eq 'responsetype') {
                   16763:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16764:             }
                   16765:         }
                   16766:     }
                   16767:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16768:     if (defined($navmap)) {
                   16769:         my %allresponses;
                   16770:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16771:             my %responses = $res->responseTypes();
                   16772:             foreach my $key (keys(%responses)) {
                   16773:                 next unless(exists($checkresponsetypes{$key}));
                   16774:                 $allresponses{$key} += $responses{$key};
                   16775:             }
                   16776:         }
                   16777:         foreach my $key (keys(%allresponses)) {
                   16778:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16779:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16780:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16781:             }
                   16782:         }
                   16783:         undef($navmap);
                   16784:     }
                   16785:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16786:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16787:     }
                   16788:     return;
                   16789: }
                   16790: 
1.1075.2.27  raeburn  16791: sub allmaps_incourse {
                   16792:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16793:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16794:         $cid = $env{'request.course.id'};
                   16795:         $cdom = $env{'course.'.$cid.'.domain'};
                   16796:         $cnum = $env{'course.'.$cid.'.num'};
                   16797:         $chome = $env{'course.'.$cid.'.home'};
                   16798:     }
                   16799:     my %allmaps = ();
                   16800:     my $lastchange =
                   16801:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16802:     if ($lastchange > $env{'request.course.tied'}) {
                   16803:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16804:         unless ($ferr) {
                   16805:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16806:         }
                   16807:     }
                   16808:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16809:     if (defined($navmap)) {
                   16810:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16811:             $allmaps{$res->src()} = 1;
                   16812:         }
                   16813:     }
                   16814:     return \%allmaps;
                   16815: }
                   16816: 
1.1075.2.11  raeburn  16817: sub parse_supplemental_title {
                   16818:     my ($title) = @_;
                   16819: 
                   16820:     my ($foldertitle,$renametitle);
                   16821:     if ($title =~ /&amp;&amp;&amp;/) {
                   16822:         $title = &HTML::Entites::decode($title);
                   16823:     }
                   16824:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16825:         $renametitle=$4;
                   16826:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16827:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16828:         my $name =  &plainname($uname,$udom);
                   16829:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16830:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16831:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16832:             $name.': <br />'.$foldertitle;
                   16833:     }
                   16834:     if (wantarray) {
                   16835:         return ($title,$foldertitle,$renametitle);
                   16836:     }
                   16837:     return $title;
                   16838: }
                   16839: 
1.1075.2.43  raeburn  16840: sub recurse_supplemental {
                   16841:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16842:     if ($suppmap) {
                   16843:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16844:         if ($fatal) {
                   16845:             $errors ++;
                   16846:         } else {
                   16847:             if ($#LONCAPA::map::resources > 0) {
                   16848:                 foreach my $res (@LONCAPA::map::resources) {
                   16849:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16850:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16851:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16852:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16853:                         } else {
                   16854:                             $numfiles ++;
                   16855:                         }
                   16856:                     }
                   16857:                 }
                   16858:             }
                   16859:         }
                   16860:     }
                   16861:     return ($numfiles,$errors);
                   16862: }
                   16863: 
1.1075.2.18  raeburn  16864: sub symb_to_docspath {
1.1075.2.119  raeburn  16865:     my ($symb,$navmapref) = @_;
                   16866:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16867:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16868:     if ($resurl=~/\.(sequence|page)$/) {
                   16869:         $mapurl=$resurl;
                   16870:     } elsif ($resurl eq 'adm/navmaps') {
                   16871:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16872:     }
                   16873:     my $mapresobj;
1.1075.2.119  raeburn  16874:     unless (ref($$navmapref)) {
                   16875:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16876:     }
                   16877:     if (ref($$navmapref)) {
                   16878:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16879:     }
                   16880:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16881:     my $type=$2;
                   16882:     my $path;
                   16883:     if (ref($mapresobj)) {
                   16884:         my $pcslist = $mapresobj->map_hierarchy();
                   16885:         if ($pcslist ne '') {
                   16886:             foreach my $pc (split(/,/,$pcslist)) {
                   16887:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16888:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16889:                 if (ref($res)) {
                   16890:                     my $thisurl = $res->src();
                   16891:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16892:                     my $thistitle = $res->title();
                   16893:                     $path .= '&'.
                   16894:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16895:                              &escape($thistitle).
1.1075.2.18  raeburn  16896:                              ':'.$res->randompick().
                   16897:                              ':'.$res->randomout().
                   16898:                              ':'.$res->encrypted().
                   16899:                              ':'.$res->randomorder().
                   16900:                              ':'.$res->is_page();
                   16901:                 }
                   16902:             }
                   16903:         }
                   16904:         $path =~ s/^\&//;
                   16905:         my $maptitle = $mapresobj->title();
                   16906:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16907:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16908:         }
                   16909:         $path .= (($path ne '')? '&' : '').
                   16910:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16911:                  &escape($maptitle).
1.1075.2.18  raeburn  16912:                  ':'.$mapresobj->randompick().
                   16913:                  ':'.$mapresobj->randomout().
                   16914:                  ':'.$mapresobj->encrypted().
                   16915:                  ':'.$mapresobj->randomorder().
                   16916:                  ':'.$mapresobj->is_page();
                   16917:     } else {
                   16918:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16919:         my $ispage = (($type eq 'page')? 1 : '');
                   16920:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16921:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16922:         }
                   16923:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16924:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16925:     }
                   16926:     unless ($mapurl eq 'default') {
                   16927:         $path = 'default&'.
1.1075.2.46  raeburn  16928:                 &escape('Main Content').
1.1075.2.18  raeburn  16929:                 ':::::&'.$path;
                   16930:     }
                   16931:     return $path;
                   16932: }
                   16933: 
1.1075.2.14  raeburn  16934: sub captcha_display {
1.1075.2.137  raeburn  16935:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16936:     my ($output,$error);
1.1075.2.107  raeburn  16937:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  16938:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16939:     if ($captcha eq 'original') {
                   16940:         $output = &create_captcha();
                   16941:         unless ($output) {
                   16942:             $error = 'captcha';
                   16943:         }
                   16944:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16945:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16946:         unless ($output) {
                   16947:             $error = 'recaptcha';
                   16948:         }
                   16949:     }
1.1075.2.107  raeburn  16950:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16951: }
                   16952: 
                   16953: sub captcha_response {
1.1075.2.137  raeburn  16954:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16955:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  16956:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16957:     if ($captcha eq 'original') {
                   16958:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16959:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16960:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16961:     } else {
                   16962:         $captcha_chk = 1;
                   16963:     }
                   16964:     return ($captcha_chk,$captcha_error);
                   16965: }
                   16966: 
                   16967: sub get_captcha_config {
1.1075.2.137  raeburn  16968:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  16969:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16970:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16971:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16972:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16973:     if ($context eq 'usercreation') {
                   16974:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16975:         if (ref($domconfig{$context}) eq 'HASH') {
                   16976:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16977:             if (ref($hashtocheck) eq 'HASH') {
                   16978:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16979:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16980:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16981:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16982:                     }
                   16983:                     if ($privkey && $pubkey) {
                   16984:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16985:                         $version = $hashtocheck->{'recaptchaversion'};
                   16986:                         if ($version ne '2') {
                   16987:                             $version = 1;
                   16988:                         }
1.1075.2.14  raeburn  16989:                     } else {
                   16990:                         $captcha = 'original';
                   16991:                     }
                   16992:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16993:                     $captcha = 'original';
                   16994:                 }
                   16995:             }
                   16996:         } else {
                   16997:             $captcha = 'captcha';
                   16998:         }
                   16999:     } elsif ($context eq 'login') {
                   17000:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17001:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17002:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17003:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17004:             if ($privkey && $pubkey) {
                   17005:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17006:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17007:                 if ($version ne '2') {
                   17008:                     $version = 1;
                   17009:                 }
1.1075.2.14  raeburn  17010:             } else {
                   17011:                 $captcha = 'original';
                   17012:             }
                   17013:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17014:             $captcha = 'original';
                   17015:         }
1.1075.2.137  raeburn  17016:     } elsif ($context eq 'passwords') {
                   17017:         if ($dom_in_effect) {
                   17018:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17019:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17020:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17021:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17022:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17023:                 }
                   17024:                 if ($privkey && $pubkey) {
                   17025:                     $captcha = 'recaptcha';
                   17026:                     $version = $passwdconf{'recaptchaversion'};
                   17027:                     if ($version ne '2') {
                   17028:                         $version = 1;
                   17029:                     }
                   17030:                 } else {
                   17031:                     $captcha = 'original';
                   17032:                 }
                   17033:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17034:                 $captcha = 'original';
                   17035:             }
                   17036:         }
1.1075.2.14  raeburn  17037:     }
1.1075.2.107  raeburn  17038:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17039: }
                   17040: 
                   17041: sub create_captcha {
                   17042:     my %captcha_params = &captcha_settings();
                   17043:     my ($output,$maxtries,$tries) = ('',10,0);
                   17044:     while ($tries < $maxtries) {
                   17045:         $tries ++;
                   17046:         my $captcha = Authen::Captcha->new (
                   17047:                                            output_folder => $captcha_params{'output_dir'},
                   17048:                                            data_folder   => $captcha_params{'db_dir'},
                   17049:                                           );
                   17050:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17051: 
                   17052:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17053:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17054:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17055:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17056:                       '<br />'.
                   17057:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17058:             last;
                   17059:         }
                   17060:     }
                   17061:     return $output;
                   17062: }
                   17063: 
                   17064: sub captcha_settings {
                   17065:     my %captcha_params = (
                   17066:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17067:                            www_output_dir => "/captchaspool",
                   17068:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17069:                            numchars       => '5',
                   17070:                          );
                   17071:     return %captcha_params;
                   17072: }
                   17073: 
                   17074: sub check_captcha {
                   17075:     my ($captcha_chk,$captcha_error);
                   17076:     my $code = $env{'form.code'};
                   17077:     my $md5sum = $env{'form.crypt'};
                   17078:     my %captcha_params = &captcha_settings();
                   17079:     my $captcha = Authen::Captcha->new(
                   17080:                       output_folder => $captcha_params{'output_dir'},
                   17081:                       data_folder   => $captcha_params{'db_dir'},
                   17082:                   );
1.1075.2.26  raeburn  17083:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17084:     my %captcha_hash = (
                   17085:                         0       => 'Code not checked (file error)',
                   17086:                        -1      => 'Failed: code expired',
                   17087:                        -2      => 'Failed: invalid code (not in database)',
                   17088:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17089:     );
                   17090:     if ($captcha_chk != 1) {
                   17091:         $captcha_error = $captcha_hash{$captcha_chk}
                   17092:     }
                   17093:     return ($captcha_chk,$captcha_error);
                   17094: }
                   17095: 
                   17096: sub create_recaptcha {
1.1075.2.107  raeburn  17097:     my ($pubkey,$version) = @_;
                   17098:     if ($version >= 2) {
                   17099:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17100:     } else {
                   17101:         my $use_ssl;
                   17102:         if ($ENV{'SERVER_PORT'} == 443) {
                   17103:             $use_ssl = 1;
                   17104:         }
                   17105:         my $captcha = Captcha::reCAPTCHA->new;
                   17106:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17107:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17108:                &mt('If the text is hard to read, [_1] will replace them.',
                   17109:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17110:                '<br /><br />';
                   17111:      }
1.1075.2.14  raeburn  17112: }
                   17113: 
                   17114: sub check_recaptcha {
1.1075.2.107  raeburn  17115:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17116:     my $captcha_chk;
1.1075.2.107  raeburn  17117:     if ($version >= 2) {
                   17118:         my $ua = LWP::UserAgent->new;
                   17119:         $ua->timeout(10);
                   17120:         my %info = (
                   17121:                      secret   => $privkey,
                   17122:                      response => $env{'form.g-recaptcha-response'},
                   17123:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17124:                    );
                   17125:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17126:         if ($response->is_success)  {
                   17127:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17128:             if (ref($data) eq 'HASH') {
                   17129:                 if ($data->{'success'}) {
                   17130:                     $captcha_chk = 1;
                   17131:                 }
                   17132:             }
                   17133:         }
                   17134:     } else {
                   17135:         my $captcha = Captcha::reCAPTCHA->new;
                   17136:         my $captcha_result =
                   17137:             $captcha->check_answer(
                   17138:                                     $privkey,
                   17139:                                     $ENV{'REMOTE_ADDR'},
                   17140:                                     $env{'form.recaptcha_challenge_field'},
                   17141:                                     $env{'form.recaptcha_response_field'},
                   17142:                                   );
                   17143:         if ($captcha_result->{is_valid}) {
                   17144:             $captcha_chk = 1;
                   17145:         }
1.1075.2.14  raeburn  17146:     }
                   17147:     return $captcha_chk;
                   17148: }
                   17149: 
1.1075.2.64  raeburn  17150: sub emailusername_info {
1.1075.2.103  raeburn  17151:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17152:     my %titles = &Apache::lonlocal::texthash (
                   17153:                      lastname      => 'Last Name',
                   17154:                      firstname     => 'First Name',
                   17155:                      institution   => 'School/college/university',
                   17156:                      location      => "School's city, state/province, country",
                   17157:                      web           => "School's web address",
                   17158:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17159:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17160:                  );
                   17161:     return (\@fields,\%titles);
                   17162: }
                   17163: 
1.1075.2.56  raeburn  17164: sub cleanup_html {
                   17165:     my ($incoming) = @_;
                   17166:     my $outgoing;
                   17167:     if ($incoming ne '') {
                   17168:         $outgoing = $incoming;
                   17169:         $outgoing =~ s/;/&#059;/g;
                   17170:         $outgoing =~ s/\#/&#035;/g;
                   17171:         $outgoing =~ s/\&/&#038;/g;
                   17172:         $outgoing =~ s/</&#060;/g;
                   17173:         $outgoing =~ s/>/&#062;/g;
                   17174:         $outgoing =~ s/\(/&#040/g;
                   17175:         $outgoing =~ s/\)/&#041;/g;
                   17176:         $outgoing =~ s/"/&#034;/g;
                   17177:         $outgoing =~ s/'/&#039;/g;
                   17178:         $outgoing =~ s/\$/&#036;/g;
                   17179:         $outgoing =~ s{/}{&#047;}g;
                   17180:         $outgoing =~ s/=/&#061;/g;
                   17181:         $outgoing =~ s/\\/&#092;/g
                   17182:     }
                   17183:     return $outgoing;
                   17184: }
                   17185: 
1.1075.2.74  raeburn  17186: # Checks for critical messages and returns a redirect url if one exists.
                   17187: # $interval indicates how often to check for messages.
                   17188: sub critical_redirect {
                   17189:     my ($interval) = @_;
                   17190:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17191:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17192:                                         $env{'user.name'});
                   17193:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17194:         my $redirecturl;
                   17195:         if ($what[0]) {
                   17196:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17197:                 $redirecturl='/adm/email?critical=display';
                   17198:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17199:                 return (1, $url);
                   17200:             }
                   17201:         }
                   17202:     }
                   17203:     return ();
                   17204: }
                   17205: 
1.1075.2.64  raeburn  17206: # Use:
                   17207: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17208: #
                   17209: ##################################################
                   17210: #          password associated functions         #
                   17211: ##################################################
                   17212: sub des_keys {
                   17213:     # Make a new key for DES encryption.
                   17214:     # Each key has two parts which are returned separately.
                   17215:     # Please note:  Each key must be passed through the &hex function
                   17216:     # before it is output to the web browser.  The hex versions cannot
                   17217:     # be used to decrypt.
                   17218:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17219:                 '8','9','a','b','c','d','e','f');
                   17220:     my $lkey='';
                   17221:     for (0..7) {
                   17222:         $lkey.=$hexstr[rand(15)];
                   17223:     }
                   17224:     my $ukey='';
                   17225:     for (0..7) {
                   17226:         $ukey.=$hexstr[rand(15)];
                   17227:     }
                   17228:     return ($lkey,$ukey);
                   17229: }
                   17230: 
                   17231: sub des_decrypt {
                   17232:     my ($key,$cyphertext) = @_;
                   17233:     my $keybin=pack("H16",$key);
                   17234:     my $cypher;
                   17235:     if ($Crypt::DES::VERSION>=2.03) {
                   17236:         $cypher=new Crypt::DES $keybin;
                   17237:     } else {
                   17238:         $cypher=new DES $keybin;
                   17239:     }
1.1075.2.106  raeburn  17240:     my $plaintext='';
                   17241:     my $cypherlength = length($cyphertext);
                   17242:     my $numchunks = int($cypherlength/32);
                   17243:     for (my $j=0; $j<$numchunks; $j++) {
                   17244:         my $start = $j*32;
                   17245:         my $cypherblock = substr($cyphertext,$start,32);
                   17246:         my $chunk =
                   17247:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17248:         $chunk .=
                   17249:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17250:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17251:         $plaintext .= $chunk;
                   17252:     }
1.1075.2.64  raeburn  17253:     return $plaintext;
                   17254: }
                   17255: 
1.1075.2.141.  .1(raebu 17256:20): sub make_short_symbs {
                   17257:20):     my ($cdom,$cnum,$navmap) = @_;
                   17258:20):     return unless (ref($navmap));
                   17259:20):     my ($numnew,@errors);
                   17260:20):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17261:20):     if (@toshorten) {
                   17262:20):         my (%maps,%resources,%titles);
                   17263:20):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17264:20):                                                                'shorturls',$cdom,$cnum);
                   17265:20):         my %tocreate;
                   17266:20):         if (keys(%resources)) {
                   17267:20):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17268:20):                 my $symb = $resources{$item};
                   17269:20):                 if ($symb) {
                   17270:20):                     $tocreate{$cnum.'&'.$symb} = 1;
                   17271:20):                 }
                   17272:20):             }
                   17273:20):         }
                   17274:20):         if (keys(%tocreate)) {
                   17275:20):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17276:20):             my $su = Short::URL->new(no_vowels => 1);
                   17277:20):             my $init = '';
                   17278:20):             my (%newunique,%addcourse,%courseonly,%failed);
                   17279:20):             # get lock on tiny db
                   17280:20):             my $now = time;
                   17281:20):             my $lockhash = {
                   17282:20):                                 "lock\0$now" => $env{'user.name'}.
                   17283:20):                                                 ':'.$env{'user.domain'},
                   17284:20):                             };
                   17285:20):             my $tries = 0;
                   17286:20):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17287:20):             my ($code,$error);
                   17288:20):             while (($gotlock ne 'ok') && ($tries<3)) {
                   17289:20):                 $tries ++;
                   17290:20):                 sleep 1;
                   17291:20):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17292:20):             }
                   17293:20):             if ($gotlock eq 'ok') {
                   17294:20):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17295:20):                                        \%addcourse,\%courseonly,\%failed);
                   17296:20):                 if (keys(%failed)) {
                   17297:20):                     my $numfailed = scalar(keys(%failed));
                   17298:20):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17299:20):                 }
                   17300:20):                 if (keys(%newunique)) {
                   17301:20):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17302:20):                     if ($putres eq 'ok') {
                   17303:20):                         $numnew = scalar(keys(%newunique));
                   17304:20):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17305:20):                         unless ($newputres eq 'ok') {
                   17306:20):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17307:20):                         }
                   17308:20):                     } else {
                   17309:20):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   17310:20):                     }
                   17311:20):                 }
                   17312:20):             }
                   17313:20):         }
                   17314:20):     }
                   17315:20):     return ($numnew,\@errors);
                   17316:20): }
                   17317:20): 
                   17318:20): sub shorten_symbs {
                   17319:20):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   17320:20):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   17321:20):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   17322:20):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   17323:20):     my (%possibles,%collisions);
                   17324:20):     foreach my $key (keys(%{$tocreate})) {
                   17325:20):         my $num = String::CRC32::crc32($key);
                   17326:20):         my $tiny = $su->encode($num,$init);
                   17327:20):         if ($tiny) {
                   17328:20):             $possibles{$tiny} = $key;
                   17329:20):         }
                   17330:20):     }
                   17331:20):     if (!$init) {
                   17332:20):         $init = 1;
                   17333:20):     } else {
                   17334:20):         $init ++;
                   17335:20):     }
                   17336:20):     if (keys(%possibles)) {
                   17337:20):         my @posstiny = keys(%possibles);
                   17338:20):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   17339:20):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   17340:20):         if (keys(%currtiny)) {
                   17341:20):             foreach my $key (keys(%currtiny)) {
                   17342:20):                 next if ($currtiny{$key} eq '');
                   17343:20):                 if ($currtiny{$key} eq $possibles{$key}) {
                   17344:20):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   17345:20):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17346:20):                         $courseonly->{$tsymb} = $key;
                   17347:20):                     }
                   17348:20):                 } else {
                   17349:20):                     $collisions{$possibles{$key}} = 1;
                   17350:20):                 }
                   17351:20):                 delete($possibles{$key});
                   17352:20):             }
                   17353:20):         }
                   17354:20):         foreach my $key (keys(%possibles)) {
                   17355:20):             $newunique->{$key} = $possibles{$key};
                   17356:20):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   17357:20):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17358:20):                 $addcourse->{$tsymb} = $key;
                   17359:20):             }
                   17360:20):         }
                   17361:20):     }
                   17362:20):     if (keys(%collisions)) {
                   17363:20):         if ($init <5) {
                   17364:20):             if (!$init) {
                   17365:20):                 $init = 1;
                   17366:20):             } else {
                   17367:20):                 $init ++;
                   17368:20):             }
                   17369:20):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   17370:20):                                    $newunique,$addcourse,$courseonly,$failed);
                   17371:20):         } else {
                   17372:20):             foreach my $key (keys(%collisions)) {
                   17373:20):                 $failed->{$key} = 1;
                   17374:20):                 $failed->{$key} = 1;
                   17375:20):             }
                   17376:20):         }
                   17377:20):     }
                   17378:20):     return $init;
                   17379:20): }
                   17380:20): 
1.1075.2.135  raeburn  17381: sub is_nonframeable {
                   17382:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17383:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17384:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17385: 
                   17386:     $remprotocol = lc($remprotocol);
                   17387:     $remhost = lc($remhost);
                   17388:     my $remport = 80;
                   17389:     if ($remprotocol eq 'https') {
                   17390:         $remport = 443;
                   17391:     }
                   17392:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17393:     if ($cached) {
                   17394:         unless ($nocache) {
                   17395:             if ($result) {
                   17396:                 return 1;
                   17397:             } else {
                   17398:                 return 0;
                   17399:             }
                   17400:         }
                   17401:     }
                   17402:     my $uselink;
                   17403:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.141.  .2(raebu 17404:20):     my $ua = LWP::UserAgent->new;
                   17405:20):     $ua->timeout(5);
                   17406:20):     my $response=$ua->request($request);
1.1075.2.135  raeburn  17407:     if ($response->is_success()) {
                   17408:         my $secpolicy = lc($response->header('content-security-policy'));
                   17409:         my $xframeop = lc($response->header('x-frame-options'));
                   17410:         $secpolicy =~ s/^\s+|\s+$//g;
                   17411:         $xframeop =~ s/^\s+|\s+$//g;
                   17412:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17413:             my $remotehost = $remprotocol.'://'.$remhost;
                   17414:             my ($origin,$protocol,$port);
                   17415:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17416:                 $port = $ENV{'SERVER_PORT'};
                   17417:             } else {
                   17418:                 $port = 80;
                   17419:             }
                   17420:             if ($absolute eq '') {
                   17421:                 $protocol = 'http:';
                   17422:                 if ($port == 443) {
                   17423:                     $protocol = 'https:';
                   17424:                 }
                   17425:                 $origin = $protocol.'//'.lc($hostname);
                   17426:             } else {
                   17427:                 $origin = lc($absolute);
                   17428:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17429:             }
                   17430:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17431:                 my $framepolicy = $1;
                   17432:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17433:                 my @policies = split(/\s+/,$framepolicy);
                   17434:                 if (@policies) {
                   17435:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17436:                         $uselink = 1;
                   17437:                     } else {
                   17438:                         $uselink = 1;
                   17439:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17440:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17441:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17442:                             undef($uselink);
                   17443:                         }
                   17444:                         if ($uselink) {
                   17445:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17446:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17447:                                     undef($uselink);
                   17448:                                 }
                   17449:                             }
                   17450:                         }
                   17451:                         if ($uselink) {
                   17452:                             my @possok;
                   17453:                             if ($ip ne '') {
                   17454:                                 push(@possok,$ip);
                   17455:                             }
                   17456:                             my $hoststr = '';
                   17457:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17458:                                 if ($hoststr eq '') {
                   17459:                                     $hoststr = $part;
                   17460:                                 } else {
                   17461:                                     $hoststr = "$part.$hoststr";
                   17462:                                 }
                   17463:                                 if ($hoststr eq $hostname) {
                   17464:                                     push(@possok,$hostname);
                   17465:                                 } else {
                   17466:                                     push(@possok,"*.$hoststr");
                   17467:                                 }
                   17468:                             }
                   17469:                             if (@possok) {
                   17470:                                 foreach my $poss (@possok) {
                   17471:                                     last if (!$uselink);
                   17472:                                     foreach my $policy (@policies) {
                   17473:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17474:                                             undef($uselink);
                   17475:                                             last;
                   17476:                                         }
                   17477:                                     }
                   17478:                                 }
                   17479:                             }
                   17480:                         }
                   17481:                     }
                   17482:                 }
                   17483:             } elsif ($xframeop ne '') {
                   17484:                 $uselink = 1;
                   17485:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17486:                 if (@policies) {
                   17487:                     unless (grep(/^deny$/,@policies)) {
                   17488:                         if ($origin ne '') {
                   17489:                             if (grep(/^sameorigin$/,@policies)) {
                   17490:                                 if ($remotehost eq $origin) {
                   17491:                                     undef($uselink);
                   17492:                                 }
                   17493:                             }
                   17494:                             if ($uselink) {
                   17495:                                 foreach my $policy (@policies) {
                   17496:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17497:                                         my $allowfrom = $1;
                   17498:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17499:                                             undef($uselink);
                   17500:                                             last;
                   17501:                                         }
                   17502:                                     }
                   17503:                                 }
                   17504:                             }
                   17505:                         }
                   17506:                     }
                   17507:                 }
                   17508:             }
                   17509:         }
                   17510:     }
                   17511:     if ($nocache) {
                   17512:         if ($cached) {
                   17513:             my $devalidate;
                   17514:             if ($uselink && !$result) {
                   17515:                 $devalidate = 1;
                   17516:             } elsif (!$uselink && $result) {
                   17517:                 $devalidate = 1;
                   17518:             }
                   17519:             if ($devalidate) {
                   17520:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17521:             }
                   17522:         }
                   17523:     } else {
                   17524:         if ($uselink) {
                   17525:             $result = 1;
                   17526:         } else {
                   17527:             $result = 0;
                   17528:         }
                   17529:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17530:     }
                   17531:     return $uselink;
                   17532: }
                   17533: 
1.112     bowersj2 17534: 1;
                   17535: __END__;
1.41      ng       17536: 

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