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

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.  .8(raebu    4:20): # $Id: loncommon.pm,v 1.1075.2.141.2.7 2020/09/28 17:45:08 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.141.  .7(raebu 4683:20):     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
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) =
1.1075.2.141.  .7(raebu 4689:20):                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  4690:             return ($startblock,$endblock,$triggerblock);
                   4691:         }
                   4692:     } else {
1.490     raeburn  4693:         $udom = $env{'user.domain'};
                   4694:         $uname = $env{'user.name'};
                   4695:     }
                   4696: 
1.502     raeburn  4697:     my $startblock = 0;
                   4698:     my $endblock = 0;
1.1062    raeburn  4699:     my $triggerblock = '';
1.482     raeburn  4700:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4701: 
1.490     raeburn  4702:     # If uname is for a user, and activity is course-specific, i.e.,
                   4703:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4704: 
1.490     raeburn  4705:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.141.  .6(raebu 4706:20):          $activity eq 'groups' || $activity eq 'printout' ||
          .8(raebu 4707:20):          $activity eq 'search' || $activity eq 'reinit' ||
                   4708:20):          $activity eq 'alert') &&
1.1075.2.73  raeburn  4709:         ($env{'request.course.id'})) {
1.490     raeburn  4710:         foreach my $key (keys(%live_courses)) {
                   4711:             if ($key ne $env{'request.course.id'}) {
                   4712:                 delete($live_courses{$key});
                   4713:             }
                   4714:         }
                   4715:     }
                   4716: 
                   4717:     my $otheruser = 0;
                   4718:     my %own_courses;
                   4719:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4720:         # Resource belongs to user other than current user.
                   4721:         $otheruser = 1;
                   4722:         # Gather courses for current user
                   4723:         %own_courses = 
                   4724:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4725:     }
                   4726: 
                   4727:     # Gather active course roles - course coordinator, instructor, 
                   4728:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4729: 
                   4730:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4731:         my ($cdom,$cnum);
                   4732:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4733:             $cdom = $env{'course.'.$course.'.domain'};
                   4734:             $cnum = $env{'course.'.$course.'.num'};
                   4735:         } else {
1.490     raeburn  4736:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4737:         }
                   4738:         my $no_ownblock = 0;
                   4739:         my $no_userblock = 0;
1.533     raeburn  4740:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4741:             # Check if current user has 'evb' priv for this
                   4742:             if (defined($own_courses{$course})) {
                   4743:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4744:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4745:                     if ($sec ne 'none') {
                   4746:                         $checkrole .= '/'.$sec;
                   4747:                     }
                   4748:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4749:                         $no_ownblock = 1;
                   4750:                         last;
                   4751:                     }
                   4752:                 }
                   4753:             }
                   4754:             # if they have 'evb' priv and are currently not playing student
                   4755:             next if (($no_ownblock) &&
                   4756:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4757:         }
1.474     raeburn  4758:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4759:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4760:             if ($sec ne 'none') {
1.482     raeburn  4761:                 $checkrole .= '/'.$sec;
1.474     raeburn  4762:             }
1.490     raeburn  4763:             if ($otheruser) {
                   4764:                 # Resource belongs to user other than current user.
                   4765:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4766:                 my (%allroles,%userroles);
                   4767:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4768:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4769:                         my ($trole,$tdom,$tnum,$tsec);
                   4770:                         if ($entry =~ /^cr/) {
                   4771:                             ($trole,$tdom,$tnum,$tsec) = 
                   4772:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4773:                         } else {
                   4774:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4775:                         }
                   4776:                         my ($spec,$area,$trest);
                   4777:                         $area = '/'.$tdom.'/'.$tnum;
                   4778:                         $trest = $tnum;
                   4779:                         if ($tsec ne '') {
                   4780:                             $area .= '/'.$tsec;
                   4781:                             $trest .= '/'.$tsec;
                   4782:                         }
                   4783:                         $spec = $trole.'.'.$area;
                   4784:                         if ($trole =~ /^cr/) {
                   4785:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4786:                                                               $tdom,$spec,$trest,$area);
                   4787:                         } else {
                   4788:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4789:                                                                 $tdom,$spec,$trest,$area);
                   4790:                         }
                   4791:                     }
1.1075.2.124  raeburn  4792:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4793:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4794:                         if ($1) {
                   4795:                             $no_userblock = 1;
                   4796:                             last;
                   4797:                         }
1.486     raeburn  4798:                     }
                   4799:                 }
1.490     raeburn  4800:             } else {
                   4801:                 # Resource belongs to current user
                   4802:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4803:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4804:                     $no_ownblock = 1;
                   4805:                     last;
                   4806:                 }
1.474     raeburn  4807:             }
                   4808:         }
                   4809:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4810:         next if (($no_ownblock) &&
1.491     albertel 4811:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4812:         next if ($no_userblock);
1.474     raeburn  4813: 
1.1075.2.128  raeburn  4814:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4815:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4816:         
1.1062    raeburn  4817:         my ($start,$end,$trigger) = 
1.1075.2.141.  .7(raebu 4818:20):             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  4819:         if (($start != 0) && 
                   4820:             (($startblock == 0) || ($startblock > $start))) {
                   4821:             $startblock = $start;
1.1062    raeburn  4822:             if ($trigger ne '') {
                   4823:                 $triggerblock = $trigger;
                   4824:             }
1.502     raeburn  4825:         }
                   4826:         if (($end != 0)  &&
                   4827:             (($endblock == 0) || ($endblock < $end))) {
                   4828:             $endblock = $end;
1.1062    raeburn  4829:             if ($trigger ne '') {
                   4830:                 $triggerblock = $trigger;
                   4831:             }
1.502     raeburn  4832:         }
1.490     raeburn  4833:     }
1.1062    raeburn  4834:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4835: }
                   4836: 
                   4837: sub get_blocks {
1.1075.2.141.  .7(raebu 4838:20):     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  4839:     my $startblock = 0;
                   4840:     my $endblock = 0;
1.1062    raeburn  4841:     my $triggerblock = '';
1.490     raeburn  4842:     my $course = $cdom.'_'.$cnum;
                   4843:     $setters->{$course} = {};
                   4844:     $setters->{$course}{'staff'} = [];
                   4845:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4846:     $setters->{$course}{'triggers'} = [];
                   4847:     my (@blockers,%triggered);
                   4848:     my $now = time;
                   4849:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4850:     if ($activity eq 'docs') {
1.1075.2.141.  .7(raebu 4851:20):         my ($blocked,$nosymbcache);
                   4852:20):         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   4853:20):             $blocked = 1;
                   4854:20):             $nosymbcache = 1;
                   4855:20):         }
                   4856:20):         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$blocked,\%commblocks);
1.1062    raeburn  4857:         foreach my $block (@blockers) {
                   4858:             if ($block =~ /^firstaccess____(.+)$/) {
                   4859:                 my $item = $1;
                   4860:                 my $type = 'map';
                   4861:                 my $timersymb = $item;
                   4862:                 if ($item eq 'course') {
                   4863:                     $type = 'course';
                   4864:                 } elsif ($item =~ /___\d+___/) {
                   4865:                     $type = 'resource';
                   4866:                 } else {
                   4867:                     $timersymb = &Apache::lonnet::symbread($item);
                   4868:                 }
                   4869:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4870:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4871:                 $triggered{$block} = {
                   4872:                                        start => $start,
                   4873:                                        end   => $end,
                   4874:                                        type  => $type,
                   4875:                                      };
                   4876:             }
                   4877:         }
                   4878:     } else {
                   4879:         foreach my $block (keys(%commblocks)) {
                   4880:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4881:                 my ($start,$end) = ($1,$2);
                   4882:                 if ($start <= time && $end >= time) {
                   4883:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4884:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4885:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4886:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4887:                                     push(@blockers,$block);
                   4888:                                 }
                   4889:                             }
                   4890:                         }
                   4891:                     }
                   4892:                 }
                   4893:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4894:                 my $item = $1;
                   4895:                 my $timersymb = $item; 
                   4896:                 my $type = 'map';
                   4897:                 if ($item eq 'course') {
                   4898:                     $type = 'course';
                   4899:                 } elsif ($item =~ /___\d+___/) {
                   4900:                     $type = 'resource';
                   4901:                 } else {
                   4902:                     $timersymb = &Apache::lonnet::symbread($item);
                   4903:                 }
                   4904:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4905:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4906:                 if ($start && $end) {
                   4907:                     if (($start <= time) && ($end >= time)) {
                   4908:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4909:                             push(@blockers,$block);
                   4910:                             $triggered{$block} = {
                   4911:                                                    start => $start,
                   4912:                                                    end   => $end,
                   4913:                                                    type  => $type,
                   4914:                                                  };
                   4915:                         }
                   4916:                     }
1.490     raeburn  4917:                 }
1.1062    raeburn  4918:             }
                   4919:         }
                   4920:     }
                   4921:     foreach my $blocker (@blockers) {
                   4922:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4923:             &parse_block_record($commblocks{$blocker});
                   4924:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4925:         my ($start,$end,$triggertype);
                   4926:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4927:             ($start,$end) = ($1,$2);
                   4928:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4929:             $start = $triggered{$blocker}{'start'};
                   4930:             $end = $triggered{$blocker}{'end'};
                   4931:             $triggertype = $triggered{$blocker}{'type'};
                   4932:         }
                   4933:         if ($start) {
                   4934:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4935:             if ($triggertype) {
                   4936:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4937:             } else {
                   4938:                 push(@{$$setters{$course}{'triggers'}},0);
                   4939:             }
                   4940:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4941:                 $startblock = $start;
                   4942:                 if ($triggertype) {
                   4943:                     $triggerblock = $blocker;
1.474     raeburn  4944:                 }
                   4945:             }
1.1062    raeburn  4946:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4947:                $endblock = $end;
                   4948:                if ($triggertype) {
                   4949:                    $triggerblock = $blocker;
                   4950:                }
                   4951:             }
1.474     raeburn  4952:         }
                   4953:     }
1.1062    raeburn  4954:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4955: }
                   4956: 
                   4957: sub parse_block_record {
                   4958:     my ($record) = @_;
                   4959:     my ($setuname,$setudom,$title,$blocks);
                   4960:     if (ref($record) eq 'HASH') {
                   4961:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4962:         $title = &unescape($record->{'event'});
                   4963:         $blocks = $record->{'blocks'};
                   4964:     } else {
                   4965:         my @data = split(/:/,$record,3);
                   4966:         if (scalar(@data) eq 2) {
                   4967:             $title = $data[1];
                   4968:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4969:         } else {
                   4970:             ($setuname,$setudom,$title) = @data;
                   4971:         }
                   4972:         $blocks = { 'com' => 'on' };
                   4973:     }
                   4974:     return ($setuname,$setudom,$title,$blocks);
                   4975: }
                   4976: 
1.854     kalberla 4977: sub blocking_status {
1.1075.2.141.  .7(raebu 4978:20):     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  4979:     my %setters;
1.890     droeschl 4980: 
1.1061    raeburn  4981: # check for active blocking
1.1062    raeburn  4982:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.141.  .7(raebu 4983:20):         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  4984:     my $blocked = 0;
                   4985:     if ($startblock && $endblock) {
                   4986:         $blocked = 1;
                   4987:     }
1.890     droeschl 4988: 
1.1061    raeburn  4989: # caller just wants to know whether a block is active
                   4990:     if (!wantarray) { return $blocked; }
                   4991: 
                   4992: # build a link to a popup window containing the details
                   4993:     my $querystring  = "?activity=$activity";
                   4994: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4995:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4996:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4997:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4998:     } elsif ($activity eq 'docs') {
1.1075.2.141.  .7(raebu 4999:20):         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5000:20):         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5001:20):         if ($symb) {
                   5002:20):             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5003:20):             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5004:20):         }
1.1062    raeburn  5005:     }
1.1061    raeburn  5006: 
                   5007:     my $output .= <<'END_MYBLOCK';
                   5008: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5009:     var options = "width=" + w + ",height=" + h + ",";
                   5010:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5011:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5012:     var newWin = window.open(url, wdwName, options);
                   5013:     newWin.focus();
                   5014: }
1.890     droeschl 5015: END_MYBLOCK
1.854     kalberla 5016: 
1.1061    raeburn  5017:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5018:   
1.1061    raeburn  5019:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5020:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5021:     my $class = 'LC_comblock';
1.1062    raeburn  5022:     if ($activity eq 'docs') {
                   5023:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5024:         $class = '';
1.1063    raeburn  5025:     } elsif ($activity eq 'printout') {
                   5026:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5027:     } elsif ($activity eq 'passwd') {
                   5028:         $text = &mt('Password Changing Blocked');
1.1075.2.141.  .6(raebu 5029:20):     } elsif ($activity eq 'grades') {
                   5030:20):         $text = &mt('Gradebook Blocked');
          .8(raebu 5031:20):     } elsif ($activity eq 'search') {
                   5032:20):         $text = &mt('Search Blocked');
          .6(raebu 5033:20):     } elsif ($activity eq 'alert') {
                   5034:20):         $text = &mt('Checking Critical Messages Blocked');
                   5035:20):     } elsif ($activity eq 'reinit') {
                   5036:20):         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5037:     }
1.1061    raeburn  5038:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5039: <div class='$class'>
1.869     kalberla 5040:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5041:   title='$text'>
                   5042:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5043:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5044:   title='$text'>$text</a>
1.867     kalberla 5045: </div>
                   5046: 
                   5047: END_BLOCK
1.474     raeburn  5048: 
1.1061    raeburn  5049:     return ($blocked, $output);
1.854     kalberla 5050: }
1.490     raeburn  5051: 
1.60      matthew  5052: ###############################################
                   5053: 
1.682     raeburn  5054: sub check_ip_acc {
1.1075.2.105  raeburn  5055:     my ($acc,$clientip)=@_;
1.682     raeburn  5056:     &Apache::lonxml::debug("acc is $acc");
                   5057:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5058:         return 1;
                   5059:     }
1.1075.2.141.  .4(raebu 5060:20):     my ($ip,$allowed);
                   5061:20):     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5062:20):         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5063:20):         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5064:20):     } else {
                   5065:20):         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   5066:20):     }
1.682     raeburn  5067: 
                   5068:     my $name;
1.1075.2.141.  .1(raebu 5069:20):     my %access = (
                   5070:20):                      allowfrom => 1,
                   5071:20):                      denyfrom  => 0,
                   5072:20):                  );
                   5073:20):     my @allows;
                   5074:20):     my @denies;
                   5075:20):     foreach my $item (split(',',$acc)) {
                   5076:20):         $item =~ s/^\s*//;
                   5077:20):         $item =~ s/\s*$//;
                   5078:20):         if ($item =~ /^\!(.+)$/) {
                   5079:20):             push(@denies,$1);
                   5080:20):         } else {
                   5081:20):             push(@allows,$item);
                   5082:20):         }
                   5083:20):     }
                   5084:20):     my $numdenies = scalar(@denies);
                   5085:20):     my $numallows = scalar(@allows);
                   5086:20):     my $count = 0;
                   5087:20):     foreach my $pattern (@denies,@allows) {
                   5088:20):         $count ++;
                   5089:20):         my $acctype = 'allowfrom';
                   5090:20):         if ($count <= $numdenies) {
                   5091:20):             $acctype = 'denyfrom';
                   5092:20):         }
1.682     raeburn  5093:         if ($pattern =~ /\*$/) {
                   5094:             #35.8.*
                   5095:             $pattern=~s/\*//;
1.1075.2.141.  .1(raebu 5096:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5097:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5098:             #35.8.3.[34-56]
                   5099:             my $low=$2;
                   5100:             my $high=$3;
                   5101:             $pattern=$1;
                   5102:             if ($ip =~ /^\Q$pattern\E/) {
                   5103:                 my $last=(split(/\./,$ip))[3];
1.1075.2.141.  .1(raebu 5104:20):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5105:             }
                   5106:         } elsif ($pattern =~ /^\*/) {
                   5107:             #*.msu.edu
                   5108:             $pattern=~s/\*//;
                   5109:             if (!defined($name)) {
                   5110:                 use Socket;
                   5111:                 my $netaddr=inet_aton($ip);
                   5112:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5113:             }
1.1075.2.141.  .1(raebu 5114:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5115:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5116:             #127.0.0.1
1.1075.2.141.  .1(raebu 5117:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5118:         } else {
                   5119:             #some.name.com
                   5120:             if (!defined($name)) {
                   5121:                 use Socket;
                   5122:                 my $netaddr=inet_aton($ip);
                   5123:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5124:             }
1.1075.2.141.  .1(raebu 5125:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5126:20):         }
                   5127:20):         if ($allowed =~ /^(0|1)$/) { last; }
                   5128:20):     }
                   5129:20):     if ($allowed eq '') {
                   5130:20):         if ($numdenies && !$numallows) {
                   5131:20):             $allowed = 1;
                   5132:20):         } else {
                   5133:20):             $allowed = 0;
1.682     raeburn  5134:         }
                   5135:     }
                   5136:     return $allowed;
                   5137: }
                   5138: 
                   5139: ###############################################
                   5140: 
1.60      matthew  5141: =pod
                   5142: 
1.112     bowersj2 5143: =head1 Domain Template Functions
                   5144: 
                   5145: =over 4
                   5146: 
                   5147: =item * &determinedomain()
1.60      matthew  5148: 
                   5149: Inputs: $domain (usually will be undef)
                   5150: 
1.63      www      5151: Returns: Determines which domain should be used for designs
1.60      matthew  5152: 
                   5153: =cut
1.54      www      5154: 
1.60      matthew  5155: ###############################################
1.63      www      5156: sub determinedomain {
                   5157:     my $domain=shift;
1.531     albertel 5158:     if (! $domain) {
1.60      matthew  5159:         # Determine domain if we have not been given one
1.893     raeburn  5160:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5161:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5162:         if ($env{'request.role.domain'}) { 
                   5163:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5164:         }
                   5165:     }
1.63      www      5166:     return $domain;
                   5167: }
                   5168: ###############################################
1.517     raeburn  5169: 
1.518     albertel 5170: sub devalidate_domconfig_cache {
                   5171:     my ($udom)=@_;
                   5172:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5173: }
                   5174: 
                   5175: # ---------------------- Get domain configuration for a domain
                   5176: sub get_domainconf {
                   5177:     my ($udom) = @_;
                   5178:     my $cachetime=1800;
                   5179:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5180:     if (defined($cached)) { return %{$result}; }
                   5181: 
                   5182:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5183: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5184:     my (%designhash,%legacy);
1.518     albertel 5185:     if (keys(%domconfig) > 0) {
                   5186:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5187:             if (keys(%{$domconfig{'login'}})) {
                   5188:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5189:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5190:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5191:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5192:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5193:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5194:                                         if ($key eq 'loginvia') {
                   5195:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5196:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5197:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5198:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5199:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5200:                                                 } else {
                   5201:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5202:                                                 }
1.948     raeburn  5203:                                             }
1.1075.2.87  raeburn  5204:                                         } elsif ($key eq 'headtag') {
                   5205:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5206:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5207:                                             }
1.946     raeburn  5208:                                         }
1.1075.2.87  raeburn  5209:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5210:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5211:                                         }
1.946     raeburn  5212:                                     }
                   5213:                                 }
                   5214:                             }
                   5215:                         } else {
                   5216:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5217:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5218:                                     $domconfig{'login'}{$key}{$img};
                   5219:                             }
1.699     raeburn  5220:                         }
                   5221:                     } else {
                   5222:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5223:                     }
1.632     raeburn  5224:                 }
                   5225:             } else {
                   5226:                 $legacy{'login'} = 1;
1.518     albertel 5227:             }
1.632     raeburn  5228:         } else {
                   5229:             $legacy{'login'} = 1;
1.518     albertel 5230:         }
                   5231:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5232:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5233:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5234:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5235:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5236:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5237:                         }
1.518     albertel 5238:                     }
                   5239:                 }
1.632     raeburn  5240:             } else {
                   5241:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5242:             }
1.632     raeburn  5243:         } else {
                   5244:             $legacy{'rolecolors'} = 1;
1.518     albertel 5245:         }
1.948     raeburn  5246:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5247:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5248:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5249:             }
                   5250:         }
1.632     raeburn  5251:         if (keys(%legacy) > 0) {
                   5252:             my %legacyhash = &get_legacy_domconf($udom);
                   5253:             foreach my $item (keys(%legacyhash)) {
                   5254:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5255:                     if ($legacy{'login'}) { 
                   5256:                         $designhash{$item} = $legacyhash{$item};
                   5257:                     }
                   5258:                 } else {
                   5259:                     if ($legacy{'rolecolors'}) {
                   5260:                         $designhash{$item} = $legacyhash{$item};
                   5261:                     }
1.518     albertel 5262:                 }
                   5263:             }
                   5264:         }
1.632     raeburn  5265:     } else {
                   5266:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5267:     }
                   5268:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5269: 				  $cachetime);
                   5270:     return %designhash;
                   5271: }
                   5272: 
1.632     raeburn  5273: sub get_legacy_domconf {
                   5274:     my ($udom) = @_;
                   5275:     my %legacyhash;
                   5276:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5277:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5278:     if (-e $designfile) {
1.1075.2.128  raeburn  5279:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5280:             while (my $line = <$fh>) {
                   5281:                 next if ($line =~ /^\#/);
                   5282:                 chomp($line);
                   5283:                 my ($key,$val)=(split(/\=/,$line));
                   5284:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5285:             }
                   5286:             close($fh);
                   5287:         }
                   5288:     }
1.1026    raeburn  5289:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5290:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5291:     }
                   5292:     return %legacyhash;
                   5293: }
                   5294: 
1.63      www      5295: =pod
                   5296: 
1.112     bowersj2 5297: =item * &domainlogo()
1.63      www      5298: 
                   5299: Inputs: $domain (usually will be undef)
                   5300: 
                   5301: Returns: A link to a domain logo, if the domain logo exists.
                   5302: If the domain logo does not exist, a description of the domain.
                   5303: 
                   5304: =cut
1.112     bowersj2 5305: 
1.63      www      5306: ###############################################
                   5307: sub domainlogo {
1.517     raeburn  5308:     my $domain = &determinedomain(shift);
1.518     albertel 5309:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5310:     # See if there is a logo
                   5311:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5312:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5313:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5314: 	    if ($imgsrc =~ m{^/res/}) {
                   5315: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5316: 		&Apache::lonnet::repcopy($local_name);
                   5317: 	    }
                   5318: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5319:         } 
                   5320:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5321:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5322:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5323:     } else {
1.60      matthew  5324:         return '';
1.59      www      5325:     }
                   5326: }
1.63      www      5327: ##############################################
                   5328: 
                   5329: =pod
                   5330: 
1.112     bowersj2 5331: =item * &designparm()
1.63      www      5332: 
                   5333: Inputs: $which parameter; $domain (usually will be undef)
                   5334: 
                   5335: Returns: value of designparamter $which
                   5336: 
                   5337: =cut
1.112     bowersj2 5338: 
1.397     albertel 5339: 
1.400     albertel 5340: ##############################################
1.397     albertel 5341: sub designparm {
                   5342:     my ($which,$domain)=@_;
                   5343:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5344:         return $env{'environment.color.'.$which};
1.96      www      5345:     }
1.63      www      5346:     $domain=&determinedomain($domain);
1.1016    raeburn  5347:     my %domdesign;
                   5348:     unless ($domain eq 'public') {
                   5349:         %domdesign = &get_domainconf($domain);
                   5350:     }
1.520     raeburn  5351:     my $output;
1.517     raeburn  5352:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5353:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5354:     } else {
1.520     raeburn  5355:         $output = $defaultdesign{$which};
                   5356:     }
                   5357:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5358:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5359:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5360:             if ($output =~ m{^/res/}) {
                   5361:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5362:                 &Apache::lonnet::repcopy($local_name);
                   5363:             }
1.520     raeburn  5364:             $output = &lonhttpdurl($output);
                   5365:         }
1.63      www      5366:     }
1.520     raeburn  5367:     return $output;
1.63      www      5368: }
1.59      www      5369: 
1.822     bisitz   5370: ##############################################
                   5371: =pod
                   5372: 
1.832     bisitz   5373: =item * &authorspace()
                   5374: 
1.1028    raeburn  5375: Inputs: $url (usually will be undef).
1.832     bisitz   5376: 
1.1075.2.40  raeburn  5377: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5378:          directory being viewed (or for which action is being taken). 
                   5379:          If $url is provided, and begins /priv/<domain>/<uname>
                   5380:          the path will be that portion of the $context argument.
                   5381:          Otherwise the path will be for the author space of the current
                   5382:          user when the current role is author, or for that of the 
                   5383:          co-author/assistant co-author space when the current role 
                   5384:          is co-author or assistant co-author.
1.832     bisitz   5385: 
                   5386: =cut
                   5387: 
                   5388: sub authorspace {
1.1028    raeburn  5389:     my ($url) = @_;
                   5390:     if ($url ne '') {
                   5391:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5392:            return $1;
                   5393:         }
                   5394:     }
1.832     bisitz   5395:     my $caname = '';
1.1024    www      5396:     my $cadom = '';
1.1028    raeburn  5397:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5398:         ($cadom,$caname) =
1.832     bisitz   5399:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5400:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5401:         $caname = $env{'user.name'};
1.1024    www      5402:         $cadom = $env{'user.domain'};
1.832     bisitz   5403:     }
1.1028    raeburn  5404:     if (($caname ne '') && ($cadom ne '')) {
                   5405:         return "/priv/$cadom/$caname/";
                   5406:     }
                   5407:     return;
1.832     bisitz   5408: }
                   5409: 
                   5410: ##############################################
                   5411: =pod
                   5412: 
1.822     bisitz   5413: =item * &head_subbox()
                   5414: 
                   5415: Inputs: $content (contains HTML code with page functions, etc.)
                   5416: 
                   5417: Returns: HTML div with $content
                   5418:          To be included in page header
                   5419: 
                   5420: =cut
                   5421: 
                   5422: sub head_subbox {
                   5423:     my ($content)=@_;
                   5424:     my $output =
1.993     raeburn  5425:         '<div class="LC_head_subbox">'
1.822     bisitz   5426:        .$content
                   5427:        .'</div>'
                   5428: }
                   5429: 
                   5430: ##############################################
                   5431: =pod
                   5432: 
                   5433: =item * &CSTR_pageheader()
                   5434: 
1.1026    raeburn  5435: Input: (optional) filename from which breadcrumb trail is built.
                   5436:        In most cases no input as needed, as $env{'request.filename'}
                   5437:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5438: 
                   5439: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5440:          To be included on Authoring Space pages
1.822     bisitz   5441: 
                   5442: =cut
                   5443: 
                   5444: sub CSTR_pageheader {
1.1026    raeburn  5445:     my ($trailfile) = @_;
                   5446:     if ($trailfile eq '') {
                   5447:         $trailfile = $env{'request.filename'};
                   5448:     }
                   5449: 
                   5450: # this is for resources; directories have customtitle, and crumbs
                   5451: # and select recent are created in lonpubdir.pm
                   5452: 
                   5453:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5454:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5455:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5456:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5457:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5458: 
                   5459:     my $parentpath = '';
                   5460:     my $lastitem = '';
                   5461:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5462:         $parentpath = $1;
                   5463:         $lastitem = $2;
                   5464:     } else {
                   5465:         $lastitem = $thisdisfn;
                   5466:     }
1.921     bisitz   5467: 
                   5468:     my $output =
1.822     bisitz   5469:          '<div>'
                   5470:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5471:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5472:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5473:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5474:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5475: 
                   5476:     if ($lastitem) {
                   5477:         $output .=
                   5478:              '<span class="LC_filename">'
                   5479:             .$lastitem
                   5480:             .'</span>';
                   5481:     }
                   5482:     $output .=
                   5483:          '<br />'
1.822     bisitz   5484:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5485:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5486:         .'</form>'
                   5487:         .&Apache::lonmenu::constspaceform()
                   5488:         .'</div>';
1.921     bisitz   5489: 
                   5490:     return $output;
1.822     bisitz   5491: }
                   5492: 
1.60      matthew  5493: ###############################################
                   5494: ###############################################
                   5495: 
                   5496: =pod
                   5497: 
1.112     bowersj2 5498: =back
                   5499: 
1.549     albertel 5500: =head1 HTML Helpers
1.112     bowersj2 5501: 
                   5502: =over 4
                   5503: 
                   5504: =item * &bodytag()
1.60      matthew  5505: 
                   5506: Returns a uniform header for LON-CAPA web pages.
                   5507: 
                   5508: Inputs: 
                   5509: 
1.112     bowersj2 5510: =over 4
                   5511: 
                   5512: =item * $title, A title to be displayed on the page.
                   5513: 
                   5514: =item * $function, the current role (can be undef).
                   5515: 
                   5516: =item * $addentries, extra parameters for the <body> tag.
                   5517: 
                   5518: =item * $bodyonly, if defined, only return the <body> tag.
                   5519: 
                   5520: =item * $domain, if defined, force a given domain.
                   5521: 
                   5522: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5523:             text interface only)
1.60      matthew  5524: 
1.814     bisitz   5525: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5526:                      navigational links
1.317     albertel 5527: 
1.338     albertel 5528: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5529: 
1.1075.2.12  raeburn  5530: =item * $no_inline_link, if true and in remote mode, don't show the
                   5531:          'Switch To Inline Menu' link
                   5532: 
1.460     albertel 5533: =item * $args, optional argument valid values are
                   5534:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5535:             use_absolute     -> for external resource or syllabus, this will
                   5536:                                 contain https://<hostname> if server uses
                   5537:                                 https (as per hosts.tab), but request is for http
                   5538:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5539: 
1.1075.2.15  raeburn  5540: =item * $advtoolsref, optional argument, ref to an array containing
                   5541:             inlineremote items to be added in "Functions" menu below
                   5542:             breadcrumbs.
                   5543: 
1.112     bowersj2 5544: =back
                   5545: 
1.60      matthew  5546: Returns: A uniform header for LON-CAPA web pages.  
                   5547: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5548: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5549: other decorations will be returned.
                   5550: 
                   5551: =cut
                   5552: 
1.54      www      5553: sub bodytag {
1.831     bisitz   5554:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5555:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5556: 
1.954     raeburn  5557:     my $public;
                   5558:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5559:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5560:         $public = 1;
                   5561:     }
1.460     albertel 5562:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5563:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5564:     my $hostname = $args->{'hostname'};
1.339     albertel 5565: 
1.183     matthew  5566:     $function = &get_users_function() if (!$function);
1.339     albertel 5567:     my $img =    &designparm($function.'.img',$domain);
                   5568:     my $font =   &designparm($function.'.font',$domain);
                   5569:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5570: 
1.803     bisitz   5571:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5572: 		   'bgcolor' => $pgbg,
1.339     albertel 5573: 		   'text'    => $font,
                   5574:                    'alink'   => &designparm($function.'.alink',$domain),
                   5575: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5576: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5577:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5578: 
1.63      www      5579:  # role and realm
1.1075.2.68  raeburn  5580:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5581:     if ($realm) {
                   5582:         $realm = '/'.$realm;
                   5583:     }
1.378     raeburn  5584:     if ($role  eq 'ca') {
1.479     albertel 5585:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5586:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5587:     } 
1.55      www      5588: # realm
1.258     albertel 5589:     if ($env{'request.course.id'}) {
1.378     raeburn  5590:         if ($env{'request.role'} !~ /^cr/) {
                   5591:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5592:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5593:             if ($env{'request.role.desc'}) {
                   5594:                 $role = $env{'request.role.desc'};
                   5595:             } else {
                   5596:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5597:             }
1.1075.2.115  raeburn  5598:         } else {
                   5599:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5600:         }
1.898     raeburn  5601:         if ($env{'request.course.sec'}) {
                   5602:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5603:         }   
1.359     albertel 5604: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5605:     } else {
                   5606:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5607:     }
1.433     albertel 5608: 
1.359     albertel 5609:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5610: 
1.438     albertel 5611:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5612: 
1.101     www      5613: # construct main body tag
1.359     albertel 5614:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5615: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5616: 
1.1075.2.38  raeburn  5617:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5618: 
                   5619:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5620:         return $bodytag;
1.1075.2.38  raeburn  5621:     }
1.359     albertel 5622: 
1.954     raeburn  5623:     if ($public) {
1.433     albertel 5624: 	undef($role);
                   5625:     }
1.359     albertel 5626:     
1.762     bisitz   5627:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5628:     #
                   5629:     # Extra info if you are the DC
                   5630:     my $dc_info = '';
                   5631:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5632:                         $env{'course.'.$env{'request.course.id'}.
                   5633:                                  '.domain'}.'/'})) {
                   5634:         my $cid = $env{'request.course.id'};
1.917     raeburn  5635:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5636:         $dc_info =~ s/\s+$//;
1.359     albertel 5637:     }
                   5638: 
1.1075.2.108  raeburn  5639:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5640: 
1.1075.2.13  raeburn  5641:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5642: 
1.1075.2.38  raeburn  5643: 
                   5644: 
1.1075.2.21  raeburn  5645:     my $funclist;
                   5646:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5647:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5648:                     Apache::lonmenu::serverform();
                   5649:         my $forbodytag;
                   5650:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5651:                                             $forcereg,$args->{'group'},
                   5652:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5653:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5654:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5655:             $funclist = $forbodytag;
                   5656:         }
                   5657:     } else {
1.903     droeschl 5658: 
                   5659:         #    if ($env{'request.state'} eq 'construct') {
                   5660:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5661:         #    }
                   5662: 
1.1075.2.38  raeburn  5663:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5664:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5665: 
1.1075.2.38  raeburn  5666:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5667: 
1.916     droeschl 5668:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5669:             if ($dc_info) {
                   5670:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5671:             }
1.1075.2.38  raeburn  5672:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5673:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5674:             return $bodytag;
                   5675:         }
1.894     droeschl 5676: 
1.927     raeburn  5677:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5678:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5679:         }
1.916     droeschl 5680: 
1.1075.2.38  raeburn  5681:         $bodytag .= $right;
1.852     droeschl 5682: 
1.917     raeburn  5683:         if ($dc_info) {
                   5684:             $dc_info = &dc_courseid_toggle($dc_info);
                   5685:         }
                   5686:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5687: 
1.1075.2.61  raeburn  5688:         #if directed to not display the secondary menu, don't.
                   5689:         if ($args->{'no_secondary_menu'}) {
                   5690:             return $bodytag;
                   5691:         }
1.903     droeschl 5692:         #don't show menus for public users
1.954     raeburn  5693:         if (!$public){
1.1075.2.52  raeburn  5694:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5695:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5696:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5697:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5698:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5699:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5700:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5701:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5702:                                                             $args->{'group'},
1.1075.2.133  raeburn  5703:                                                             $args->{'hide_buttons',
                   5704:                                                             $hostname});
1.1075.2.15  raeburn  5705:             } else {
1.1075.2.21  raeburn  5706:                 my $forbodytag;
                   5707:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5708:                                                     $forcereg,$args->{'group'},
                   5709:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5710:                                                     $advtoolsref,'',$hostname,
                   5711:                                                     \$forbodytag);
1.1075.2.21  raeburn  5712:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5713:                     $bodytag .= $forbodytag;
                   5714:                 }
1.920     raeburn  5715:             }
1.903     droeschl 5716:         }else{
                   5717:             # this is to seperate menu from content when there's no secondary
                   5718:             # menu. Especially needed for public accessible ressources.
                   5719:             $bodytag .= '<hr style="clear:both" />';
                   5720:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5721:         }
1.903     droeschl 5722: 
1.235     raeburn  5723:         return $bodytag;
1.1075.2.12  raeburn  5724:     }
                   5725: 
                   5726: #
                   5727: # Top frame rendering, Remote is up
                   5728: #
                   5729: 
                   5730:     my $imgsrc = $img;
                   5731:     if ($img =~ /^\/adm/) {
                   5732:         $imgsrc = &lonhttpdurl($img);
                   5733:     }
                   5734:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5735: 
1.1075.2.60  raeburn  5736:     my $help=($no_inline_link?''
                   5737:               :&Apache::loncommon::top_nav_help('Help'));
                   5738: 
1.1075.2.12  raeburn  5739:     # Explicit link to get inline menu
                   5740:     my $menu= ($no_inline_link?''
                   5741:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5742: 
                   5743:     if ($dc_info) {
                   5744:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5745:     }
                   5746: 
1.1075.2.38  raeburn  5747:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5748:     unless ($public) {
                   5749:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5750:                                 undef,'LC_menubuttons_link');
                   5751:     }
                   5752: 
1.1075.2.12  raeburn  5753:     unless ($env{'form.inhibitmenu'}) {
                   5754:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5755:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5756:                        <li>$help</li>
1.1075.2.12  raeburn  5757:                        <li>$menu</li>
                   5758:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5759:     }
1.1075.2.13  raeburn  5760:     if ($env{'request.state'} eq 'construct') {
                   5761:         if (!$public){
                   5762:             if ($env{'request.state'} eq 'construct') {
                   5763:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5764:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5765:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5766:                             &Apache::lonmenu::innerregister($forcereg,
                   5767:                                                             $args->{'bread_crumbs'});
                   5768:             }
                   5769:         }
                   5770:     }
1.1075.2.21  raeburn  5771:     return $bodytag."\n".$funclist;
1.182     matthew  5772: }
                   5773: 
1.917     raeburn  5774: sub dc_courseid_toggle {
                   5775:     my ($dc_info) = @_;
1.980     raeburn  5776:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5777:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5778:            &mt('(More ...)').'</a></span>'.
                   5779:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5780: }
                   5781: 
1.330     albertel 5782: sub make_attr_string {
                   5783:     my ($register,$attr_ref) = @_;
                   5784: 
                   5785:     if ($attr_ref && !ref($attr_ref)) {
                   5786: 	die("addentries Must be a hash ref ".
                   5787: 	    join(':',caller(1))." ".
                   5788: 	    join(':',caller(0))." ");
                   5789:     }
                   5790: 
                   5791:     if ($register) {
1.339     albertel 5792: 	my ($on_load,$on_unload);
                   5793: 	foreach my $key (keys(%{$attr_ref})) {
                   5794: 	    if      (lc($key) eq 'onload') {
                   5795: 		$on_load.=$attr_ref->{$key}.';';
                   5796: 		delete($attr_ref->{$key});
                   5797: 
                   5798: 	    } elsif (lc($key) eq 'onunload') {
                   5799: 		$on_unload.=$attr_ref->{$key}.';';
                   5800: 		delete($attr_ref->{$key});
                   5801: 	    }
                   5802: 	}
1.1075.2.12  raeburn  5803:         if ($env{'environment.remote'} eq 'on') {
                   5804:             $attr_ref->{'onload'}  =
                   5805:                 &Apache::lonmenu::loadevents().  $on_load;
                   5806:             $attr_ref->{'onunload'}=
                   5807:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5808:         } else {  
                   5809: 	    $attr_ref->{'onload'}  = $on_load;
                   5810: 	    $attr_ref->{'onunload'}= $on_unload;
                   5811:         }
1.330     albertel 5812:     }
1.339     albertel 5813: 
1.330     albertel 5814:     my $attr_string;
1.1075.2.56  raeburn  5815:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5816: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5817:     }
                   5818:     return $attr_string;
                   5819: }
                   5820: 
                   5821: 
1.182     matthew  5822: ###############################################
1.251     albertel 5823: ###############################################
                   5824: 
                   5825: =pod
                   5826: 
                   5827: =item * &endbodytag()
                   5828: 
                   5829: Returns a uniform footer for LON-CAPA web pages.
                   5830: 
1.635     raeburn  5831: Inputs: 1 - optional reference to an args hash
                   5832: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5833: a 'Continue' link is not displayed if the page contains an
                   5834: internal redirect in the <head></head> section,
                   5835: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5836: 
                   5837: =cut
                   5838: 
                   5839: sub endbodytag {
1.635     raeburn  5840:     my ($args) = @_;
1.1075.2.6  raeburn  5841:     my $endbodytag;
                   5842:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5843:         $endbodytag='</body>';
                   5844:     }
1.315     albertel 5845:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5846:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5847: 	    $endbodytag=
                   5848: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5849: 	        &mt('Continue').'</a>'.
                   5850: 	        $endbodytag;
                   5851:         }
1.315     albertel 5852:     }
1.251     albertel 5853:     return $endbodytag;
                   5854: }
                   5855: 
1.352     albertel 5856: =pod
                   5857: 
                   5858: =item * &standard_css()
                   5859: 
                   5860: Returns a style sheet
                   5861: 
                   5862: Inputs: (all optional)
                   5863:             domain         -> force to color decorate a page for a specific
                   5864:                                domain
                   5865:             function       -> force usage of a specific rolish color scheme
                   5866:             bgcolor        -> override the default page bgcolor
                   5867: 
                   5868: =cut
                   5869: 
1.343     albertel 5870: sub standard_css {
1.345     albertel 5871:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5872:     $function  = &get_users_function() if (!$function);
                   5873:     my $img    = &designparm($function.'.img',   $domain);
                   5874:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5875:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5876:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5877: #second colour for later usage
1.345     albertel 5878:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5879:     my $pgbg_or_bgcolor =
                   5880: 	         $bgcolor ||
1.352     albertel 5881: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5882:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5883:     my $alink  = &designparm($function.'.alink', $domain);
                   5884:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5885:     my $link   = &designparm($function.'.link',  $domain);
                   5886: 
1.602     albertel 5887:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5888:     my $mono                 = 'monospace';
1.850     bisitz   5889:     my $data_table_head      = $sidebg;
                   5890:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5891:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5892:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5893:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5894:     my $mail_new             = '#FFBB77';
                   5895:     my $mail_new_hover       = '#DD9955';
                   5896:     my $mail_read            = '#BBBB77';
                   5897:     my $mail_read_hover      = '#999944';
                   5898:     my $mail_replied         = '#AAAA88';
                   5899:     my $mail_replied_hover   = '#888855';
                   5900:     my $mail_other           = '#99BBBB';
                   5901:     my $mail_other_hover     = '#669999';
1.391     albertel 5902:     my $table_header         = '#DDDDDD';
1.489     raeburn  5903:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5904:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5905:     my $button_hover         = '#BF2317';
1.392     albertel 5906: 
1.608     albertel 5907:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5908:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5909:                                              : '0 3px 0 4px';
1.448     albertel 5910: 
1.523     albertel 5911: 
1.343     albertel 5912:     return <<END;
1.947     droeschl 5913: 
                   5914: /* needed for iframe to allow 100% height in FF */
                   5915: body, html { 
                   5916:     margin: 0;
                   5917:     padding: 0 0.5%;
                   5918:     height: 99%; /* to avoid scrollbars */
                   5919: }
                   5920: 
1.795     www      5921: body {
1.911     bisitz   5922:   font-family: $sans;
                   5923:   line-height:130%;
                   5924:   font-size:0.83em;
                   5925:   color:$font;
1.795     www      5926: }
                   5927: 
1.959     onken    5928: a:focus,
                   5929: a:focus img {
1.795     www      5930:   color: red;
                   5931: }
1.698     harmsja  5932: 
1.911     bisitz   5933: form, .inline {
                   5934:   display: inline;
1.795     www      5935: }
1.721     harmsja  5936: 
1.795     www      5937: .LC_right {
1.911     bisitz   5938:   text-align:right;
1.795     www      5939: }
                   5940: 
                   5941: .LC_middle {
1.911     bisitz   5942:   vertical-align:middle;
1.795     www      5943: }
1.721     harmsja  5944: 
1.1075.2.38  raeburn  5945: .LC_floatleft {
                   5946:   float: left;
                   5947: }
                   5948: 
                   5949: .LC_floatright {
                   5950:   float: right;
                   5951: }
                   5952: 
1.911     bisitz   5953: .LC_400Box {
                   5954:   width:400px;
                   5955: }
1.721     harmsja  5956: 
1.947     droeschl 5957: .LC_iframecontainer {
                   5958:     width: 98%;
                   5959:     margin: 0;
                   5960:     position: fixed;
                   5961:     top: 8.5em;
                   5962:     bottom: 0;
                   5963: }
                   5964: 
                   5965: .LC_iframecontainer iframe{
                   5966:     border: none;
                   5967:     width: 100%;
                   5968:     height: 100%;
                   5969: }
                   5970: 
1.778     bisitz   5971: .LC_filename {
                   5972:   font-family: $mono;
                   5973:   white-space:pre;
1.921     bisitz   5974:   font-size: 120%;
1.778     bisitz   5975: }
                   5976: 
                   5977: .LC_fileicon {
                   5978:   border: none;
                   5979:   height: 1.3em;
                   5980:   vertical-align: text-bottom;
                   5981:   margin-right: 0.3em;
                   5982:   text-decoration:none;
                   5983: }
                   5984: 
1.1008    www      5985: .LC_setting {
                   5986:   text-decoration:underline;
                   5987: }
                   5988: 
1.350     albertel 5989: .LC_error {
                   5990:   color: red;
                   5991: }
1.795     www      5992: 
1.1075.2.15  raeburn  5993: .LC_warning {
                   5994:   color: darkorange;
                   5995: }
                   5996: 
1.457     albertel 5997: .LC_diff_removed {
1.733     bisitz   5998:   color: red;
1.394     albertel 5999: }
1.532     albertel 6000: 
                   6001: .LC_info,
1.457     albertel 6002: .LC_success,
                   6003: .LC_diff_added {
1.350     albertel 6004:   color: green;
                   6005: }
1.795     www      6006: 
1.802     bisitz   6007: div.LC_confirm_box {
                   6008:   background-color: #FAFAFA;
                   6009:   border: 1px solid $lg_border_color;
                   6010:   margin-right: 0;
                   6011:   padding: 5px;
                   6012: }
                   6013: 
                   6014: div.LC_confirm_box .LC_error img,
                   6015: div.LC_confirm_box .LC_success img {
                   6016:   vertical-align: middle;
                   6017: }
                   6018: 
1.1075.2.108  raeburn  6019: .LC_maxwidth {
                   6020:   max-width: 100%;
                   6021:   height: auto;
                   6022: }
                   6023: 
                   6024: .LC_textsize_mobile {
                   6025:   \@media only screen and (max-device-width: 480px) {
                   6026:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6027:   }
                   6028: }
                   6029: 
1.440     albertel 6030: .LC_icon {
1.771     droeschl 6031:   border: none;
1.790     droeschl 6032:   vertical-align: middle;
1.771     droeschl 6033: }
                   6034: 
1.543     albertel 6035: .LC_docs_spacer {
                   6036:   width: 25px;
                   6037:   height: 1px;
1.771     droeschl 6038:   border: none;
1.543     albertel 6039: }
1.346     albertel 6040: 
1.532     albertel 6041: .LC_internal_info {
1.735     bisitz   6042:   color: #999999;
1.532     albertel 6043: }
                   6044: 
1.794     www      6045: .LC_discussion {
1.1050    www      6046:   background: $data_table_dark;
1.911     bisitz   6047:   border: 1px solid black;
                   6048:   margin: 2px;
1.794     www      6049: }
                   6050: 
                   6051: .LC_disc_action_left {
1.1050    www      6052:   background: $sidebg;
1.911     bisitz   6053:   text-align: left;
1.1050    www      6054:   padding: 4px;
                   6055:   margin: 2px;
1.794     www      6056: }
                   6057: 
                   6058: .LC_disc_action_right {
1.1050    www      6059:   background: $sidebg;
1.911     bisitz   6060:   text-align: right;
1.1050    www      6061:   padding: 4px;
                   6062:   margin: 2px;
1.794     www      6063: }
                   6064: 
                   6065: .LC_disc_new_item {
1.911     bisitz   6066:   background: white;
                   6067:   border: 2px solid red;
1.1050    www      6068:   margin: 4px;
                   6069:   padding: 4px;
1.794     www      6070: }
                   6071: 
                   6072: .LC_disc_old_item {
1.911     bisitz   6073:   background: white;
1.1050    www      6074:   margin: 4px;
                   6075:   padding: 4px;
1.794     www      6076: }
                   6077: 
1.458     albertel 6078: table.LC_pastsubmission {
                   6079:   border: 1px solid black;
                   6080:   margin: 2px;
                   6081: }
                   6082: 
1.924     bisitz   6083: table#LC_menubuttons {
1.345     albertel 6084:   width: 100%;
                   6085:   background: $pgbg;
1.392     albertel 6086:   border: 2px;
1.402     albertel 6087:   border-collapse: separate;
1.803     bisitz   6088:   padding: 0;
1.345     albertel 6089: }
1.392     albertel 6090: 
1.801     tempelho 6091: table#LC_title_bar a {
                   6092:   color: $fontmenu;
                   6093: }
1.836     bisitz   6094: 
1.807     droeschl 6095: table#LC_title_bar {
1.819     tempelho 6096:   clear: both;
1.836     bisitz   6097:   display: none;
1.807     droeschl 6098: }
                   6099: 
1.795     www      6100: table#LC_title_bar,
1.933     droeschl 6101: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6102: table#LC_title_bar.LC_with_remote {
1.359     albertel 6103:   width: 100%;
1.392     albertel 6104:   border-color: $pgbg;
                   6105:   border-style: solid;
                   6106:   border-width: $border;
1.379     albertel 6107:   background: $pgbg;
1.801     tempelho 6108:   color: $fontmenu;
1.392     albertel 6109:   border-collapse: collapse;
1.803     bisitz   6110:   padding: 0;
1.819     tempelho 6111:   margin: 0;
1.359     albertel 6112: }
1.795     www      6113: 
1.933     droeschl 6114: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6115:     margin: 0;
                   6116:     padding: 0;
1.933     droeschl 6117:     position: relative;
                   6118:     list-style: none;
1.913     droeschl 6119: }
1.933     droeschl 6120: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6121:     display: inline;
                   6122: }
1.933     droeschl 6123: 
                   6124: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6125:     padding: 0;
1.933     droeschl 6126:     margin: 0;
                   6127:     float: left;
1.913     droeschl 6128: }
1.933     droeschl 6129: .LC_breadcrumb_tools_tools {
                   6130:     padding: 0;
                   6131:     margin: 0;
1.913     droeschl 6132:     float: right;
                   6133: }
                   6134: 
1.359     albertel 6135: table#LC_title_bar td {
                   6136:   background: $tabbg;
                   6137: }
1.795     www      6138: 
1.911     bisitz   6139: table#LC_menubuttons img {
1.803     bisitz   6140:   border: none;
1.346     albertel 6141: }
1.795     www      6142: 
1.842     droeschl 6143: .LC_breadcrumbs_component {
1.911     bisitz   6144:   float: right;
                   6145:   margin: 0 1em;
1.357     albertel 6146: }
1.842     droeschl 6147: .LC_breadcrumbs_component img {
1.911     bisitz   6148:   vertical-align: middle;
1.777     tempelho 6149: }
1.795     www      6150: 
1.1075.2.108  raeburn  6151: .LC_breadcrumbs_hoverable {
                   6152:   background: $sidebg;
                   6153: }
                   6154: 
1.383     albertel 6155: td.LC_table_cell_checkbox {
                   6156:   text-align: center;
                   6157: }
1.795     www      6158: 
                   6159: .LC_fontsize_small {
1.911     bisitz   6160:   font-size: 70%;
1.705     tempelho 6161: }
                   6162: 
1.844     bisitz   6163: #LC_breadcrumbs {
1.911     bisitz   6164:   clear:both;
                   6165:   background: $sidebg;
                   6166:   border-bottom: 1px solid $lg_border_color;
                   6167:   line-height: 2.5em;
1.933     droeschl 6168:   overflow: hidden;
1.911     bisitz   6169:   margin: 0;
                   6170:   padding: 0;
1.995     raeburn  6171:   text-align: left;
1.819     tempelho 6172: }
1.862     bisitz   6173: 
1.1075.2.16  raeburn  6174: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6175:   clear:both;
                   6176:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6177:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6178:   margin: 0 0 10px 0;
1.966     bisitz   6179:   padding: 3px;
1.995     raeburn  6180:   text-align: left;
1.822     bisitz   6181: }
                   6182: 
1.795     www      6183: .LC_fontsize_medium {
1.911     bisitz   6184:   font-size: 85%;
1.705     tempelho 6185: }
                   6186: 
1.795     www      6187: .LC_fontsize_large {
1.911     bisitz   6188:   font-size: 120%;
1.705     tempelho 6189: }
                   6190: 
1.346     albertel 6191: .LC_menubuttons_inline_text {
                   6192:   color: $font;
1.698     harmsja  6193:   font-size: 90%;
1.701     harmsja  6194:   padding-left:3px;
1.346     albertel 6195: }
                   6196: 
1.934     droeschl 6197: .LC_menubuttons_inline_text img{
                   6198:   vertical-align: middle;
                   6199: }
                   6200: 
1.1051    www      6201: li.LC_menubuttons_inline_text img {
1.951     onken    6202:   cursor:pointer;
1.1002    droeschl 6203:   text-decoration: none;
1.951     onken    6204: }
                   6205: 
1.526     www      6206: .LC_menubuttons_link {
                   6207:   text-decoration: none;
                   6208: }
1.795     www      6209: 
1.522     albertel 6210: .LC_menubuttons_category {
1.521     www      6211:   color: $font;
1.526     www      6212:   background: $pgbg;
1.521     www      6213:   font-size: larger;
                   6214:   font-weight: bold;
                   6215: }
                   6216: 
1.346     albertel 6217: td.LC_menubuttons_text {
1.911     bisitz   6218:   color: $font;
1.346     albertel 6219: }
1.706     harmsja  6220: 
1.346     albertel 6221: .LC_current_location {
                   6222:   background: $tabbg;
                   6223: }
1.795     www      6224: 
1.1075.2.134  raeburn  6225: td.LC_zero_height {
                   6226:   line-height: 0;
                   6227:   cellpadding: 0;
                   6228: }
                   6229: 
1.938     bisitz   6230: table.LC_data_table {
1.347     albertel 6231:   border: 1px solid #000000;
1.402     albertel 6232:   border-collapse: separate;
1.426     albertel 6233:   border-spacing: 1px;
1.610     albertel 6234:   background: $pgbg;
1.347     albertel 6235: }
1.795     www      6236: 
1.422     albertel 6237: .LC_data_table_dense {
                   6238:   font-size: small;
                   6239: }
1.795     www      6240: 
1.507     raeburn  6241: table.LC_nested_outer {
                   6242:   border: 1px solid #000000;
1.589     raeburn  6243:   border-collapse: collapse;
1.803     bisitz   6244:   border-spacing: 0;
1.507     raeburn  6245:   width: 100%;
                   6246: }
1.795     www      6247: 
1.879     raeburn  6248: table.LC_innerpickbox,
1.507     raeburn  6249: table.LC_nested {
1.803     bisitz   6250:   border: none;
1.589     raeburn  6251:   border-collapse: collapse;
1.803     bisitz   6252:   border-spacing: 0;
1.507     raeburn  6253:   width: 100%;
                   6254: }
1.795     www      6255: 
1.911     bisitz   6256: table.LC_data_table tr th,
                   6257: table.LC_calendar tr th,
1.879     raeburn  6258: table.LC_prior_tries tr th,
                   6259: table.LC_innerpickbox tr th {
1.349     albertel 6260:   font-weight: bold;
                   6261:   background-color: $data_table_head;
1.801     tempelho 6262:   color:$fontmenu;
1.701     harmsja  6263:   font-size:90%;
1.347     albertel 6264: }
1.795     www      6265: 
1.879     raeburn  6266: table.LC_innerpickbox tr th,
                   6267: table.LC_innerpickbox tr td {
                   6268:   vertical-align: top;
                   6269: }
                   6270: 
1.711     raeburn  6271: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6272:   background-color: #CCCCCC;
1.711     raeburn  6273:   font-weight: bold;
                   6274:   text-align: left;
                   6275: }
1.795     www      6276: 
1.912     bisitz   6277: table.LC_data_table tr.LC_odd_row > td {
                   6278:   background-color: $data_table_light;
                   6279:   padding: 2px;
                   6280:   vertical-align: top;
                   6281: }
                   6282: 
1.809     bisitz   6283: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6284:   background-color: $data_table_light;
1.912     bisitz   6285:   vertical-align: top;
                   6286: }
                   6287: 
                   6288: table.LC_data_table tr.LC_even_row > td {
                   6289:   background-color: $data_table_dark;
1.425     albertel 6290:   padding: 2px;
1.900     bisitz   6291:   vertical-align: top;
1.347     albertel 6292: }
1.795     www      6293: 
1.809     bisitz   6294: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6295:   background-color: $data_table_dark;
1.900     bisitz   6296:   vertical-align: top;
1.347     albertel 6297: }
1.795     www      6298: 
1.425     albertel 6299: table.LC_data_table tr.LC_data_table_highlight td {
                   6300:   background-color: $data_table_darker;
                   6301: }
1.795     www      6302: 
1.639     raeburn  6303: table.LC_data_table tr td.LC_leftcol_header {
                   6304:   background-color: $data_table_head;
                   6305:   font-weight: bold;
                   6306: }
1.795     www      6307: 
1.451     albertel 6308: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6309: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6310:   font-weight: bold;
                   6311:   font-style: italic;
                   6312:   text-align: center;
                   6313:   padding: 8px;
1.347     albertel 6314: }
1.795     www      6315: 
1.1075.2.30  raeburn  6316: table.LC_data_table tr.LC_empty_row td,
                   6317: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6318:   background-color: $sidebg;
                   6319: }
                   6320: 
                   6321: table.LC_nested tr.LC_empty_row td {
                   6322:   background-color: #FFFFFF;
                   6323: }
                   6324: 
1.890     droeschl 6325: table.LC_caption {
                   6326: }
                   6327: 
1.507     raeburn  6328: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6329:   padding: 4ex
                   6330: }
1.795     www      6331: 
1.507     raeburn  6332: table.LC_nested_outer tr th {
                   6333:   font-weight: bold;
1.801     tempelho 6334:   color:$fontmenu;
1.507     raeburn  6335:   background-color: $data_table_head;
1.701     harmsja  6336:   font-size: small;
1.507     raeburn  6337:   border-bottom: 1px solid #000000;
                   6338: }
1.795     www      6339: 
1.507     raeburn  6340: table.LC_nested_outer tr td.LC_subheader {
                   6341:   background-color: $data_table_head;
                   6342:   font-weight: bold;
                   6343:   font-size: small;
                   6344:   border-bottom: 1px solid #000000;
                   6345:   text-align: right;
1.451     albertel 6346: }
1.795     www      6347: 
1.507     raeburn  6348: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6349:   background-color: #CCCCCC;
1.451     albertel 6350:   font-weight: bold;
                   6351:   font-size: small;
1.507     raeburn  6352:   text-align: center;
                   6353: }
1.795     www      6354: 
1.589     raeburn  6355: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6356: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6357:   text-align: left;
1.451     albertel 6358: }
1.795     www      6359: 
1.507     raeburn  6360: table.LC_nested td {
1.735     bisitz   6361:   background-color: #FFFFFF;
1.451     albertel 6362:   font-size: small;
1.507     raeburn  6363: }
1.795     www      6364: 
1.507     raeburn  6365: table.LC_nested_outer tr th.LC_right_item,
                   6366: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6367: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6368: table.LC_nested tr td.LC_right_item {
1.451     albertel 6369:   text-align: right;
                   6370: }
                   6371: 
1.507     raeburn  6372: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6373:   background-color: #EEEEEE;
1.451     albertel 6374: }
                   6375: 
1.473     raeburn  6376: table.LC_createuser {
                   6377: }
                   6378: 
                   6379: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6380:   font-size: small;
1.473     raeburn  6381: }
                   6382: 
                   6383: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6384:   background-color: #CCCCCC;
1.473     raeburn  6385:   font-weight: bold;
                   6386:   text-align: center;
                   6387: }
                   6388: 
1.349     albertel 6389: table.LC_calendar {
                   6390:   border: 1px solid #000000;
                   6391:   border-collapse: collapse;
1.917     raeburn  6392:   width: 98%;
1.349     albertel 6393: }
1.795     www      6394: 
1.349     albertel 6395: table.LC_calendar_pickdate {
                   6396:   font-size: xx-small;
                   6397: }
1.795     www      6398: 
1.349     albertel 6399: table.LC_calendar tr td {
                   6400:   border: 1px solid #000000;
                   6401:   vertical-align: top;
1.917     raeburn  6402:   width: 14%;
1.349     albertel 6403: }
1.795     www      6404: 
1.349     albertel 6405: table.LC_calendar tr td.LC_calendar_day_empty {
                   6406:   background-color: $data_table_dark;
                   6407: }
1.795     www      6408: 
1.779     bisitz   6409: table.LC_calendar tr td.LC_calendar_day_current {
                   6410:   background-color: $data_table_highlight;
1.777     tempelho 6411: }
1.795     www      6412: 
1.938     bisitz   6413: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6414:   background-color: $mail_new;
                   6415: }
1.795     www      6416: 
1.938     bisitz   6417: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6418:   background-color: $mail_new_hover;
                   6419: }
1.795     www      6420: 
1.938     bisitz   6421: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6422:   background-color: $mail_read;
                   6423: }
1.795     www      6424: 
1.938     bisitz   6425: /*
                   6426: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6427:   background-color: $mail_read_hover;
                   6428: }
1.938     bisitz   6429: */
1.795     www      6430: 
1.938     bisitz   6431: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6432:   background-color: $mail_replied;
                   6433: }
1.795     www      6434: 
1.938     bisitz   6435: /*
                   6436: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6437:   background-color: $mail_replied_hover;
                   6438: }
1.938     bisitz   6439: */
1.795     www      6440: 
1.938     bisitz   6441: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6442:   background-color: $mail_other;
                   6443: }
1.795     www      6444: 
1.938     bisitz   6445: /*
                   6446: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6447:   background-color: $mail_other_hover;
                   6448: }
1.938     bisitz   6449: */
1.494     raeburn  6450: 
1.777     tempelho 6451: table.LC_data_table tr > td.LC_browser_file,
                   6452: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6453:   background: #AAEE77;
1.389     albertel 6454: }
1.795     www      6455: 
1.777     tempelho 6456: table.LC_data_table tr > td.LC_browser_file_locked,
                   6457: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6458:   background: #FFAA99;
1.387     albertel 6459: }
1.795     www      6460: 
1.777     tempelho 6461: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6462:   background: #888888;
1.779     bisitz   6463: }
1.795     www      6464: 
1.777     tempelho 6465: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6466: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6467:   background: #F8F866;
1.777     tempelho 6468: }
1.795     www      6469: 
1.696     bisitz   6470: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6471:   background: #E0E8FF;
1.387     albertel 6472: }
1.696     bisitz   6473: 
1.707     bisitz   6474: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6475:   /* background: #77FF77; */
1.707     bisitz   6476: }
1.795     www      6477: 
1.707     bisitz   6478: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6479:   border-right: 8px solid #FFFF77;
1.707     bisitz   6480: }
1.795     www      6481: 
1.707     bisitz   6482: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6483:   border-right: 8px solid #FFAA77;
1.707     bisitz   6484: }
1.795     www      6485: 
1.707     bisitz   6486: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6487:   border-right: 8px solid #FF7777;
1.707     bisitz   6488: }
1.795     www      6489: 
1.707     bisitz   6490: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6491:   border-right: 8px solid #AAFF77;
1.707     bisitz   6492: }
1.795     www      6493: 
1.707     bisitz   6494: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6495:   border-right: 8px solid #11CC55;
1.707     bisitz   6496: }
                   6497: 
1.388     albertel 6498: span.LC_current_location {
1.701     harmsja  6499:   font-size:larger;
1.388     albertel 6500:   background: $pgbg;
                   6501: }
1.387     albertel 6502: 
1.1029    www      6503: span.LC_current_nav_location {
                   6504:   font-weight:bold;
                   6505:   background: $sidebg;
                   6506: }
                   6507: 
1.395     albertel 6508: span.LC_parm_menu_item {
                   6509:   font-size: larger;
                   6510: }
1.795     www      6511: 
1.395     albertel 6512: span.LC_parm_scope_all {
                   6513:   color: red;
                   6514: }
1.795     www      6515: 
1.395     albertel 6516: span.LC_parm_scope_folder {
                   6517:   color: green;
                   6518: }
1.795     www      6519: 
1.395     albertel 6520: span.LC_parm_scope_resource {
                   6521:   color: orange;
                   6522: }
1.795     www      6523: 
1.395     albertel 6524: span.LC_parm_part {
                   6525:   color: blue;
                   6526: }
1.795     www      6527: 
1.911     bisitz   6528: span.LC_parm_folder,
                   6529: span.LC_parm_symb {
1.395     albertel 6530:   font-size: x-small;
                   6531:   font-family: $mono;
                   6532:   color: #AAAAAA;
                   6533: }
                   6534: 
1.977     bisitz   6535: ul.LC_parm_parmlist li {
                   6536:   display: inline-block;
                   6537:   padding: 0.3em 0.8em;
                   6538:   vertical-align: top;
                   6539:   width: 150px;
                   6540:   border-top:1px solid $lg_border_color;
                   6541: }
                   6542: 
1.795     www      6543: td.LC_parm_overview_level_menu,
                   6544: td.LC_parm_overview_map_menu,
                   6545: td.LC_parm_overview_parm_selectors,
                   6546: td.LC_parm_overview_restrictions  {
1.396     albertel 6547:   border: 1px solid black;
                   6548:   border-collapse: collapse;
                   6549: }
1.795     www      6550: 
1.396     albertel 6551: table.LC_parm_overview_restrictions td {
                   6552:   border-width: 1px 4px 1px 4px;
                   6553:   border-style: solid;
                   6554:   border-color: $pgbg;
                   6555:   text-align: center;
                   6556: }
1.795     www      6557: 
1.396     albertel 6558: table.LC_parm_overview_restrictions th {
                   6559:   background: $tabbg;
                   6560:   border-width: 1px 4px 1px 4px;
                   6561:   border-style: solid;
                   6562:   border-color: $pgbg;
                   6563: }
1.795     www      6564: 
1.398     albertel 6565: table#LC_helpmenu {
1.803     bisitz   6566:   border: none;
1.398     albertel 6567:   height: 55px;
1.803     bisitz   6568:   border-spacing: 0;
1.398     albertel 6569: }
                   6570: 
                   6571: table#LC_helpmenu fieldset legend {
                   6572:   font-size: larger;
                   6573: }
1.795     www      6574: 
1.397     albertel 6575: table#LC_helpmenu_links {
                   6576:   width: 100%;
                   6577:   border: 1px solid black;
                   6578:   background: $pgbg;
1.803     bisitz   6579:   padding: 0;
1.397     albertel 6580:   border-spacing: 1px;
                   6581: }
1.795     www      6582: 
1.397     albertel 6583: table#LC_helpmenu_links tr td {
                   6584:   padding: 1px;
                   6585:   background: $tabbg;
1.399     albertel 6586:   text-align: center;
                   6587:   font-weight: bold;
1.397     albertel 6588: }
1.396     albertel 6589: 
1.795     www      6590: table#LC_helpmenu_links a:link,
                   6591: table#LC_helpmenu_links a:visited,
1.397     albertel 6592: table#LC_helpmenu_links a:active {
                   6593:   text-decoration: none;
                   6594:   color: $font;
                   6595: }
1.795     www      6596: 
1.397     albertel 6597: table#LC_helpmenu_links a:hover {
                   6598:   text-decoration: underline;
                   6599:   color: $vlink;
                   6600: }
1.396     albertel 6601: 
1.417     albertel 6602: .LC_chrt_popup_exists {
                   6603:   border: 1px solid #339933;
                   6604:   margin: -1px;
                   6605: }
1.795     www      6606: 
1.417     albertel 6607: .LC_chrt_popup_up {
                   6608:   border: 1px solid yellow;
                   6609:   margin: -1px;
                   6610: }
1.795     www      6611: 
1.417     albertel 6612: .LC_chrt_popup {
                   6613:   border: 1px solid #8888FF;
                   6614:   background: #CCCCFF;
                   6615: }
1.795     www      6616: 
1.421     albertel 6617: table.LC_pick_box {
                   6618:   border-collapse: separate;
                   6619:   background: white;
                   6620:   border: 1px solid black;
                   6621:   border-spacing: 1px;
                   6622: }
1.795     www      6623: 
1.421     albertel 6624: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6625:   background: $sidebg;
1.421     albertel 6626:   font-weight: bold;
1.900     bisitz   6627:   text-align: left;
1.740     bisitz   6628:   vertical-align: top;
1.421     albertel 6629:   width: 184px;
                   6630:   padding: 8px;
                   6631: }
1.795     www      6632: 
1.579     raeburn  6633: table.LC_pick_box td.LC_pick_box_value {
                   6634:   text-align: left;
                   6635:   padding: 8px;
                   6636: }
1.795     www      6637: 
1.579     raeburn  6638: table.LC_pick_box td.LC_pick_box_select {
                   6639:   text-align: left;
                   6640:   padding: 8px;
                   6641: }
1.795     www      6642: 
1.424     albertel 6643: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6644:   padding: 0;
1.421     albertel 6645:   height: 1px;
                   6646:   background: black;
                   6647: }
1.795     www      6648: 
1.421     albertel 6649: table.LC_pick_box td.LC_pick_box_submit {
                   6650:   text-align: right;
                   6651: }
1.795     www      6652: 
1.579     raeburn  6653: table.LC_pick_box td.LC_evenrow_value {
                   6654:   text-align: left;
                   6655:   padding: 8px;
                   6656:   background-color: $data_table_light;
                   6657: }
1.795     www      6658: 
1.579     raeburn  6659: table.LC_pick_box td.LC_oddrow_value {
                   6660:   text-align: left;
                   6661:   padding: 8px;
                   6662:   background-color: $data_table_light;
                   6663: }
1.795     www      6664: 
1.579     raeburn  6665: span.LC_helpform_receipt_cat {
                   6666:   font-weight: bold;
                   6667: }
1.795     www      6668: 
1.424     albertel 6669: table.LC_group_priv_box {
                   6670:   background: white;
                   6671:   border: 1px solid black;
                   6672:   border-spacing: 1px;
                   6673: }
1.795     www      6674: 
1.424     albertel 6675: table.LC_group_priv_box td.LC_pick_box_title {
                   6676:   background: $tabbg;
                   6677:   font-weight: bold;
                   6678:   text-align: right;
                   6679:   width: 184px;
                   6680: }
1.795     www      6681: 
1.424     albertel 6682: table.LC_group_priv_box td.LC_groups_fixed {
                   6683:   background: $data_table_light;
                   6684:   text-align: center;
                   6685: }
1.795     www      6686: 
1.424     albertel 6687: table.LC_group_priv_box td.LC_groups_optional {
                   6688:   background: $data_table_dark;
                   6689:   text-align: center;
                   6690: }
1.795     www      6691: 
1.424     albertel 6692: table.LC_group_priv_box td.LC_groups_functionality {
                   6693:   background: $data_table_darker;
                   6694:   text-align: center;
                   6695:   font-weight: bold;
                   6696: }
1.795     www      6697: 
1.424     albertel 6698: table.LC_group_priv td {
                   6699:   text-align: left;
1.803     bisitz   6700:   padding: 0;
1.424     albertel 6701: }
                   6702: 
                   6703: .LC_navbuttons {
                   6704:   margin: 2ex 0ex 2ex 0ex;
                   6705: }
1.795     www      6706: 
1.423     albertel 6707: .LC_topic_bar {
                   6708:   font-weight: bold;
                   6709:   background: $tabbg;
1.918     wenzelju 6710:   margin: 1em 0em 1em 2em;
1.805     bisitz   6711:   padding: 3px;
1.918     wenzelju 6712:   font-size: 1.2em;
1.423     albertel 6713: }
1.795     www      6714: 
1.423     albertel 6715: .LC_topic_bar span {
1.918     wenzelju 6716:   left: 0.5em;
                   6717:   position: absolute;
1.423     albertel 6718:   vertical-align: middle;
1.918     wenzelju 6719:   font-size: 1.2em;
1.423     albertel 6720: }
1.795     www      6721: 
1.423     albertel 6722: table.LC_course_group_status {
                   6723:   margin: 20px;
                   6724: }
1.795     www      6725: 
1.423     albertel 6726: table.LC_status_selector td {
                   6727:   vertical-align: top;
                   6728:   text-align: center;
1.424     albertel 6729:   padding: 4px;
                   6730: }
1.795     www      6731: 
1.599     albertel 6732: div.LC_feedback_link {
1.616     albertel 6733:   clear: both;
1.829     kalberla 6734:   background: $sidebg;
1.779     bisitz   6735:   width: 100%;
1.829     kalberla 6736:   padding-bottom: 10px;
                   6737:   border: 1px $tabbg solid;
1.833     kalberla 6738:   height: 22px;
                   6739:   line-height: 22px;
                   6740:   padding-top: 5px;
                   6741: }
                   6742: 
                   6743: div.LC_feedback_link img {
                   6744:   height: 22px;
1.867     kalberla 6745:   vertical-align:middle;
1.829     kalberla 6746: }
                   6747: 
1.911     bisitz   6748: div.LC_feedback_link a {
1.829     kalberla 6749:   text-decoration: none;
1.489     raeburn  6750: }
1.795     www      6751: 
1.867     kalberla 6752: div.LC_comblock {
1.911     bisitz   6753:   display:inline;
1.867     kalberla 6754:   color:$font;
                   6755:   font-size:90%;
                   6756: }
                   6757: 
                   6758: div.LC_feedback_link div.LC_comblock {
                   6759:   padding-left:5px;
                   6760: }
                   6761: 
                   6762: div.LC_feedback_link div.LC_comblock a {
                   6763:   color:$font;
                   6764: }
                   6765: 
1.489     raeburn  6766: span.LC_feedback_link {
1.858     bisitz   6767:   /* background: $feedback_link_bg; */
1.599     albertel 6768:   font-size: larger;
                   6769: }
1.795     www      6770: 
1.599     albertel 6771: span.LC_message_link {
1.858     bisitz   6772:   /* background: $feedback_link_bg; */
1.599     albertel 6773:   font-size: larger;
                   6774:   position: absolute;
                   6775:   right: 1em;
1.489     raeburn  6776: }
1.421     albertel 6777: 
1.515     albertel 6778: table.LC_prior_tries {
1.524     albertel 6779:   border: 1px solid #000000;
                   6780:   border-collapse: separate;
                   6781:   border-spacing: 1px;
1.515     albertel 6782: }
1.523     albertel 6783: 
1.515     albertel 6784: table.LC_prior_tries td {
1.524     albertel 6785:   padding: 2px;
1.515     albertel 6786: }
1.523     albertel 6787: 
                   6788: .LC_answer_correct {
1.795     www      6789:   background: lightgreen;
                   6790:   color: darkgreen;
                   6791:   padding: 6px;
1.523     albertel 6792: }
1.795     www      6793: 
1.523     albertel 6794: .LC_answer_charged_try {
1.797     www      6795:   background: #FFAAAA;
1.795     www      6796:   color: darkred;
                   6797:   padding: 6px;
1.523     albertel 6798: }
1.795     www      6799: 
1.779     bisitz   6800: .LC_answer_not_charged_try,
1.523     albertel 6801: .LC_answer_no_grade,
                   6802: .LC_answer_late {
1.795     www      6803:   background: lightyellow;
1.523     albertel 6804:   color: black;
1.795     www      6805:   padding: 6px;
1.523     albertel 6806: }
1.795     www      6807: 
1.523     albertel 6808: .LC_answer_previous {
1.795     www      6809:   background: lightblue;
                   6810:   color: darkblue;
                   6811:   padding: 6px;
1.523     albertel 6812: }
1.795     www      6813: 
1.779     bisitz   6814: .LC_answer_no_message {
1.777     tempelho 6815:   background: #FFFFFF;
                   6816:   color: black;
1.795     www      6817:   padding: 6px;
1.779     bisitz   6818: }
1.795     www      6819: 
1.1075.2.140  raeburn  6820: .LC_answer_unknown,
                   6821: .LC_answer_warning {
1.779     bisitz   6822:   background: orange;
                   6823:   color: black;
1.795     www      6824:   padding: 6px;
1.777     tempelho 6825: }
1.795     www      6826: 
1.529     albertel 6827: span.LC_prior_numerical,
                   6828: span.LC_prior_string,
                   6829: span.LC_prior_custom,
                   6830: span.LC_prior_reaction,
                   6831: span.LC_prior_math {
1.925     bisitz   6832:   font-family: $mono;
1.523     albertel 6833:   white-space: pre;
                   6834: }
                   6835: 
1.525     albertel 6836: span.LC_prior_string {
1.925     bisitz   6837:   font-family: $mono;
1.525     albertel 6838:   white-space: pre;
                   6839: }
                   6840: 
1.523     albertel 6841: table.LC_prior_option {
                   6842:   width: 100%;
                   6843:   border-collapse: collapse;
                   6844: }
1.795     www      6845: 
1.911     bisitz   6846: table.LC_prior_rank,
1.795     www      6847: table.LC_prior_match {
1.528     albertel 6848:   border-collapse: collapse;
                   6849: }
1.795     www      6850: 
1.528     albertel 6851: table.LC_prior_option tr td,
                   6852: table.LC_prior_rank tr td,
                   6853: table.LC_prior_match tr td {
1.524     albertel 6854:   border: 1px solid #000000;
1.515     albertel 6855: }
                   6856: 
1.855     bisitz   6857: .LC_nobreak {
1.544     albertel 6858:   white-space: nowrap;
1.519     raeburn  6859: }
                   6860: 
1.576     raeburn  6861: span.LC_cusr_emph {
                   6862:   font-style: italic;
                   6863: }
                   6864: 
1.633     raeburn  6865: span.LC_cusr_subheading {
                   6866:   font-weight: normal;
                   6867:   font-size: 85%;
                   6868: }
                   6869: 
1.861     bisitz   6870: div.LC_docs_entry_move {
1.859     bisitz   6871:   border: 1px solid #BBBBBB;
1.545     albertel 6872:   background: #DDDDDD;
1.861     bisitz   6873:   width: 22px;
1.859     bisitz   6874:   padding: 1px;
                   6875:   margin: 0;
1.545     albertel 6876: }
                   6877: 
1.861     bisitz   6878: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6879: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6880:   font-size: x-small;
                   6881: }
1.795     www      6882: 
1.861     bisitz   6883: .LC_docs_entry_parameter {
                   6884:   white-space: nowrap;
                   6885: }
                   6886: 
1.544     albertel 6887: .LC_docs_copy {
1.545     albertel 6888:   color: #000099;
1.544     albertel 6889: }
1.795     www      6890: 
1.544     albertel 6891: .LC_docs_cut {
1.545     albertel 6892:   color: #550044;
1.544     albertel 6893: }
1.795     www      6894: 
1.544     albertel 6895: .LC_docs_rename {
1.545     albertel 6896:   color: #009900;
1.544     albertel 6897: }
1.795     www      6898: 
1.544     albertel 6899: .LC_docs_remove {
1.545     albertel 6900:   color: #990000;
                   6901: }
                   6902: 
1.1075.2.134  raeburn  6903: .LC_domprefs_email,
1.547     albertel 6904: .LC_docs_reinit_warn,
                   6905: .LC_docs_ext_edit {
                   6906:   font-size: x-small;
                   6907: }
                   6908: 
1.545     albertel 6909: table.LC_docs_adddocs td,
                   6910: table.LC_docs_adddocs th {
                   6911:   border: 1px solid #BBBBBB;
                   6912:   padding: 4px;
                   6913:   background: #DDDDDD;
1.543     albertel 6914: }
                   6915: 
1.584     albertel 6916: table.LC_sty_begin {
                   6917:   background: #BBFFBB;
                   6918: }
1.795     www      6919: 
1.584     albertel 6920: table.LC_sty_end {
                   6921:   background: #FFBBBB;
                   6922: }
                   6923: 
1.589     raeburn  6924: table.LC_double_column {
1.803     bisitz   6925:   border-width: 0;
1.589     raeburn  6926:   border-collapse: collapse;
                   6927:   width: 100%;
                   6928:   padding: 2px;
                   6929: }
                   6930: 
                   6931: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6932:   top: 2px;
1.589     raeburn  6933:   left: 2px;
                   6934:   width: 47%;
                   6935:   vertical-align: top;
                   6936: }
                   6937: 
                   6938: table.LC_double_column tr td.LC_right_col {
                   6939:   top: 2px;
1.779     bisitz   6940:   right: 2px;
1.589     raeburn  6941:   width: 47%;
                   6942:   vertical-align: top;
                   6943: }
                   6944: 
1.591     raeburn  6945: div.LC_left_float {
                   6946:   float: left;
                   6947:   padding-right: 5%;
1.597     albertel 6948:   padding-bottom: 4px;
1.591     raeburn  6949: }
                   6950: 
                   6951: div.LC_clear_float_header {
1.597     albertel 6952:   padding-bottom: 2px;
1.591     raeburn  6953: }
                   6954: 
                   6955: div.LC_clear_float_footer {
1.597     albertel 6956:   padding-top: 10px;
1.591     raeburn  6957:   clear: both;
                   6958: }
                   6959: 
1.597     albertel 6960: div.LC_grade_show_user {
1.941     bisitz   6961: /*  border-left: 5px solid $sidebg; */
                   6962:   border-top: 5px solid #000000;
                   6963:   margin: 50px 0 0 0;
1.936     bisitz   6964:   padding: 15px 0 5px 10px;
1.597     albertel 6965: }
1.795     www      6966: 
1.936     bisitz   6967: div.LC_grade_show_user_odd_row {
1.941     bisitz   6968: /*  border-left: 5px solid #000000; */
                   6969: }
                   6970: 
                   6971: div.LC_grade_show_user div.LC_Box {
                   6972:   margin-right: 50px;
1.597     albertel 6973: }
                   6974: 
                   6975: div.LC_grade_submissions,
                   6976: div.LC_grade_message_center,
1.936     bisitz   6977: div.LC_grade_info_links {
1.597     albertel 6978:   margin: 5px;
                   6979:   width: 99%;
                   6980:   background: #FFFFFF;
                   6981: }
1.795     www      6982: 
1.597     albertel 6983: div.LC_grade_submissions_header,
1.936     bisitz   6984: div.LC_grade_message_center_header {
1.705     tempelho 6985:   font-weight: bold;
                   6986:   font-size: large;
1.597     albertel 6987: }
1.795     www      6988: 
1.597     albertel 6989: div.LC_grade_submissions_body,
1.936     bisitz   6990: div.LC_grade_message_center_body {
1.597     albertel 6991:   border: 1px solid black;
                   6992:   width: 99%;
                   6993:   background: #FFFFFF;
                   6994: }
1.795     www      6995: 
1.613     albertel 6996: table.LC_scantron_action {
                   6997:   width: 100%;
                   6998: }
1.795     www      6999: 
1.613     albertel 7000: table.LC_scantron_action tr th {
1.698     harmsja  7001:   font-weight:bold;
                   7002:   font-style:normal;
1.613     albertel 7003: }
1.795     www      7004: 
1.779     bisitz   7005: .LC_edit_problem_header,
1.614     albertel 7006: div.LC_edit_problem_footer {
1.705     tempelho 7007:   font-weight: normal;
                   7008:   font-size:  medium;
1.602     albertel 7009:   margin: 2px;
1.1060    bisitz   7010:   background-color: $sidebg;
1.600     albertel 7011: }
1.795     www      7012: 
1.600     albertel 7013: div.LC_edit_problem_header,
1.602     albertel 7014: div.LC_edit_problem_header div,
1.614     albertel 7015: div.LC_edit_problem_footer,
                   7016: div.LC_edit_problem_footer div,
1.602     albertel 7017: div.LC_edit_problem_editxml_header,
                   7018: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7019:   z-index: 100;
1.600     albertel 7020: }
1.795     www      7021: 
1.600     albertel 7022: div.LC_edit_problem_header_title {
1.705     tempelho 7023:   font-weight: bold;
                   7024:   font-size: larger;
1.602     albertel 7025:   background: $tabbg;
                   7026:   padding: 3px;
1.1060    bisitz   7027:   margin: 0 0 5px 0;
1.602     albertel 7028: }
1.795     www      7029: 
1.602     albertel 7030: table.LC_edit_problem_header_title {
                   7031:   width: 100%;
1.600     albertel 7032:   background: $tabbg;
1.602     albertel 7033: }
                   7034: 
1.1075.2.112  raeburn  7035: div.LC_edit_actionbar {
                   7036:     background-color: $sidebg;
                   7037:     margin: 0;
                   7038:     padding: 0;
                   7039:     line-height: 200%;
1.602     albertel 7040: }
1.795     www      7041: 
1.1075.2.112  raeburn  7042: div.LC_edit_actionbar div{
                   7043:     padding: 0;
                   7044:     margin: 0;
                   7045:     display: inline-block;
1.600     albertel 7046: }
1.795     www      7047: 
1.1075.2.34  raeburn  7048: .LC_edit_opt {
                   7049:   padding-left: 1em;
                   7050:   white-space: nowrap;
                   7051: }
                   7052: 
1.1075.2.57  raeburn  7053: .LC_edit_problem_latexhelper{
                   7054:     text-align: right;
                   7055: }
                   7056: 
                   7057: #LC_edit_problem_colorful div{
                   7058:     margin-left: 40px;
                   7059: }
                   7060: 
1.1075.2.112  raeburn  7061: #LC_edit_problem_codemirror div{
                   7062:     margin-left: 0px;
                   7063: }
                   7064: 
1.911     bisitz   7065: img.stift {
1.803     bisitz   7066:   border-width: 0;
                   7067:   vertical-align: middle;
1.677     riegler  7068: }
1.680     riegler  7069: 
1.923     bisitz   7070: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7071:   vertical-align: top;
1.777     tempelho 7072: }
1.795     www      7073: 
1.716     raeburn  7074: div.LC_createcourse {
1.911     bisitz   7075:   margin: 10px 10px 10px 10px;
1.716     raeburn  7076: }
                   7077: 
1.917     raeburn  7078: .LC_dccid {
1.1075.2.38  raeburn  7079:   float: right;
1.917     raeburn  7080:   margin: 0.2em 0 0 0;
                   7081:   padding: 0;
                   7082:   font-size: 90%;
                   7083:   display:none;
                   7084: }
                   7085: 
1.897     wenzelju 7086: ol.LC_primary_menu a:hover,
1.721     harmsja  7087: ol#LC_MenuBreadcrumbs a:hover,
                   7088: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7089: ul#LC_secondary_menu a:hover,
1.721     harmsja  7090: .LC_FormSectionClearButton input:hover
1.795     www      7091: ul.LC_TabContent   li:hover a {
1.952     onken    7092:   color:$button_hover;
1.911     bisitz   7093:   text-decoration:none;
1.693     droeschl 7094: }
                   7095: 
1.779     bisitz   7096: h1 {
1.911     bisitz   7097:   padding: 0;
                   7098:   line-height:130%;
1.693     droeschl 7099: }
1.698     harmsja  7100: 
1.911     bisitz   7101: h2,
                   7102: h3,
                   7103: h4,
                   7104: h5,
                   7105: h6 {
                   7106:   margin: 5px 0 5px 0;
                   7107:   padding: 0;
                   7108:   line-height:130%;
1.693     droeschl 7109: }
1.795     www      7110: 
                   7111: .LC_hcell {
1.911     bisitz   7112:   padding:3px 15px 3px 15px;
                   7113:   margin: 0;
                   7114:   background-color:$tabbg;
                   7115:   color:$fontmenu;
                   7116:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7117: }
1.795     www      7118: 
1.840     bisitz   7119: .LC_Box > .LC_hcell {
1.911     bisitz   7120:   margin: 0 -10px 10px -10px;
1.835     bisitz   7121: }
                   7122: 
1.721     harmsja  7123: .LC_noBorder {
1.911     bisitz   7124:   border: 0;
1.698     harmsja  7125: }
1.693     droeschl 7126: 
1.721     harmsja  7127: .LC_FormSectionClearButton input {
1.911     bisitz   7128:   background-color:transparent;
                   7129:   border: none;
                   7130:   cursor:pointer;
                   7131:   text-decoration:underline;
1.693     droeschl 7132: }
1.763     bisitz   7133: 
                   7134: .LC_help_open_topic {
1.911     bisitz   7135:   color: #FFFFFF;
                   7136:   background-color: #EEEEFF;
                   7137:   margin: 1px;
                   7138:   padding: 4px;
                   7139:   border: 1px solid #000033;
                   7140:   white-space: nowrap;
                   7141:   /* vertical-align: middle; */
1.759     neumanie 7142: }
1.693     droeschl 7143: 
1.911     bisitz   7144: dl,
                   7145: ul,
                   7146: div,
                   7147: fieldset {
                   7148:   margin: 10px 10px 10px 0;
                   7149:   /* overflow: hidden; */
1.693     droeschl 7150: }
1.795     www      7151: 
1.1075.2.90  raeburn  7152: article.geogebraweb div {
                   7153:     margin: 0;
                   7154: }
                   7155: 
1.838     bisitz   7156: fieldset > legend {
1.911     bisitz   7157:   font-weight: bold;
                   7158:   padding: 0 5px 0 5px;
1.838     bisitz   7159: }
                   7160: 
1.813     bisitz   7161: #LC_nav_bar {
1.911     bisitz   7162:   float: left;
1.995     raeburn  7163:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7164:   margin: 0 0 2px 0;
1.807     droeschl 7165: }
                   7166: 
1.916     droeschl 7167: #LC_realm {
                   7168:   margin: 0.2em 0 0 0;
                   7169:   padding: 0;
                   7170:   font-weight: bold;
                   7171:   text-align: center;
1.995     raeburn  7172:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7173: }
                   7174: 
1.911     bisitz   7175: #LC_nav_bar em {
                   7176:   font-weight: bold;
                   7177:   font-style: normal;
1.807     droeschl 7178: }
                   7179: 
1.897     wenzelju 7180: ol.LC_primary_menu {
1.934     droeschl 7181:   margin: 0;
1.1075.2.2  raeburn  7182:   padding: 0;
1.807     droeschl 7183: }
                   7184: 
1.852     droeschl 7185: ol#LC_PathBreadcrumbs {
1.911     bisitz   7186:   margin: 0;
1.693     droeschl 7187: }
                   7188: 
1.897     wenzelju 7189: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7190:   color: RGB(80, 80, 80);
                   7191:   vertical-align: middle;
                   7192:   text-align: left;
                   7193:   list-style: none;
1.1075.2.112  raeburn  7194:   position: relative;
1.1075.2.2  raeburn  7195:   float: left;
1.1075.2.112  raeburn  7196:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7197:   line-height: 1.5em;
1.1075.2.2  raeburn  7198: }
                   7199: 
1.1075.2.113  raeburn  7200: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7201: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7202:   display: block;
                   7203:   margin: 0;
                   7204:   padding: 0 5px 0 10px;
                   7205:   text-decoration: none;
                   7206: }
                   7207: 
1.1075.2.112  raeburn  7208: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7209:   display: inline-block;
                   7210:   width: 95%;
                   7211:   text-align: left;
                   7212: }
                   7213: 
                   7214: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7215:   display: inline-block;
                   7216:   width: 5%;
                   7217:   float: right;
                   7218:   text-align: right;
                   7219:   font-size: 70%;
                   7220: }
                   7221: 
                   7222: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7223:   display: none;
1.1075.2.112  raeburn  7224:   width: 15em;
1.1075.2.2  raeburn  7225:   background-color: $data_table_light;
1.1075.2.112  raeburn  7226:   position: absolute;
                   7227:   top: 100%;
                   7228: }
                   7229: 
                   7230: ol.LC_primary_menu ul ul {
                   7231:   left: 100%;
                   7232:   top: 0;
1.1075.2.2  raeburn  7233: }
                   7234: 
1.1075.2.112  raeburn  7235: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7236:   display: block;
                   7237:   position: absolute;
                   7238:   margin: 0;
                   7239:   padding: 0;
1.1075.2.5  raeburn  7240:   z-index: 2;
1.1075.2.2  raeburn  7241: }
                   7242: 
                   7243: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7244: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7245:   font-size: 90%;
1.911     bisitz   7246:   vertical-align: top;
1.1075.2.2  raeburn  7247:   float: none;
1.1075.2.5  raeburn  7248:   border-left: 1px solid black;
                   7249:   border-right: 1px solid black;
1.1075.2.112  raeburn  7250: /* A dark bottom border to visualize different menu options;
                   7251: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7252:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7253: }
                   7254: 
1.1075.2.112  raeburn  7255: ol.LC_primary_menu li li p:hover {
                   7256:   color:$button_hover;
                   7257:   text-decoration:none;
                   7258:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7259: }
                   7260: 
                   7261: ol.LC_primary_menu li li a:hover {
                   7262:    color:$button_hover;
                   7263:    background-color:$data_table_dark;
1.693     droeschl 7264: }
                   7265: 
1.1075.2.112  raeburn  7266: /* Font-size equal to the size of the predecessors*/
                   7267: ol.LC_primary_menu li:hover li li {
                   7268:   font-size: 100%;
                   7269: }
                   7270: 
1.897     wenzelju 7271: ol.LC_primary_menu li img {
1.911     bisitz   7272:   vertical-align: bottom;
1.934     droeschl 7273:   height: 1.1em;
1.1075.2.3  raeburn  7274:   margin: 0.2em 0 0 0;
1.693     droeschl 7275: }
                   7276: 
1.897     wenzelju 7277: ol.LC_primary_menu a {
1.911     bisitz   7278:   color: RGB(80, 80, 80);
                   7279:   text-decoration: none;
1.693     droeschl 7280: }
1.795     www      7281: 
1.949     droeschl 7282: ol.LC_primary_menu a.LC_new_message {
                   7283:   font-weight:bold;
                   7284:   color: darkred;
                   7285: }
                   7286: 
1.975     raeburn  7287: ol.LC_docs_parameters {
                   7288:   margin-left: 0;
                   7289:   padding: 0;
                   7290:   list-style: none;
                   7291: }
                   7292: 
                   7293: ol.LC_docs_parameters li {
                   7294:   margin: 0;
                   7295:   padding-right: 20px;
                   7296:   display: inline;
                   7297: }
                   7298: 
1.976     raeburn  7299: ol.LC_docs_parameters li:before {
                   7300:   content: "\\002022 \\0020";
                   7301: }
                   7302: 
                   7303: li.LC_docs_parameters_title {
                   7304:   font-weight: bold;
                   7305: }
                   7306: 
                   7307: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7308:   content: "";
                   7309: }
                   7310: 
1.897     wenzelju 7311: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7312:   clear: right;
1.911     bisitz   7313:   color: $fontmenu;
                   7314:   background: $tabbg;
                   7315:   list-style: none;
                   7316:   padding: 0;
                   7317:   margin: 0;
                   7318:   width: 100%;
1.995     raeburn  7319:   text-align: left;
1.1075.2.4  raeburn  7320:   float: left;
1.808     droeschl 7321: }
                   7322: 
1.897     wenzelju 7323: ul#LC_secondary_menu li {
1.911     bisitz   7324:   font-weight: bold;
                   7325:   line-height: 1.8em;
                   7326:   border-right: 1px solid black;
1.1075.2.4  raeburn  7327:   float: left;
                   7328: }
                   7329: 
                   7330: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7331:   background-color: $data_table_light;
                   7332: }
                   7333: 
                   7334: ul#LC_secondary_menu li a {
                   7335:   padding: 0 0.8em;
                   7336: }
                   7337: 
                   7338: ul#LC_secondary_menu li ul {
                   7339:   display: none;
                   7340: }
                   7341: 
                   7342: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7343:   display: block;
                   7344:   position: absolute;
                   7345:   margin: 0;
                   7346:   padding: 0;
                   7347:   list-style:none;
                   7348:   float: none;
                   7349:   background-color: $data_table_light;
1.1075.2.5  raeburn  7350:   z-index: 2;
1.1075.2.10  raeburn  7351:   margin-left: -1px;
1.1075.2.4  raeburn  7352: }
                   7353: 
                   7354: ul#LC_secondary_menu li ul li {
                   7355:   font-size: 90%;
                   7356:   vertical-align: top;
                   7357:   border-left: 1px solid black;
                   7358:   border-right: 1px solid black;
1.1075.2.33  raeburn  7359:   background-color: $data_table_light;
1.1075.2.4  raeburn  7360:   list-style:none;
                   7361:   float: none;
                   7362: }
                   7363: 
                   7364: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7365:   background-color: $data_table_dark;
1.807     droeschl 7366: }
                   7367: 
1.847     tempelho 7368: ul.LC_TabContent {
1.911     bisitz   7369:   display:block;
                   7370:   background: $sidebg;
                   7371:   border-bottom: solid 1px $lg_border_color;
                   7372:   list-style:none;
1.1020    raeburn  7373:   margin: -1px -10px 0 -10px;
1.911     bisitz   7374:   padding: 0;
1.693     droeschl 7375: }
                   7376: 
1.795     www      7377: ul.LC_TabContent li,
                   7378: ul.LC_TabContentBigger li {
1.911     bisitz   7379:   float:left;
1.741     harmsja  7380: }
1.795     www      7381: 
1.897     wenzelju 7382: ul#LC_secondary_menu li a {
1.911     bisitz   7383:   color: $fontmenu;
                   7384:   text-decoration: none;
1.693     droeschl 7385: }
1.795     www      7386: 
1.721     harmsja  7387: ul.LC_TabContent {
1.952     onken    7388:   min-height:20px;
1.721     harmsja  7389: }
1.795     www      7390: 
                   7391: ul.LC_TabContent li {
1.911     bisitz   7392:   vertical-align:middle;
1.959     onken    7393:   padding: 0 16px 0 10px;
1.911     bisitz   7394:   background-color:$tabbg;
                   7395:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7396:   border-left: solid 1px $font;
1.721     harmsja  7397: }
1.795     www      7398: 
1.847     tempelho 7399: ul.LC_TabContent .right {
1.911     bisitz   7400:   float:right;
1.847     tempelho 7401: }
                   7402: 
1.911     bisitz   7403: ul.LC_TabContent li a,
                   7404: ul.LC_TabContent li {
                   7405:   color:rgb(47,47,47);
                   7406:   text-decoration:none;
                   7407:   font-size:95%;
                   7408:   font-weight:bold;
1.952     onken    7409:   min-height:20px;
                   7410: }
                   7411: 
1.959     onken    7412: ul.LC_TabContent li a:hover,
                   7413: ul.LC_TabContent li a:focus {
1.952     onken    7414:   color: $button_hover;
1.959     onken    7415:   background:none;
                   7416:   outline:none;
1.952     onken    7417: }
                   7418: 
                   7419: ul.LC_TabContent li:hover {
                   7420:   color: $button_hover;
                   7421:   cursor:pointer;
1.721     harmsja  7422: }
1.795     www      7423: 
1.911     bisitz   7424: ul.LC_TabContent li.active {
1.952     onken    7425:   color: $font;
1.911     bisitz   7426:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7427:   border-bottom:solid 1px #FFFFFF;
                   7428:   cursor: default;
1.744     ehlerst  7429: }
1.795     www      7430: 
1.959     onken    7431: ul.LC_TabContent li.active a {
                   7432:   color:$font;
                   7433:   background:#FFFFFF;
                   7434:   outline: none;
                   7435: }
1.1047    raeburn  7436: 
                   7437: ul.LC_TabContent li.goback {
                   7438:   float: left;
                   7439:   border-left: none;
                   7440: }
                   7441: 
1.870     tempelho 7442: #maincoursedoc {
1.911     bisitz   7443:   clear:both;
1.870     tempelho 7444: }
                   7445: 
                   7446: ul.LC_TabContentBigger {
1.911     bisitz   7447:   display:block;
                   7448:   list-style:none;
                   7449:   padding: 0;
1.870     tempelho 7450: }
                   7451: 
1.795     www      7452: ul.LC_TabContentBigger li {
1.911     bisitz   7453:   vertical-align:bottom;
                   7454:   height: 30px;
                   7455:   font-size:110%;
                   7456:   font-weight:bold;
                   7457:   color: #737373;
1.841     tempelho 7458: }
                   7459: 
1.957     onken    7460: ul.LC_TabContentBigger li.active {
                   7461:   position: relative;
                   7462:   top: 1px;
                   7463: }
                   7464: 
1.870     tempelho 7465: ul.LC_TabContentBigger li a {
1.911     bisitz   7466:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7467:   height: 30px;
                   7468:   line-height: 30px;
                   7469:   text-align: center;
                   7470:   display: block;
                   7471:   text-decoration: none;
1.958     onken    7472:   outline: none;  
1.741     harmsja  7473: }
1.795     www      7474: 
1.870     tempelho 7475: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7476:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7477:   color:$font;
1.744     ehlerst  7478: }
1.795     www      7479: 
1.870     tempelho 7480: ul.LC_TabContentBigger li b {
1.911     bisitz   7481:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7482:   display: block;
                   7483:   float: left;
                   7484:   padding: 0 30px;
1.957     onken    7485:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7486: }
                   7487: 
1.956     onken    7488: ul.LC_TabContentBigger li:hover b {
                   7489:   color:$button_hover;
                   7490: }
                   7491: 
1.870     tempelho 7492: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7493:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7494:   color:$font;
1.957     onken    7495:   border: 0;
1.741     harmsja  7496: }
1.693     droeschl 7497: 
1.870     tempelho 7498: 
1.862     bisitz   7499: ul.LC_CourseBreadcrumbs {
                   7500:   background: $sidebg;
1.1020    raeburn  7501:   height: 2em;
1.862     bisitz   7502:   padding-left: 10px;
1.1020    raeburn  7503:   margin: 0;
1.862     bisitz   7504:   list-style-position: inside;
                   7505: }
                   7506: 
1.911     bisitz   7507: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7508: ol#LC_PathBreadcrumbs {
1.911     bisitz   7509:   padding-left: 10px;
                   7510:   margin: 0;
1.933     droeschl 7511:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7512: }
                   7513: 
1.911     bisitz   7514: ol#LC_MenuBreadcrumbs li,
                   7515: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7516: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7517:   display: inline;
1.933     droeschl 7518:   white-space: normal;  
1.693     droeschl 7519: }
                   7520: 
1.823     bisitz   7521: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7522: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7523:   text-decoration: none;
                   7524:   font-size:90%;
1.693     droeschl 7525: }
1.795     www      7526: 
1.969     droeschl 7527: ol#LC_MenuBreadcrumbs h1 {
                   7528:   display: inline;
                   7529:   font-size: 90%;
                   7530:   line-height: 2.5em;
                   7531:   margin: 0;
                   7532:   padding: 0;
                   7533: }
                   7534: 
1.795     www      7535: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7536:   text-decoration:none;
                   7537:   font-size:100%;
                   7538:   font-weight:bold;
1.693     droeschl 7539: }
1.795     www      7540: 
1.840     bisitz   7541: .LC_Box {
1.911     bisitz   7542:   border: solid 1px $lg_border_color;
                   7543:   padding: 0 10px 10px 10px;
1.746     neumanie 7544: }
1.795     www      7545: 
1.1020    raeburn  7546: .LC_DocsBox {
                   7547:   border: solid 1px $lg_border_color;
                   7548:   padding: 0 0 10px 10px;
                   7549: }
                   7550: 
1.795     www      7551: .LC_AboutMe_Image {
1.911     bisitz   7552:   float:left;
                   7553:   margin-right:10px;
1.747     neumanie 7554: }
1.795     www      7555: 
                   7556: .LC_Clear_AboutMe_Image {
1.911     bisitz   7557:   clear:left;
1.747     neumanie 7558: }
1.795     www      7559: 
1.721     harmsja  7560: dl.LC_ListStyleClean dt {
1.911     bisitz   7561:   padding-right: 5px;
                   7562:   display: table-header-group;
1.693     droeschl 7563: }
                   7564: 
1.721     harmsja  7565: dl.LC_ListStyleClean dd {
1.911     bisitz   7566:   display: table-row;
1.693     droeschl 7567: }
                   7568: 
1.721     harmsja  7569: .LC_ListStyleClean,
                   7570: .LC_ListStyleSimple,
                   7571: .LC_ListStyleNormal,
1.795     www      7572: .LC_ListStyleSpecial {
1.911     bisitz   7573:   /* display:block; */
                   7574:   list-style-position: inside;
                   7575:   list-style-type: none;
                   7576:   overflow: hidden;
                   7577:   padding: 0;
1.693     droeschl 7578: }
                   7579: 
1.721     harmsja  7580: .LC_ListStyleSimple li,
                   7581: .LC_ListStyleSimple dd,
                   7582: .LC_ListStyleNormal li,
                   7583: .LC_ListStyleNormal dd,
                   7584: .LC_ListStyleSpecial li,
1.795     www      7585: .LC_ListStyleSpecial dd {
1.911     bisitz   7586:   margin: 0;
                   7587:   padding: 5px 5px 5px 10px;
                   7588:   clear: both;
1.693     droeschl 7589: }
                   7590: 
1.721     harmsja  7591: .LC_ListStyleClean li,
                   7592: .LC_ListStyleClean dd {
1.911     bisitz   7593:   padding-top: 0;
                   7594:   padding-bottom: 0;
1.693     droeschl 7595: }
                   7596: 
1.721     harmsja  7597: .LC_ListStyleSimple dd,
1.795     www      7598: .LC_ListStyleSimple li {
1.911     bisitz   7599:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7600: }
                   7601: 
1.721     harmsja  7602: .LC_ListStyleSpecial li,
                   7603: .LC_ListStyleSpecial dd {
1.911     bisitz   7604:   list-style-type: none;
                   7605:   background-color: RGB(220, 220, 220);
                   7606:   margin-bottom: 4px;
1.693     droeschl 7607: }
                   7608: 
1.721     harmsja  7609: table.LC_SimpleTable {
1.911     bisitz   7610:   margin:5px;
                   7611:   border:solid 1px $lg_border_color;
1.795     www      7612: }
1.693     droeschl 7613: 
1.721     harmsja  7614: table.LC_SimpleTable tr {
1.911     bisitz   7615:   padding: 0;
                   7616:   border:solid 1px $lg_border_color;
1.693     droeschl 7617: }
1.795     www      7618: 
                   7619: table.LC_SimpleTable thead {
1.911     bisitz   7620:   background:rgb(220,220,220);
1.693     droeschl 7621: }
                   7622: 
1.721     harmsja  7623: div.LC_columnSection {
1.911     bisitz   7624:   display: block;
                   7625:   clear: both;
                   7626:   overflow: hidden;
                   7627:   margin: 0;
1.693     droeschl 7628: }
                   7629: 
1.721     harmsja  7630: div.LC_columnSection>* {
1.911     bisitz   7631:   float: left;
                   7632:   margin: 10px 20px 10px 0;
                   7633:   overflow:hidden;
1.693     droeschl 7634: }
1.721     harmsja  7635: 
1.795     www      7636: table em {
1.911     bisitz   7637:   font-weight: bold;
                   7638:   font-style: normal;
1.748     schulted 7639: }
1.795     www      7640: 
1.779     bisitz   7641: table.LC_tableBrowseRes,
1.795     www      7642: table.LC_tableOfContent {
1.911     bisitz   7643:   border:none;
                   7644:   border-spacing: 1px;
                   7645:   padding: 3px;
                   7646:   background-color: #FFFFFF;
                   7647:   font-size: 90%;
1.753     droeschl 7648: }
1.789     droeschl 7649: 
1.911     bisitz   7650: table.LC_tableOfContent {
                   7651:   border-collapse: collapse;
1.789     droeschl 7652: }
                   7653: 
1.771     droeschl 7654: table.LC_tableBrowseRes a,
1.768     schulted 7655: table.LC_tableOfContent a {
1.911     bisitz   7656:   background-color: transparent;
                   7657:   text-decoration: none;
1.753     droeschl 7658: }
                   7659: 
1.795     www      7660: table.LC_tableOfContent img {
1.911     bisitz   7661:   border: none;
                   7662:   height: 1.3em;
                   7663:   vertical-align: text-bottom;
                   7664:   margin-right: 0.3em;
1.753     droeschl 7665: }
1.757     schulted 7666: 
1.795     www      7667: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7668:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7669: }
                   7670: 
1.795     www      7671: a#LC_content_toolbar_everything {
1.911     bisitz   7672:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7673: }
                   7674: 
1.795     www      7675: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7676:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7677: }
                   7678: 
1.795     www      7679: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7680:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7681: }
                   7682: 
1.795     www      7683: a#LC_content_toolbar_changefolder {
1.911     bisitz   7684:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7685: }
                   7686: 
1.795     www      7687: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7688:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7689: }
                   7690: 
1.1043    raeburn  7691: a#LC_content_toolbar_edittoplevel {
                   7692:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7693: }
                   7694: 
1.795     www      7695: ul#LC_toolbar li a:hover {
1.911     bisitz   7696:   background-position: bottom center;
1.757     schulted 7697: }
                   7698: 
1.795     www      7699: ul#LC_toolbar {
1.911     bisitz   7700:   padding: 0;
                   7701:   margin: 2px;
                   7702:   list-style:none;
                   7703:   position:relative;
                   7704:   background-color:white;
1.1075.2.9  raeburn  7705:   overflow: auto;
1.757     schulted 7706: }
                   7707: 
1.795     www      7708: ul#LC_toolbar li {
1.911     bisitz   7709:   border:1px solid white;
                   7710:   padding: 0;
                   7711:   margin: 0;
                   7712:   float: left;
                   7713:   display:inline;
                   7714:   vertical-align:middle;
1.1075.2.9  raeburn  7715:   white-space: nowrap;
1.911     bisitz   7716: }
1.757     schulted 7717: 
1.783     amueller 7718: 
1.795     www      7719: a.LC_toolbarItem {
1.911     bisitz   7720:   display:block;
                   7721:   padding: 0;
                   7722:   margin: 0;
                   7723:   height: 32px;
                   7724:   width: 32px;
                   7725:   color:white;
                   7726:   border: none;
                   7727:   background-repeat:no-repeat;
                   7728:   background-color:transparent;
1.757     schulted 7729: }
                   7730: 
1.915     droeschl 7731: ul.LC_funclist {
                   7732:     margin: 0;
                   7733:     padding: 0.5em 1em 0.5em 0;
                   7734: }
                   7735: 
1.933     droeschl 7736: ul.LC_funclist > li:first-child {
                   7737:     font-weight:bold; 
                   7738:     margin-left:0.8em;
                   7739: }
                   7740: 
1.915     droeschl 7741: ul.LC_funclist + ul.LC_funclist {
                   7742:     /* 
                   7743:        left border as a seperator if we have more than
                   7744:        one list 
                   7745:     */
                   7746:     border-left: 1px solid $sidebg;
                   7747:     /* 
                   7748:        this hides the left border behind the border of the 
                   7749:        outer box if element is wrapped to the next 'line' 
                   7750:     */
                   7751:     margin-left: -1px;
                   7752: }
                   7753: 
1.843     bisitz   7754: ul.LC_funclist li {
1.915     droeschl 7755:   display: inline;
1.782     bisitz   7756:   white-space: nowrap;
1.915     droeschl 7757:   margin: 0 0 0 25px;
                   7758:   line-height: 150%;
1.782     bisitz   7759: }
                   7760: 
1.974     wenzelju 7761: .LC_hidden {
                   7762:   display: none;
                   7763: }
                   7764: 
1.1030    www      7765: .LCmodal-overlay {
                   7766: 		position:fixed;
                   7767: 		top:0;
                   7768: 		right:0;
                   7769: 		bottom:0;
                   7770: 		left:0;
                   7771: 		height:100%;
                   7772: 		width:100%;
                   7773: 		margin:0;
                   7774: 		padding:0;
                   7775: 		background:#999;
                   7776: 		opacity:.75;
                   7777: 		filter: alpha(opacity=75);
                   7778: 		-moz-opacity: 0.75;
                   7779: 		z-index:101;
                   7780: }
                   7781: 
                   7782: * html .LCmodal-overlay {   
                   7783: 		position: absolute;
                   7784: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7785: }
                   7786: 
                   7787: .LCmodal-window {
                   7788: 		position:fixed;
                   7789: 		top:50%;
                   7790: 		left:50%;
                   7791: 		margin:0;
                   7792: 		padding:0;
                   7793: 		z-index:102;
                   7794: 	}
                   7795: 
                   7796: * html .LCmodal-window {
                   7797: 		position:absolute;
                   7798: }
                   7799: 
                   7800: .LCclose-window {
                   7801: 		position:absolute;
                   7802: 		width:32px;
                   7803: 		height:32px;
                   7804: 		right:8px;
                   7805: 		top:8px;
                   7806: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7807: 		text-indent:-99999px;
                   7808: 		overflow:hidden;
                   7809: 		cursor:pointer;
                   7810: }
                   7811: 
1.1075.2.141  raeburn  7812: pre.LC_wordwrap {
                   7813:   white-space: pre-wrap;
                   7814:   white-space: -moz-pre-wrap;
                   7815:   white-space: -pre-wrap;
                   7816:   white-space: -o-pre-wrap;
                   7817:   word-wrap: break-word;
                   7818: }
                   7819: 
1.1075.2.17  raeburn  7820: /*
                   7821:   styles used by TTH when "Default set of options to pass to tth/m
                   7822:   when converting TeX" in course settings has been set
                   7823: 
                   7824:   option passed: -t
                   7825: 
                   7826: */
                   7827: 
                   7828: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7829: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7830: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7831: td div.norm {line-height:normal;}
                   7832: 
                   7833: /*
                   7834:   option passed -y3
                   7835: */
                   7836: 
                   7837: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7838: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7839: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7840: 
1.1075.2.121  raeburn  7841: #LC_minitab_header {
                   7842:   float:left;
                   7843:   width:100%;
                   7844:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7845:   font-size:93%;
                   7846:   line-height:normal;
                   7847:   margin: 0.5em 0 0.5em 0;
                   7848: }
                   7849: #LC_minitab_header ul {
                   7850:   margin:0;
                   7851:   padding:10px 10px 0;
                   7852:   list-style:none;
                   7853: }
                   7854: #LC_minitab_header li {
                   7855:   float:left;
                   7856:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7857:   margin:0;
                   7858:   padding:0 0 0 9px;
                   7859: }
                   7860: #LC_minitab_header a {
                   7861:   display:block;
                   7862:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7863:   padding:5px 15px 4px 6px;
                   7864: }
                   7865: #LC_minitab_header #LC_current_minitab {
                   7866:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7867: }
                   7868: #LC_minitab_header #LC_current_minitab a {
                   7869:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7870:   padding-bottom:5px;
                   7871: }
                   7872: 
                   7873: 
1.343     albertel 7874: END
                   7875: }
                   7876: 
1.306     albertel 7877: =pod
                   7878: 
                   7879: =item * &headtag()
                   7880: 
                   7881: Returns a uniform footer for LON-CAPA web pages.
                   7882: 
1.307     albertel 7883: Inputs: $title - optional title for the head
                   7884:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7885:         $args - optional arguments
1.319     albertel 7886:             force_register - if is true call registerurl so the remote is 
                   7887:                              informed
1.415     albertel 7888:             redirect       -> array ref of
                   7889:                                    1- seconds before redirect occurs
                   7890:                                    2- url to redirect to
                   7891:                                    3- whether the side effect should occur
1.315     albertel 7892:                            (side effect of setting 
                   7893:                                $env{'internal.head.redirect'} to the url 
                   7894:                                redirected too)
1.352     albertel 7895:             domain         -> force to color decorate a page for a specific
                   7896:                                domain
                   7897:             function       -> force usage of a specific rolish color scheme
                   7898:             bgcolor        -> override the default page bgcolor
1.460     albertel 7899:             no_auto_mt_title
                   7900:                            -> prevent &mt()ing the title arg
1.464     albertel 7901: 
1.306     albertel 7902: =cut
                   7903: 
                   7904: sub headtag {
1.313     albertel 7905:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7906:     
1.363     albertel 7907:     my $function = $args->{'function'} || &get_users_function();
                   7908:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7909:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7910:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7911:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7912: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7913: 		   #time(),
1.418     albertel 7914: 		   $env{'environment.color.timestamp'},
1.363     albertel 7915: 		   $function,$domain,$bgcolor);
                   7916: 
1.369     www      7917:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7918: 
1.308     albertel 7919:     my $result =
                   7920: 	'<head>'.
1.1075.2.56  raeburn  7921: 	&font_settings($args);
1.319     albertel 7922: 
1.1075.2.72  raeburn  7923:     my $inhibitprint;
                   7924:     if ($args->{'print_suppress'}) {
                   7925:         $inhibitprint = &print_suppression();
                   7926:     }
1.1064    raeburn  7927: 
1.461     albertel 7928:     if (!$args->{'frameset'}) {
                   7929: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7930:     }
1.1075.2.12  raeburn  7931:     if ($args->{'force_register'}) {
                   7932:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7933:     }
1.436     albertel 7934:     if (!$args->{'no_nav_bar'} 
                   7935: 	&& !$args->{'only_body'}
                   7936: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7937: 	$result .= &help_menu_js($httphost);
1.1032    www      7938:         $result.=&modal_window();
1.1038    www      7939:         $result.=&togglebox_script();
1.1034    www      7940:         $result.=&wishlist_window();
1.1041    www      7941:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7942:     } else {
                   7943:         if ($args->{'add_modal'}) {
                   7944:            $result.=&modal_window();
                   7945:         }
                   7946:         if ($args->{'add_wishlist'}) {
                   7947:            $result.=&wishlist_window();
                   7948:         }
1.1038    www      7949:         if ($args->{'add_togglebox'}) {
                   7950:            $result.=&togglebox_script();
                   7951:         }
1.1041    www      7952:         if ($args->{'add_progressbar'}) {
                   7953:            $result.=&LCprogressbarUpdate_script();
                   7954:         }
1.436     albertel 7955:     }
1.314     albertel 7956:     if (ref($args->{'redirect'})) {
1.414     albertel 7957: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7958: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7959: 	if (!$inhibit_continue) {
                   7960: 	    $env{'internal.head.redirect'} = $url;
                   7961: 	}
1.313     albertel 7962: 	$result.=<<ADDMETA
                   7963: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7964: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7965: ADDMETA
1.1075.2.89  raeburn  7966:     } else {
                   7967:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7968:             my $requrl = $env{'request.uri'};
                   7969:             if ($requrl eq '') {
                   7970:                 $requrl = $ENV{'REQUEST_URI'};
                   7971:                 $requrl =~ s/\?.+$//;
                   7972:             }
                   7973:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7974:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7975:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7976:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7977:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7978:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.141.  .4(raebu 7979:20):                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7980:20):                     my $offload;
1.1075.2.89  raeburn  7981:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7982:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.141.  .4(raebu 7983:20):                             $offload = 1;
                   7984:20):                         }
                   7985:20):                     }
                   7986:20):                     unless ($offload) {
                   7987:20):                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   7988:20):                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   7989:20):                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   7990:20):                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   7991:20):                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   7992:20):                                         $offload = 1;
                   7993:20):                                         $dom_in_use = $env{'user.domain'};
                   7994:20):                                     }
1.1075.2.89  raeburn  7995:                                 }
1.1075.2.141.  .4(raebu 7996:20):                             }
                   7997:20):                         }
                   7998:20):                     }
                   7999:20):                     if ($offload) {
                   8000:20):                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8001:20):                         if (($newserver) && ($newserver ne $lonhost)) {
                   8002:20):                             my $numsec = 5;
                   8003:20):                             my $timeout = $numsec * 1000;
                   8004:20):                             my ($newurl,$locknum,%locks,$msg);
                   8005:20):                             if ($env{'request.role.adv'}) {
                   8006:20):                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8007:20):                             }
                   8008:20):                             my $disable_submit = 0;
                   8009:20):                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8010:20):                                 $disable_submit = 1;
                   8011:20):                             }
                   8012:20):                             if ($locknum) {
                   8013:20):                                 my @lockinfo = sort(values(%locks));
                   8014:20):                                 $msg = &mt('Once the following tasks are complete: ')."\n".
                   8015:20):                                        join(", ",sort(values(%locks)))."\n";
                   8016:20):                                 if (&show_course()) {
                   8017:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8018:                                 } else {
1.1075.2.141.  .4(raebu 8019:20):                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8020:20):                                 }
                   8021:20):                             } else {
                   8022:20):                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8023:20):                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8024:20):                                 }
                   8025:20):                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8026:20):                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8027:20):                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8028:20):                                     $newurl .= '&role='.$env{'request.role'};
                   8029:20):                                 }
                   8030:20):                                 if ($env{'request.symb'}) {
                   8031:20):                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8032:20):                                     if ($shownsymb =~ m{^/enc/}) {
                   8033:20):                                         my $reqdmajor = 2;
                   8034:20):                                         my $reqdminor = 11;
                   8035:20):                                         my $reqdsubminor = 3;
                   8036:20):                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8037:20):                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8038:20):                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8039:20):                                         if (($major eq '' && $minor eq '') ||
                   8040:20):                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8041:20):                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8042:20):                                              ($reqdsubminor > $subminor))))) {
                   8043:20):                                             undef($shownsymb);
                   8044:20):                                         }
1.1075.2.89  raeburn  8045:                                     }
1.1075.2.141.  .4(raebu 8046:20):                                     if ($shownsymb) {
                   8047:20):                                         &js_escape(\$shownsymb);
                   8048:20):                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8049:                                     }
1.1075.2.141.  .4(raebu 8050:20):                                 } else {
                   8051:20):                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8052:20):                                     &js_escape(\$shownurl);
                   8053:20):                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8054:                                 }
1.1075.2.141.  .4(raebu 8055:20):                             }
                   8056:20):                             &js_escape(\$msg);
                   8057:20):                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8058: <meta http-equiv="pragma" content="no-cache" />
                   8059: <script type="text/javascript">
1.1075.2.92  raeburn  8060: // <![CDATA[
1.1075.2.89  raeburn  8061: function LC_Offload_Now() {
                   8062:     var dest = "$newurl";
                   8063:     if (dest != '') {
                   8064:         window.location.href="$newurl";
                   8065:     }
                   8066: }
1.1075.2.92  raeburn  8067: \$(document).ready(function () {
                   8068:     window.alert('$msg');
                   8069:     if ($disable_submit) {
1.1075.2.89  raeburn  8070:         \$(".LC_hwk_submit").prop("disabled", true);
                   8071:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8072:     }
                   8073:     setTimeout('LC_Offload_Now()', $timeout);
                   8074: });
                   8075: // ]]>
1.1075.2.89  raeburn  8076: </script>
                   8077: OFFLOAD
                   8078:                         }
                   8079:                     }
                   8080:                 }
                   8081:             }
                   8082:         }
1.313     albertel 8083:     }
1.306     albertel 8084:     if (!defined($title)) {
                   8085: 	$title = 'The LearningOnline Network with CAPA';
                   8086:     }
1.460     albertel 8087:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8088:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8089: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8090:     if (!$args->{'frameset'}) {
                   8091:         $result .= ' /';
                   8092:     }
                   8093:     $result .= '>'
1.1064    raeburn  8094:         .$inhibitprint
1.414     albertel 8095: 	.$head_extra;
1.1075.2.108  raeburn  8096:     my $clientmobile;
                   8097:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8098:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8099:     } else {
                   8100:         $clientmobile = $env{'browser.mobile'};
                   8101:     }
                   8102:     if ($clientmobile) {
1.1075.2.42  raeburn  8103:         $result .= '
                   8104: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8105: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8106:     }
1.1075.2.126  raeburn  8107:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8108:     return $result.'</head>';
1.306     albertel 8109: }
                   8110: 
                   8111: =pod
                   8112: 
1.340     albertel 8113: =item * &font_settings()
                   8114: 
                   8115: Returns neccessary <meta> to set the proper encoding
                   8116: 
1.1075.2.56  raeburn  8117: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8118: 
                   8119: =cut
                   8120: 
                   8121: sub font_settings {
1.1075.2.56  raeburn  8122:     my ($args) = @_;
1.340     albertel 8123:     my $headerstring='';
1.1075.2.56  raeburn  8124:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8125:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8126: 	$headerstring.=
1.1075.2.61  raeburn  8127: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8128:         if (!$args->{'frameset'}) {
                   8129:             $headerstring.= ' /';
                   8130:         }
                   8131:         $headerstring .= '>'."\n";
1.340     albertel 8132:     }
                   8133:     return $headerstring;
                   8134: }
                   8135: 
1.341     albertel 8136: =pod
                   8137: 
1.1064    raeburn  8138: =item * &print_suppression()
                   8139: 
                   8140: In course context returns css which causes the body to be blank when media="print",
                   8141: if printout generation is unavailable for the current resource.
                   8142: 
                   8143: This could be because:
                   8144: 
                   8145: (a) printstartdate is in the future
                   8146: 
                   8147: (b) printenddate is in the past
                   8148: 
                   8149: (c) there is an active exam block with "printout"
                   8150: functionality blocked
                   8151: 
                   8152: Users with pav, pfo or evb privileges are exempt.
                   8153: 
                   8154: Inputs: none
                   8155: 
                   8156: =cut
                   8157: 
                   8158: 
                   8159: sub print_suppression {
                   8160:     my $noprint;
                   8161:     if ($env{'request.course.id'}) {
                   8162:         my $scope = $env{'request.course.id'};
                   8163:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8164:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8165:             return;
                   8166:         }
                   8167:         if ($env{'request.course.sec'} ne '') {
                   8168:             $scope .= "/$env{'request.course.sec'}";
                   8169:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8170:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8171:                 return;
1.1064    raeburn  8172:             }
                   8173:         }
                   8174:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8175:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8176:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8177:         if ($blocked) {
                   8178:             my $checkrole = "cm./$cdom/$cnum";
                   8179:             if ($env{'request.course.sec'} ne '') {
                   8180:                 $checkrole .= "/$env{'request.course.sec'}";
                   8181:             }
                   8182:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8183:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8184:                 $noprint = 1;
                   8185:             }
                   8186:         }
                   8187:         unless ($noprint) {
                   8188:             my $symb = &Apache::lonnet::symbread();
                   8189:             if ($symb ne '') {
                   8190:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8191:                 if (ref($navmap)) {
                   8192:                     my $res = $navmap->getBySymb($symb);
                   8193:                     if (ref($res)) {
                   8194:                         if (!$res->resprintable()) {
                   8195:                             $noprint = 1;
                   8196:                         }
                   8197:                     }
                   8198:                 }
                   8199:             }
                   8200:         }
                   8201:         if ($noprint) {
                   8202:             return <<"ENDSTYLE";
                   8203: <style type="text/css" media="print">
                   8204:     body { display:none }
                   8205: </style>
                   8206: ENDSTYLE
                   8207:         }
                   8208:     }
                   8209:     return;
                   8210: }
                   8211: 
                   8212: =pod
                   8213: 
1.341     albertel 8214: =item * &xml_begin()
                   8215: 
                   8216: Returns the needed doctype and <html>
                   8217: 
                   8218: Inputs: none
                   8219: 
                   8220: =cut
                   8221: 
                   8222: sub xml_begin {
1.1075.2.61  raeburn  8223:     my ($is_frameset) = @_;
1.341     albertel 8224:     my $output='';
                   8225: 
                   8226:     if ($env{'browser.mathml'}) {
                   8227: 	$output='<?xml version="1.0"?>'
                   8228:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8229: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8230:             
                   8231: #	    .'<!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">] >'
                   8232: 	    .'<!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">'
                   8233:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8234: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8235:     } elsif ($is_frameset) {
                   8236:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8237:                 '<html>'."\n";
1.341     albertel 8238:     } else {
1.1075.2.61  raeburn  8239: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8240:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8241:     }
                   8242:     return $output;
                   8243: }
1.340     albertel 8244: 
                   8245: =pod
                   8246: 
1.306     albertel 8247: =item * &start_page()
                   8248: 
                   8249: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8250: 
1.648     raeburn  8251: Inputs:
                   8252: 
                   8253: =over 4
                   8254: 
                   8255: $title - optional title for the page
                   8256: 
                   8257: $head_extra - optional extra HTML to incude inside the <head>
                   8258: 
                   8259: $args - additional optional args supported are:
                   8260: 
                   8261: =over 8
                   8262: 
                   8263:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8264:                                     arg on
1.814     bisitz   8265:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8266:              add_entries    -> additional attributes to add to the  <body>
                   8267:              domain         -> force to color decorate a page for a 
1.317     albertel 8268:                                     specific domain
1.648     raeburn  8269:              function       -> force usage of a specific rolish color
1.317     albertel 8270:                                     scheme
1.648     raeburn  8271:              redirect       -> see &headtag()
                   8272:              bgcolor        -> override the default page bg color
                   8273:              js_ready       -> return a string ready for being used in 
1.317     albertel 8274:                                     a javascript writeln
1.648     raeburn  8275:              html_encode    -> return a string ready for being used in 
1.320     albertel 8276:                                     a html attribute
1.648     raeburn  8277:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8278:                                     $forcereg arg
1.648     raeburn  8279:              frameset       -> if true will start with a <frameset>
1.330     albertel 8280:                                     rather than <body>
1.648     raeburn  8281:              skip_phases    -> hash ref of 
1.338     albertel 8282:                                     head -> skip the <html><head> generation
                   8283:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8284:              no_inline_link -> if true and in remote mode, don't show the
                   8285:                                     'Switch To Inline Menu' link
1.648     raeburn  8286:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8287:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8288:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8289:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8290:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8291:              group          -> includes the current group, if page is for a
                   8292:                                specific group
1.1075.2.133  raeburn  8293:              use_absolute   -> for request for external resource or syllabus, this
                   8294:                                will contain https://<hostname> if server uses
                   8295:                                https (as per hosts.tab), but request is for http
                   8296:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8297: 
1.648     raeburn  8298: =back
1.460     albertel 8299: 
1.648     raeburn  8300: =back
1.562     albertel 8301: 
1.306     albertel 8302: =cut
                   8303: 
                   8304: sub start_page {
1.309     albertel 8305:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8306:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8307: 
1.315     albertel 8308:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8309:     my ($result,@advtools);
1.964     droeschl 8310: 
1.338     albertel 8311:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8312:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8313:     }
                   8314:     
                   8315:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8316: 	if ($args->{'frameset'}) {
                   8317: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8318: 						$args->{'add_entries'});
                   8319: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8320:         } else {
                   8321:             $result .=
                   8322:                 &bodytag($title, 
                   8323:                          $args->{'function'},       $args->{'add_entries'},
                   8324:                          $args->{'only_body'},      $args->{'domain'},
                   8325:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8326:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8327:                          $args,                     \@advtools);
1.831     bisitz   8328:         }
1.330     albertel 8329:     }
1.338     albertel 8330: 
1.315     albertel 8331:     if ($args->{'js_ready'}) {
1.713     kaisler  8332: 		$result = &js_ready($result);
1.315     albertel 8333:     }
1.320     albertel 8334:     if ($args->{'html_encode'}) {
1.713     kaisler  8335: 		$result = &html_encode($result);
                   8336:     }
                   8337: 
1.813     bisitz   8338:     # Preparation for new and consistent functionlist at top of screen
                   8339:     # if ($args->{'functionlist'}) {
                   8340:     #            $result .= &build_functionlist();
                   8341:     #}
                   8342: 
1.964     droeschl 8343:     # Don't add anything more if only_body wanted or in const space
                   8344:     return $result if    $args->{'only_body'} 
                   8345:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8346: 
                   8347:     #Breadcrumbs
1.758     kaisler  8348:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8349: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8350: 		#if any br links exists, add them to the breadcrumbs
                   8351: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8352: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8353: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8354: 			}
                   8355: 		}
1.1075.2.19  raeburn  8356:                 # if @advtools array contains items add then to the breadcrumbs
                   8357:                 if (@advtools > 0) {
                   8358:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8359:                 }
1.1075.2.123  raeburn  8360:                 my $menulink;
                   8361:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8362:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8363:                     $menulink = 0;
                   8364:                 } else {
                   8365:                     undef($menulink);
                   8366:                 }
1.758     kaisler  8367: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8368: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8369: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8370: 		}else{
1.1075.2.123  raeburn  8371: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8372: 		}
1.1075.2.24  raeburn  8373:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8374:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8375:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8376:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8377:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8378:     }
1.315     albertel 8379:     return $result;
1.306     albertel 8380: }
                   8381: 
                   8382: sub end_page {
1.315     albertel 8383:     my ($args) = @_;
                   8384:     $env{'internal.end_page'}++;
1.330     albertel 8385:     my $result;
1.335     albertel 8386:     if ($args->{'discussion'}) {
                   8387: 	my ($target,$parser);
                   8388: 	if (ref($args->{'discussion'})) {
                   8389: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8390: 				$args->{'discussion'}{'parser'});
                   8391: 	}
                   8392: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8393:     }
1.330     albertel 8394:     if ($args->{'frameset'}) {
                   8395: 	$result .= '</frameset>';
                   8396:     } else {
1.635     raeburn  8397: 	$result .= &endbodytag($args);
1.330     albertel 8398:     }
1.1075.2.6  raeburn  8399:     unless ($args->{'notbody'}) {
                   8400:         $result .= "\n</html>";
                   8401:     }
1.330     albertel 8402: 
1.315     albertel 8403:     if ($args->{'js_ready'}) {
1.317     albertel 8404: 	$result = &js_ready($result);
1.315     albertel 8405:     }
1.335     albertel 8406: 
1.320     albertel 8407:     if ($args->{'html_encode'}) {
                   8408: 	$result = &html_encode($result);
                   8409:     }
1.335     albertel 8410: 
1.315     albertel 8411:     return $result;
                   8412: }
                   8413: 
1.1034    www      8414: sub wishlist_window {
                   8415:     return(<<'ENDWISHLIST');
1.1046    raeburn  8416: <script type="text/javascript">
1.1034    www      8417: // <![CDATA[
                   8418: // <!-- BEGIN LON-CAPA Internal
                   8419: function set_wishlistlink(title, path) {
                   8420:     if (!title) {
                   8421:         title = document.title;
                   8422:         title = title.replace(/^LON-CAPA /,'');
                   8423:     }
1.1075.2.65  raeburn  8424:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8425:     title = title.replace("'","\\\'");
1.1034    www      8426:     if (!path) {
                   8427:         path = location.pathname;
                   8428:     }
1.1075.2.65  raeburn  8429:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8430:     path = path.replace("'","\\\'");
1.1034    www      8431:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8432:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8433: }
                   8434: // END LON-CAPA Internal -->
                   8435: // ]]>
                   8436: </script>
                   8437: ENDWISHLIST
                   8438: }
                   8439: 
1.1030    www      8440: sub modal_window {
                   8441:     return(<<'ENDMODAL');
1.1046    raeburn  8442: <script type="text/javascript">
1.1030    www      8443: // <![CDATA[
                   8444: // <!-- BEGIN LON-CAPA Internal
                   8445: var modalWindow = {
                   8446: 	parent:"body",
                   8447: 	windowId:null,
                   8448: 	content:null,
                   8449: 	width:null,
                   8450: 	height:null,
                   8451: 	close:function()
                   8452: 	{
                   8453: 	        $(".LCmodal-window").remove();
                   8454: 	        $(".LCmodal-overlay").remove();
                   8455: 	},
                   8456: 	open:function()
                   8457: 	{
                   8458: 		var modal = "";
                   8459: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8460: 		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;\">";
                   8461: 		modal += this.content;
                   8462: 		modal += "</div>";	
                   8463: 
                   8464: 		$(this.parent).append(modal);
                   8465: 
                   8466: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8467: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8468: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8469: 	}
                   8470: };
1.1075.2.42  raeburn  8471: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8472: 	{
1.1075.2.119  raeburn  8473:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8474: 		modalWindow.windowId = "myModal";
                   8475: 		modalWindow.width = width;
                   8476: 		modalWindow.height = height;
1.1075.2.80  raeburn  8477: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8478: 		modalWindow.open();
1.1075.2.87  raeburn  8479: 	};
1.1030    www      8480: // END LON-CAPA Internal -->
                   8481: // ]]>
                   8482: </script>
                   8483: ENDMODAL
                   8484: }
                   8485: 
                   8486: sub modal_link {
1.1075.2.42  raeburn  8487:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8488:     unless ($width) { $width=480; }
                   8489:     unless ($height) { $height=400; }
1.1031    www      8490:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8491:     unless ($transparency) { $transparency='true'; }
                   8492: 
1.1074    raeburn  8493:     my $target_attr;
                   8494:     if (defined($target)) {
                   8495:         $target_attr = 'target="'.$target.'"';
                   8496:     }
                   8497:     return <<"ENDLINK";
1.1075.2.141.  .3(raebu 8498:20): <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8499: ENDLINK
1.1030    www      8500: }
                   8501: 
1.1032    www      8502: sub modal_adhoc_script {
                   8503:     my ($funcname,$width,$height,$content)=@_;
                   8504:     return (<<ENDADHOC);
1.1046    raeburn  8505: <script type="text/javascript">
1.1032    www      8506: // <![CDATA[
                   8507:         var $funcname = function()
                   8508:         {
                   8509:                 modalWindow.windowId = "myModal";
                   8510:                 modalWindow.width = $width;
                   8511:                 modalWindow.height = $height;
                   8512:                 modalWindow.content = '$content';
                   8513:                 modalWindow.open();
                   8514:         };  
                   8515: // ]]>
                   8516: </script>
                   8517: ENDADHOC
                   8518: }
                   8519: 
1.1041    www      8520: sub modal_adhoc_inner {
                   8521:     my ($funcname,$width,$height,$content)=@_;
                   8522:     my $innerwidth=$width-20;
                   8523:     $content=&js_ready(
1.1042    www      8524:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8525:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8526:                  $content.
1.1041    www      8527:                  &end_scrollbox().
1.1075.2.42  raeburn  8528:                  &end_page()
1.1041    www      8529:              );
                   8530:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8531: }
                   8532: 
                   8533: sub modal_adhoc_window {
                   8534:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8535:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8536:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8537: }
                   8538: 
                   8539: sub modal_adhoc_launch {
                   8540:     my ($funcname,$width,$height,$content)=@_;
                   8541:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8542: <script type="text/javascript">
                   8543: // <![CDATA[
                   8544: $funcname();
                   8545: // ]]>
                   8546: </script>
                   8547: ENDLAUNCH
                   8548: }
                   8549: 
                   8550: sub modal_adhoc_close {
                   8551:     return (<<ENDCLOSE);
                   8552: <script type="text/javascript">
                   8553: // <![CDATA[
                   8554: modalWindow.close();
                   8555: // ]]>
                   8556: </script>
                   8557: ENDCLOSE
                   8558: }
                   8559: 
1.1038    www      8560: sub togglebox_script {
                   8561:    return(<<ENDTOGGLE);
                   8562: <script type="text/javascript"> 
                   8563: // <![CDATA[
                   8564: function LCtoggleDisplay(id,hidetext,showtext) {
                   8565:    link = document.getElementById(id + "link").childNodes[0];
                   8566:    with (document.getElementById(id).style) {
                   8567:       if (display == "none" ) {
                   8568:           display = "inline";
                   8569:           link.nodeValue = hidetext;
                   8570:         } else {
                   8571:           display = "none";
                   8572:           link.nodeValue = showtext;
                   8573:        }
                   8574:    }
                   8575: }
                   8576: // ]]>
                   8577: </script>
                   8578: ENDTOGGLE
                   8579: }
                   8580: 
1.1039    www      8581: sub start_togglebox {
                   8582:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8583:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8584:     unless ($showtext) { $showtext=&mt('show'); }
                   8585:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8586:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8587:     return &start_data_table().
                   8588:            &start_data_table_header_row().
                   8589:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8590:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8591:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8592:            &end_data_table_header_row().
                   8593:            '<tr id="'.$id.'" style="display:none""><td>';
                   8594: }
                   8595: 
                   8596: sub end_togglebox {
                   8597:     return '</td></tr>'.&end_data_table();
                   8598: }
                   8599: 
1.1041    www      8600: sub LCprogressbar_script {
1.1075.2.130  raeburn  8601:    my ($id,$number_to_do)=@_;
                   8602:    if ($number_to_do) {
                   8603:        return(<<ENDPROGRESS);
1.1041    www      8604: <script type="text/javascript">
                   8605: // <![CDATA[
1.1045    www      8606: \$('#progressbar$id').progressbar({
1.1041    www      8607:   value: 0,
                   8608:   change: function(event, ui) {
                   8609:     var newVal = \$(this).progressbar('option', 'value');
                   8610:     \$('.pblabel', this).text(LCprogressTxt);
                   8611:   }
                   8612: });
                   8613: // ]]>
                   8614: </script>
                   8615: ENDPROGRESS
1.1075.2.130  raeburn  8616:    } else {
                   8617:        return(<<ENDPROGRESS);
                   8618: <script type="text/javascript">
                   8619: // <![CDATA[
                   8620: \$('#progressbar$id').progressbar({
                   8621:   value: false,
                   8622:   create: function(event, ui) {
                   8623:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8624:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8625:   }
                   8626: });
                   8627: // ]]>
                   8628: </script>
                   8629: ENDPROGRESS
                   8630:    }
1.1041    www      8631: }
                   8632: 
                   8633: sub LCprogressbarUpdate_script {
                   8634:    return(<<ENDPROGRESSUPDATE);
                   8635: <style type="text/css">
                   8636: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8637: .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      8638: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8639: </style>
                   8640: <script type="text/javascript">
                   8641: // <![CDATA[
1.1045    www      8642: var LCprogressTxt='---';
                   8643: 
1.1075.2.130  raeburn  8644: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8645:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8646:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8647:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8648:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8649:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8650:    } else {
                   8651:        \$('#progressbar'+id).progressbar('value',percent);
                   8652:    }
1.1041    www      8653: }
                   8654: // ]]>
                   8655: </script>
                   8656: ENDPROGRESSUPDATE
                   8657: }
                   8658: 
1.1042    www      8659: my $LClastpercent;
1.1045    www      8660: my $LCidcnt;
                   8661: my $LCcurrentid;
1.1042    www      8662: 
1.1041    www      8663: sub LCprogressbar {
1.1075.2.130  raeburn  8664:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8665:     $LClastpercent=0;
1.1045    www      8666:     $LCidcnt++;
                   8667:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8668:     my ($starting,$content);
                   8669:     if ($number_to_do) {
                   8670:         $starting=&mt('Starting');
                   8671:         $content=(<<ENDPROGBAR);
                   8672: $preamble
1.1045    www      8673:   <div id="progressbar$LCcurrentid">
1.1041    www      8674:     <span class="pblabel">$starting</span>
                   8675:   </div>
                   8676: ENDPROGBAR
1.1075.2.130  raeburn  8677:     } else {
                   8678:         $starting=&mt('Loading...');
                   8679:         $LClastpercent='false';
                   8680:         $content=(<<ENDPROGBAR);
                   8681: $preamble
                   8682:   <div id="progressbar$LCcurrentid">
                   8683:       <div class="progress-label">$starting</div>
                   8684:   </div>
                   8685: ENDPROGBAR
                   8686:     }
                   8687:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8688: }
                   8689: 
                   8690: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8691:     my ($r,$val,$text,$number_to_do)=@_;
                   8692:     if ($number_to_do) {
                   8693:         unless ($val) { 
                   8694:             if ($LClastpercent) {
                   8695:                 $val=$LClastpercent;
                   8696:             } else {
                   8697:                 $val=0;
                   8698:             }
                   8699:         }
                   8700:         if ($val<0) { $val=0; }
                   8701:         if ($val>100) { $val=0; }
                   8702:         $LClastpercent=$val;
                   8703:         unless ($text) { $text=$val.'%'; }
                   8704:     } else {
                   8705:         $val = 'false';
1.1042    www      8706:     }
1.1041    www      8707:     $text=&js_ready($text);
1.1044    www      8708:     &r_print($r,<<ENDUPDATE);
1.1041    www      8709: <script type="text/javascript">
                   8710: // <![CDATA[
1.1075.2.130  raeburn  8711: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8712: // ]]>
                   8713: </script>
                   8714: ENDUPDATE
1.1035    www      8715: }
                   8716: 
1.1042    www      8717: sub LCprogressbarClose {
                   8718:     my ($r)=@_;
                   8719:     $LClastpercent=0;
1.1044    www      8720:     &r_print($r,<<ENDCLOSE);
1.1042    www      8721: <script type="text/javascript">
                   8722: // <![CDATA[
1.1045    www      8723: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8724: // ]]>
                   8725: </script>
                   8726: ENDCLOSE
1.1044    www      8727: }
                   8728: 
                   8729: sub r_print {
                   8730:     my ($r,$to_print)=@_;
                   8731:     if ($r) {
                   8732:       $r->print($to_print);
                   8733:       $r->rflush();
                   8734:     } else {
                   8735:       print($to_print);
                   8736:     }
1.1042    www      8737: }
                   8738: 
1.320     albertel 8739: sub html_encode {
                   8740:     my ($result) = @_;
                   8741: 
1.322     albertel 8742:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8743:     
                   8744:     return $result;
                   8745: }
1.1044    www      8746: 
1.317     albertel 8747: sub js_ready {
                   8748:     my ($result) = @_;
                   8749: 
1.323     albertel 8750:     $result =~ s/[\n\r]/ /xmsg;
                   8751:     $result =~ s/\\/\\\\/xmsg;
                   8752:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8753:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8754:     
                   8755:     return $result;
                   8756: }
                   8757: 
1.315     albertel 8758: sub validate_page {
                   8759:     if (  exists($env{'internal.start_page'})
1.316     albertel 8760: 	  &&     $env{'internal.start_page'} > 1) {
                   8761: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8762: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8763: 				 $ENV{'request.filename'});
1.315     albertel 8764:     }
                   8765:     if (  exists($env{'internal.end_page'})
1.316     albertel 8766: 	  &&     $env{'internal.end_page'} > 1) {
                   8767: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8768: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8769: 				 $env{'request.filename'});
1.315     albertel 8770:     }
                   8771:     if (     exists($env{'internal.start_page'})
                   8772: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8773: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8774: 				 $env{'request.filename'});
1.315     albertel 8775:     }
                   8776:     if (   ! exists($env{'internal.start_page'})
                   8777: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8778: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8779: 				 $env{'request.filename'});
1.315     albertel 8780:     }
1.306     albertel 8781: }
1.315     albertel 8782: 
1.996     www      8783: 
                   8784: sub start_scrollbox {
1.1075.2.56  raeburn  8785:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8786:     unless ($outerwidth) { $outerwidth='520px'; }
                   8787:     unless ($width) { $width='500px'; }
                   8788:     unless ($height) { $height='200px'; }
1.1075    raeburn  8789:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8790:     if ($id ne '') {
1.1075.2.42  raeburn  8791:         $table_id = ' id="table_'.$id.'"';
                   8792:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8793:     }
1.1075    raeburn  8794:     if ($bgcolor ne '') {
                   8795:         $tdcol = "background-color: $bgcolor;";
                   8796:     }
1.1075.2.42  raeburn  8797:     my $nicescroll_js;
                   8798:     if ($env{'browser.mobile'}) {
                   8799:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8800:     }
1.1075    raeburn  8801:     return <<"END";
1.1075.2.42  raeburn  8802: $nicescroll_js
                   8803: 
                   8804: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8805: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8806: END
1.996     www      8807: }
                   8808: 
                   8809: sub end_scrollbox {
1.1036    www      8810:     return '</div></td></tr></table>';
1.996     www      8811: }
                   8812: 
1.1075.2.42  raeburn  8813: sub nicescroll_javascript {
                   8814:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8815:     my %options;
                   8816:     if (ref($cursor) eq 'HASH') {
                   8817:         %options = %{$cursor};
                   8818:     }
                   8819:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8820:         $options{'railalign'} = 'left';
                   8821:     }
                   8822:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8823:         my $function  = &get_users_function();
                   8824:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8825:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8826:             $options{'cursorcolor'} = '#00F';
                   8827:         }
                   8828:     }
                   8829:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8830:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8831:             $options{'cursoropacity'}='1.0';
                   8832:         }
                   8833:     } else {
                   8834:         $options{'cursoropacity'}='1.0';
                   8835:     }
                   8836:     if ($options{'cursorfixedheight'} eq 'none') {
                   8837:         delete($options{'cursorfixedheight'});
                   8838:     } else {
                   8839:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8840:     }
                   8841:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8842:         delete($options{'railoffset'});
                   8843:     }
                   8844:     my @niceoptions;
                   8845:     while (my($key,$value) = each(%options)) {
                   8846:         if ($value =~ /^\{.+\}$/) {
                   8847:             push(@niceoptions,$key.':'.$value);
                   8848:         } else {
                   8849:             push(@niceoptions,$key.':"'.$value.'"');
                   8850:         }
                   8851:     }
                   8852:     my $nicescroll_js = '
                   8853: $(document).ready(
                   8854:       function() {
                   8855:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8856:       }
                   8857: );
                   8858: ';
                   8859:     if ($framecheck) {
                   8860:         $nicescroll_js .= '
                   8861: function expand_div(caller) {
                   8862:     if (top === self) {
                   8863:         document.getElementById("'.$id.'").style.width = "auto";
                   8864:         document.getElementById("'.$id.'").style.height = "auto";
                   8865:     } else {
                   8866:         try {
                   8867:             if (parent.frames) {
                   8868:                 if (parent.frames.length > 1) {
                   8869:                     var framesrc = parent.frames[1].location.href;
                   8870:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8871:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8872:                         document.getElementById("'.$id.'").style.width = "auto";
                   8873:                         document.getElementById("'.$id.'").style.height = "auto";
                   8874:                     }
                   8875:                 }
                   8876:             }
                   8877:         } catch (e) {
                   8878:             return;
                   8879:         }
                   8880:     }
                   8881:     return;
                   8882: }
                   8883: ';
                   8884:     }
                   8885:     if ($needjsready) {
                   8886:         $nicescroll_js = '
                   8887: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8888:     } else {
                   8889:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8890:     }
                   8891:     return $nicescroll_js;
                   8892: }
                   8893: 
1.318     albertel 8894: sub simple_error_page {
1.1075.2.49  raeburn  8895:     my ($r,$title,$msg,$args) = @_;
                   8896:     if (ref($args) eq 'HASH') {
                   8897:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8898:     } else {
                   8899:         $msg = &mt($msg);
                   8900:     }
                   8901: 
1.318     albertel 8902:     my $page =
                   8903: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8904: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8905: 	&Apache::loncommon::end_page();
                   8906:     if (ref($r)) {
                   8907: 	$r->print($page);
1.327     albertel 8908: 	return;
1.318     albertel 8909:     }
                   8910:     return $page;
                   8911: }
1.347     albertel 8912: 
                   8913: {
1.610     albertel 8914:     my @row_count;
1.961     onken    8915: 
                   8916:     sub start_data_table_count {
                   8917:         unshift(@row_count, 0);
                   8918:         return;
                   8919:     }
                   8920: 
                   8921:     sub end_data_table_count {
                   8922:         shift(@row_count);
                   8923:         return;
                   8924:     }
                   8925: 
1.347     albertel 8926:     sub start_data_table {
1.1018    raeburn  8927: 	my ($add_class,$id) = @_;
1.422     albertel 8928: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8929:         my $table_id;
                   8930:         if (defined($id)) {
                   8931:             $table_id = ' id="'.$id.'"';
                   8932:         }
1.961     onken    8933: 	&start_data_table_count();
1.1018    raeburn  8934: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8935:     }
                   8936: 
                   8937:     sub end_data_table {
1.961     onken    8938: 	&end_data_table_count();
1.389     albertel 8939: 	return '</table>'."\n";;
1.347     albertel 8940:     }
                   8941: 
                   8942:     sub start_data_table_row {
1.974     wenzelju 8943: 	my ($add_class, $id) = @_;
1.610     albertel 8944: 	$row_count[0]++;
                   8945: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8946: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8947:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8948:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8949:     }
1.471     banghart 8950:     
                   8951:     sub continue_data_table_row {
1.974     wenzelju 8952: 	my ($add_class, $id) = @_;
1.610     albertel 8953: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8954: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8955:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8956:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8957:     }
1.347     albertel 8958: 
                   8959:     sub end_data_table_row {
1.389     albertel 8960: 	return '</tr>'."\n";;
1.347     albertel 8961:     }
1.367     www      8962: 
1.421     albertel 8963:     sub start_data_table_empty_row {
1.707     bisitz   8964: #	$row_count[0]++;
1.421     albertel 8965: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8966:     }
                   8967: 
                   8968:     sub end_data_table_empty_row {
                   8969: 	return '</tr>'."\n";;
                   8970:     }
                   8971: 
1.367     www      8972:     sub start_data_table_header_row {
1.389     albertel 8973: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8974:     }
                   8975: 
                   8976:     sub end_data_table_header_row {
1.389     albertel 8977: 	return '</tr>'."\n";;
1.367     www      8978:     }
1.890     droeschl 8979: 
                   8980:     sub data_table_caption {
                   8981:         my $caption = shift;
                   8982:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8983:     }
1.347     albertel 8984: }
                   8985: 
1.548     albertel 8986: =pod
                   8987: 
                   8988: =item * &inhibit_menu_check($arg)
                   8989: 
                   8990: Checks for a inhibitmenu state and generates output to preserve it
                   8991: 
                   8992: Inputs:         $arg - can be any of
                   8993:                      - undef - in which case the return value is a string 
                   8994:                                to add  into arguments list of a uri
                   8995:                      - 'input' - in which case the return value is a HTML
                   8996:                                  <form> <input> field of type hidden to
                   8997:                                  preserve the value
                   8998:                      - a url - in which case the return value is the url with
                   8999:                                the neccesary cgi args added to preserve the
                   9000:                                inhibitmenu state
                   9001:                      - a ref to a url - no return value, but the string is
                   9002:                                         updated to include the neccessary cgi
                   9003:                                         args to preserve the inhibitmenu state
                   9004: 
                   9005: =cut
                   9006: 
                   9007: sub inhibit_menu_check {
                   9008:     my ($arg) = @_;
                   9009:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9010:     if ($arg eq 'input') {
                   9011: 	if ($env{'form.inhibitmenu'}) {
                   9012: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9013: 	} else {
                   9014: 	    return
                   9015: 	}
                   9016:     }
                   9017:     if ($env{'form.inhibitmenu'}) {
                   9018: 	if (ref($arg)) {
                   9019: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9020: 	} elsif ($arg eq '') {
                   9021: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9022: 	} else {
                   9023: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9024: 	}
                   9025:     }
                   9026:     if (!ref($arg)) {
                   9027: 	return $arg;
                   9028:     }
                   9029: }
                   9030: 
1.251     albertel 9031: ###############################################
1.182     matthew  9032: 
                   9033: =pod
                   9034: 
1.549     albertel 9035: =back
                   9036: 
                   9037: =head1 User Information Routines
                   9038: 
                   9039: =over 4
                   9040: 
1.405     albertel 9041: =item * &get_users_function()
1.182     matthew  9042: 
                   9043: Used by &bodytag to determine the current users primary role.
                   9044: Returns either 'student','coordinator','admin', or 'author'.
                   9045: 
                   9046: =cut
                   9047: 
                   9048: ###############################################
                   9049: sub get_users_function {
1.815     tempelho 9050:     my $function = 'norole';
1.818     tempelho 9051:     if ($env{'request.role'}=~/^(st)/) {
                   9052:         $function='student';
                   9053:     }
1.907     raeburn  9054:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9055:         $function='coordinator';
                   9056:     }
1.258     albertel 9057:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9058:         $function='admin';
                   9059:     }
1.826     bisitz   9060:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9061:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9062:         $function='author';
                   9063:     }
                   9064:     return $function;
1.54      www      9065: }
1.99      www      9066: 
                   9067: ###############################################
                   9068: 
1.233     raeburn  9069: =pod
                   9070: 
1.821     raeburn  9071: =item * &show_course()
                   9072: 
                   9073: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9074: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9075: 
                   9076: Inputs:
                   9077: None
                   9078: 
                   9079: Outputs:
                   9080: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9081: 
                   9082: =cut
                   9083: 
                   9084: ###############################################
                   9085: sub show_course {
                   9086:     my $course = !$env{'user.adv'};
                   9087:     if (!$env{'user.adv'}) {
                   9088:         foreach my $env (keys(%env)) {
                   9089:             next if ($env !~ m/^user\.priv\./);
                   9090:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9091:                 $course = 0;
                   9092:                 last;
                   9093:             }
                   9094:         }
                   9095:     }
                   9096:     return $course;
                   9097: }
                   9098: 
                   9099: ###############################################
                   9100: 
                   9101: =pod
                   9102: 
1.542     raeburn  9103: =item * &check_user_status()
1.274     raeburn  9104: 
                   9105: Determines current status of supplied role for a
                   9106: specific user. Roles can be active, previous or future.
                   9107: 
                   9108: Inputs: 
                   9109: user's domain, user's username, course's domain,
1.375     raeburn  9110: course's number, optional section ID.
1.274     raeburn  9111: 
                   9112: Outputs:
                   9113: role status: active, previous or future. 
                   9114: 
                   9115: =cut
                   9116: 
                   9117: sub check_user_status {
1.412     raeburn  9118:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9119:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9120:     my @uroles = keys(%userinfo);
1.274     raeburn  9121:     my $srchstr;
                   9122:     my $active_chk = 'none';
1.412     raeburn  9123:     my $now = time;
1.274     raeburn  9124:     if (@uroles > 0) {
1.908     raeburn  9125:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9126:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9127:         } else {
1.412     raeburn  9128:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9129:         }
                   9130:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9131:             my $role_end = 0;
                   9132:             my $role_start = 0;
                   9133:             $active_chk = 'active';
1.412     raeburn  9134:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9135:                 $role_end = $1;
                   9136:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9137:                     $role_start = $1;
1.274     raeburn  9138:                 }
                   9139:             }
                   9140:             if ($role_start > 0) {
1.412     raeburn  9141:                 if ($now < $role_start) {
1.274     raeburn  9142:                     $active_chk = 'future';
                   9143:                 }
                   9144:             }
                   9145:             if ($role_end > 0) {
1.412     raeburn  9146:                 if ($now > $role_end) {
1.274     raeburn  9147:                     $active_chk = 'previous';
                   9148:                 }
                   9149:             }
                   9150:         }
                   9151:     }
                   9152:     return $active_chk;
                   9153: }
                   9154: 
                   9155: ###############################################
                   9156: 
                   9157: =pod
                   9158: 
1.405     albertel 9159: =item * &get_sections()
1.233     raeburn  9160: 
                   9161: Determines all the sections for a course including
                   9162: sections with students and sections containing other roles.
1.419     raeburn  9163: Incoming parameters: 
                   9164: 
                   9165: 1. domain
                   9166: 2. course number 
                   9167: 3. reference to array containing roles for which sections should 
                   9168: be gathered (optional).
                   9169: 4. reference to array containing status types for which sections 
                   9170: should be gathered (optional).
                   9171: 
                   9172: If the third argument is undefined, sections are gathered for any role. 
                   9173: If the fourth argument is undefined, sections are gathered for any status.
                   9174: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9175:  
1.374     raeburn  9176: Returns section hash (keys are section IDs, values are
                   9177: number of users in each section), subject to the
1.419     raeburn  9178: optional roles filter, optional status filter 
1.233     raeburn  9179: 
                   9180: =cut
                   9181: 
                   9182: ###############################################
                   9183: sub get_sections {
1.419     raeburn  9184:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9185:     if (!defined($cdom) || !defined($cnum)) {
                   9186:         my $cid =  $env{'request.course.id'};
                   9187: 
                   9188: 	return if (!defined($cid));
                   9189: 
                   9190:         $cdom = $env{'course.'.$cid.'.domain'};
                   9191:         $cnum = $env{'course.'.$cid.'.num'};
                   9192:     }
                   9193: 
                   9194:     my %sectioncount;
1.419     raeburn  9195:     my $now = time;
1.240     albertel 9196: 
1.1075.2.33  raeburn  9197:     my $check_students = 1;
                   9198:     my $only_students = 0;
                   9199:     if (ref($possible_roles) eq 'ARRAY') {
                   9200:         if (grep(/^st$/,@{$possible_roles})) {
                   9201:             if (@{$possible_roles} == 1) {
                   9202:                 $only_students = 1;
                   9203:             }
                   9204:         } else {
                   9205:             $check_students = 0;
                   9206:         }
                   9207:     }
                   9208: 
                   9209:     if ($check_students) {
1.276     albertel 9210: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9211: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9212: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9213:         my $start_index = &Apache::loncoursedata::CL_START();
                   9214:         my $end_index = &Apache::loncoursedata::CL_END();
                   9215:         my $status;
1.366     albertel 9216: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9217: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9218: 				                     $data->[$status_index],
                   9219:                                                      $data->[$start_index],
                   9220:                                                      $data->[$end_index]);
                   9221:             if ($stu_status eq 'Active') {
                   9222:                 $status = 'active';
                   9223:             } elsif ($end < $now) {
                   9224:                 $status = 'previous';
                   9225:             } elsif ($start > $now) {
                   9226:                 $status = 'future';
                   9227:             } 
                   9228: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9229:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9230:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9231: 		    $sectioncount{$section}++;
                   9232:                 }
1.240     albertel 9233: 	    }
                   9234: 	}
                   9235:     }
1.1075.2.33  raeburn  9236:     if ($only_students) {
                   9237:         return %sectioncount;
                   9238:     }
1.240     albertel 9239:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9240:     foreach my $user (sort(keys(%courseroles))) {
                   9241: 	if ($user !~ /^(\w{2})/) { next; }
                   9242: 	my ($role) = ($user =~ /^(\w{2})/);
                   9243: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9244: 	my ($section,$status);
1.240     albertel 9245: 	if ($role eq 'cr' &&
                   9246: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9247: 	    $section=$1;
                   9248: 	}
                   9249: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9250: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9251:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9252:         if ($end == -1 && $start == -1) {
                   9253:             next; #deleted role
                   9254:         }
                   9255:         if (!defined($possible_status)) { 
                   9256:             $sectioncount{$section}++;
                   9257:         } else {
                   9258:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9259:                 $status = 'active';
                   9260:             } elsif ($end < $now) {
                   9261:                 $status = 'future';
                   9262:             } elsif ($start > $now) {
                   9263:                 $status = 'previous';
                   9264:             }
                   9265:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9266:                 $sectioncount{$section}++;
                   9267:             }
                   9268:         }
1.233     raeburn  9269:     }
1.366     albertel 9270:     return %sectioncount;
1.233     raeburn  9271: }
                   9272: 
1.274     raeburn  9273: ###############################################
1.294     raeburn  9274: 
                   9275: =pod
1.405     albertel 9276: 
                   9277: =item * &get_course_users()
                   9278: 
1.275     raeburn  9279: Retrieves usernames:domains for users in the specified course
                   9280: with specific role(s), and access status. 
                   9281: 
                   9282: Incoming parameters:
1.277     albertel 9283: 1. course domain
                   9284: 2. course number
                   9285: 3. access status: users must have - either active, 
1.275     raeburn  9286: previous, future, or all.
1.277     albertel 9287: 4. reference to array of permissible roles
1.288     raeburn  9288: 5. reference to array of section restrictions (optional)
                   9289: 6. reference to results object (hash of hashes).
                   9290: 7. reference to optional userdata hash
1.609     raeburn  9291: 8. reference to optional statushash
1.630     raeburn  9292: 9. flag if privileged users (except those set to unhide in
                   9293:    course settings) should be excluded    
1.609     raeburn  9294: Keys of top level results hash are roles.
1.275     raeburn  9295: Keys of inner hashes are username:domain, with 
                   9296: values set to access type.
1.288     raeburn  9297: Optional userdata hash returns an array with arguments in the 
                   9298: same order as loncoursedata::get_classlist() for student data.
                   9299: 
1.609     raeburn  9300: Optional statushash returns
                   9301: 
1.288     raeburn  9302: Entries for end, start, section and status are blank because
                   9303: of the possibility of multiple values for non-student roles.
                   9304: 
1.275     raeburn  9305: =cut
1.405     albertel 9306: 
1.275     raeburn  9307: ###############################################
1.405     albertel 9308: 
1.275     raeburn  9309: sub get_course_users {
1.630     raeburn  9310:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9311:     my %idx = ();
1.419     raeburn  9312:     my %seclists;
1.288     raeburn  9313: 
                   9314:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9315:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9316:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9317:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9318:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9319:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9320:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9321:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9322: 
1.290     albertel 9323:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9324:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9325:         my $now = time;
1.277     albertel 9326:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9327:             my $match = 0;
1.412     raeburn  9328:             my $secmatch = 0;
1.419     raeburn  9329:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9330:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9331:             if ($section eq '') {
                   9332:                 $section = 'none';
                   9333:             }
1.291     albertel 9334:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9335:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9336:                     $secmatch = 1;
                   9337:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9338:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9339:                         $secmatch = 1;
                   9340:                     }
                   9341:                 } else {  
1.419     raeburn  9342: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9343: 		        $secmatch = 1;
                   9344:                     }
1.290     albertel 9345: 		}
1.412     raeburn  9346:                 if (!$secmatch) {
                   9347:                     next;
                   9348:                 }
1.419     raeburn  9349:             }
1.275     raeburn  9350:             if (defined($$types{'active'})) {
1.288     raeburn  9351:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9352:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9353:                     $match = 1;
1.275     raeburn  9354:                 }
                   9355:             }
                   9356:             if (defined($$types{'previous'})) {
1.609     raeburn  9357:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9358:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9359:                     $match = 1;
1.275     raeburn  9360:                 }
                   9361:             }
                   9362:             if (defined($$types{'future'})) {
1.609     raeburn  9363:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9364:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9365:                     $match = 1;
1.275     raeburn  9366:                 }
                   9367:             }
1.609     raeburn  9368:             if ($match) {
                   9369:                 push(@{$seclists{$student}},$section);
                   9370:                 if (ref($userdata) eq 'HASH') {
                   9371:                     $$userdata{$student} = $$classlist{$student};
                   9372:                 }
                   9373:                 if (ref($statushash) eq 'HASH') {
                   9374:                     $statushash->{$student}{'st'}{$section} = $status;
                   9375:                 }
1.288     raeburn  9376:             }
1.275     raeburn  9377:         }
                   9378:     }
1.412     raeburn  9379:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9380:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9381:         my $now = time;
1.609     raeburn  9382:         my %displaystatus = ( previous => 'Expired',
                   9383:                               active   => 'Active',
                   9384:                               future   => 'Future',
                   9385:                             );
1.1075.2.36  raeburn  9386:         my (%nothide,@possdoms);
1.630     raeburn  9387:         if ($hidepriv) {
                   9388:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9389:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9390:                 if ($user !~ /:/) {
                   9391:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9392:                 } else {
                   9393:                     $nothide{$user} = 1;
                   9394:                 }
                   9395:             }
1.1075.2.36  raeburn  9396:             my @possdoms = ($cdom);
                   9397:             if ($coursehash{'checkforpriv'}) {
                   9398:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9399:             }
1.630     raeburn  9400:         }
1.439     raeburn  9401:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9402:             my $match = 0;
1.412     raeburn  9403:             my $secmatch = 0;
1.439     raeburn  9404:             my $status;
1.412     raeburn  9405:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9406:             $user =~ s/:$//;
1.439     raeburn  9407:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9408:             if ($end == -1 || $start == -1) {
                   9409:                 next;
                   9410:             }
                   9411:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9412:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9413:                 my ($uname,$udom) = split(/:/,$user);
                   9414:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9415:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9416:                         $secmatch = 1;
                   9417:                     } elsif ($usec eq '') {
1.420     albertel 9418:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9419:                             $secmatch = 1;
                   9420:                         }
                   9421:                     } else {
                   9422:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9423:                             $secmatch = 1;
                   9424:                         }
                   9425:                     }
                   9426:                     if (!$secmatch) {
                   9427:                         next;
                   9428:                     }
1.288     raeburn  9429:                 }
1.419     raeburn  9430:                 if ($usec eq '') {
                   9431:                     $usec = 'none';
                   9432:                 }
1.275     raeburn  9433:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9434:                     if ($hidepriv) {
1.1075.2.36  raeburn  9435:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9436:                             (!$nothide{$uname.':'.$udom})) {
                   9437:                             next;
                   9438:                         }
                   9439:                     }
1.503     raeburn  9440:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9441:                         $status = 'previous';
                   9442:                     } elsif ($start > $now) {
                   9443:                         $status = 'future';
                   9444:                     } else {
                   9445:                         $status = 'active';
                   9446:                     }
1.277     albertel 9447:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9448:                         if ($status eq $type) {
1.420     albertel 9449:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9450:                                 push(@{$$users{$role}{$user}},$type);
                   9451:                             }
1.288     raeburn  9452:                             $match = 1;
                   9453:                         }
                   9454:                     }
1.419     raeburn  9455:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9456:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9457: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9458:                         }
1.420     albertel 9459:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9460:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9461:                         }
1.609     raeburn  9462:                         if (ref($statushash) eq 'HASH') {
                   9463:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9464:                         }
1.275     raeburn  9465:                     }
                   9466:                 }
                   9467:             }
                   9468:         }
1.290     albertel 9469:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9470:             if ((defined($cdom)) && (defined($cnum))) {
                   9471:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9472:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9473:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9474:                     next if ($owner eq '');
                   9475:                     my ($ownername,$ownerdom);
                   9476:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9477:                         $ownername = $1;
                   9478:                         $ownerdom = $2;
                   9479:                     } else {
                   9480:                         $ownername = $owner;
                   9481:                         $ownerdom = $cdom;
                   9482:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9483:                     }
                   9484:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9485:                     if (defined($userdata) && 
1.609     raeburn  9486: 			!exists($$userdata{$owner})) {
                   9487: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9488:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9489:                             push(@{$seclists{$owner}},'none');
                   9490:                         }
                   9491:                         if (ref($statushash) eq 'HASH') {
                   9492:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9493:                         }
1.290     albertel 9494: 		    }
1.279     raeburn  9495:                 }
                   9496:             }
                   9497:         }
1.419     raeburn  9498:         foreach my $user (keys(%seclists)) {
                   9499:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9500:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9501:         }
1.275     raeburn  9502:     }
                   9503:     return;
                   9504: }
                   9505: 
1.288     raeburn  9506: sub get_user_info {
                   9507:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9508:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9509: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9510:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9511:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9512:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9513:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9514:     return;
                   9515: }
1.275     raeburn  9516: 
1.472     raeburn  9517: ###############################################
                   9518: 
                   9519: =pod
                   9520: 
                   9521: =item * &get_user_quota()
                   9522: 
1.1075.2.41  raeburn  9523: Retrieves quota assigned for storage of user files.
                   9524: Default is to report quota for portfolio files.
1.472     raeburn  9525: 
                   9526: Incoming parameters:
                   9527: 1. user's username
                   9528: 2. user's domain
1.1075.2.41  raeburn  9529: 3. quota name - portfolio, author, or course
                   9530:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9531: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9532:    course
1.472     raeburn  9533: 
                   9534: Returns:
1.1075.2.58  raeburn  9535: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9536: 2. (Optional) Type of setting: custom or default
                   9537:    (individually assigned or default for user's 
                   9538:    institutional status).
                   9539: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9540:    or student - types as defined in localenroll::inst_usertypes 
                   9541:    for user's domain, which determines default quota for user.
                   9542: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9543: 
                   9544: If a value has been stored in the user's environment, 
1.536     raeburn  9545: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9546: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9547: 
                   9548: =cut
                   9549: 
                   9550: ###############################################
                   9551: 
                   9552: 
                   9553: sub get_user_quota {
1.1075.2.42  raeburn  9554:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9555:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9556:     if (!defined($udom)) {
                   9557:         $udom = $env{'user.domain'};
                   9558:     }
                   9559:     if (!defined($uname)) {
                   9560:         $uname = $env{'user.name'};
                   9561:     }
                   9562:     if (($udom eq '' || $uname eq '') ||
                   9563:         ($udom eq 'public') && ($uname eq 'public')) {
                   9564:         $quota = 0;
1.536     raeburn  9565:         $quotatype = 'default';
                   9566:         $defquota = 0; 
1.472     raeburn  9567:     } else {
1.536     raeburn  9568:         my $inststatus;
1.1075.2.41  raeburn  9569:         if ($quotaname eq 'course') {
                   9570:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9571:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9572:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9573:             } else {
                   9574:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9575:                 $quota = $cenv{'internal.uploadquota'};
                   9576:             }
1.536     raeburn  9577:         } else {
1.1075.2.41  raeburn  9578:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9579:                 if ($quotaname eq 'author') {
                   9580:                     $quota = $env{'environment.authorquota'};
                   9581:                 } else {
                   9582:                     $quota = $env{'environment.portfolioquota'};
                   9583:                 }
                   9584:                 $inststatus = $env{'environment.inststatus'};
                   9585:             } else {
                   9586:                 my %userenv = 
                   9587:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9588:                                          'authorquota','inststatus'],$udom,$uname);
                   9589:                 my ($tmp) = keys(%userenv);
                   9590:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9591:                     if ($quotaname eq 'author') {
                   9592:                         $quota = $userenv{'authorquota'};
                   9593:                     } else {
                   9594:                         $quota = $userenv{'portfolioquota'};
                   9595:                     }
                   9596:                     $inststatus = $userenv{'inststatus'};
                   9597:                 } else {
                   9598:                     undef(%userenv);
                   9599:                 }
                   9600:             }
                   9601:         }
                   9602:         if ($quota eq '' || wantarray) {
                   9603:             if ($quotaname eq 'course') {
                   9604:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9605:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9606:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9607:                     $defquota = $domdefs{$crstype.'quota'};
                   9608:                 }
                   9609:                 if ($defquota eq '') {
                   9610:                     $defquota = 500;
                   9611:                 }
1.1075.2.41  raeburn  9612:             } else {
                   9613:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9614:             }
                   9615:             if ($quota eq '') {
                   9616:                 $quota = $defquota;
                   9617:                 $quotatype = 'default';
                   9618:             } else {
                   9619:                 $quotatype = 'custom';
                   9620:             }
1.472     raeburn  9621:         }
                   9622:     }
1.536     raeburn  9623:     if (wantarray) {
                   9624:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9625:     } else {
                   9626:         return $quota;
                   9627:     }
1.472     raeburn  9628: }
                   9629: 
                   9630: ###############################################
                   9631: 
                   9632: =pod
                   9633: 
                   9634: =item * &default_quota()
                   9635: 
1.536     raeburn  9636: Retrieves default quota assigned for storage of user portfolio files,
                   9637: given an (optional) user's institutional status.
1.472     raeburn  9638: 
                   9639: Incoming parameters:
1.1075.2.42  raeburn  9640: 
1.472     raeburn  9641: 1. domain
1.536     raeburn  9642: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9643:    status types (e.g., faculty, staff, student etc.)
                   9644:    which apply to the user for whom the default is being retrieved.
                   9645:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9646:    default quota will be returned.
                   9647: 3.  quota name - portfolio, author, or course
                   9648:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9649: 
                   9650: Returns:
1.1075.2.42  raeburn  9651: 
1.1075.2.58  raeburn  9652: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9653: 2. (Optional) institutional type which determined the value of the
                   9654:    default quota.
1.472     raeburn  9655: 
                   9656: If a value has been stored in the domain's configuration db,
                   9657: it will return that, otherwise it returns 20 (for backwards 
                   9658: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9659: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9660: 
1.536     raeburn  9661: If the user's status includes multiple types (e.g., staff and student),
                   9662: the largest default quota which applies to the user determines the
                   9663: default quota returned.
                   9664: 
1.472     raeburn  9665: =cut
                   9666: 
                   9667: ###############################################
                   9668: 
                   9669: 
                   9670: sub default_quota {
1.1075.2.41  raeburn  9671:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9672:     my ($defquota,$settingstatus);
                   9673:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9674:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9675:     my $key = 'defaultquota';
                   9676:     if ($quotaname eq 'author') {
                   9677:         $key = 'authorquota';
                   9678:     }
1.622     raeburn  9679:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9680:         if ($inststatus ne '') {
1.765     raeburn  9681:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9682:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9683:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9684:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9685:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9686:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9687:                             $settingstatus = $item;
1.1075.2.41  raeburn  9688:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9689:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9690:                             $settingstatus = $item;
                   9691:                         }
                   9692:                     }
1.1075.2.41  raeburn  9693:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9694:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9695:                         if ($defquota eq '') {
                   9696:                             $defquota = $quotahash{'quotas'}{$item};
                   9697:                             $settingstatus = $item;
                   9698:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9699:                             $defquota = $quotahash{'quotas'}{$item};
                   9700:                             $settingstatus = $item;
                   9701:                         }
1.536     raeburn  9702:                     }
                   9703:                 }
                   9704:             }
                   9705:         }
                   9706:         if ($defquota eq '') {
1.1075.2.41  raeburn  9707:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9708:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9709:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9710:                 $defquota = $quotahash{'quotas'}{'default'};
                   9711:             }
1.536     raeburn  9712:             $settingstatus = 'default';
1.1075.2.42  raeburn  9713:             if ($defquota eq '') {
                   9714:                 if ($quotaname eq 'author') {
                   9715:                     $defquota = 500;
                   9716:                 }
                   9717:             }
1.536     raeburn  9718:         }
                   9719:     } else {
                   9720:         $settingstatus = 'default';
1.1075.2.41  raeburn  9721:         if ($quotaname eq 'author') {
                   9722:             $defquota = 500;
                   9723:         } else {
                   9724:             $defquota = 20;
                   9725:         }
1.536     raeburn  9726:     }
                   9727:     if (wantarray) {
                   9728:         return ($defquota,$settingstatus);
1.472     raeburn  9729:     } else {
1.536     raeburn  9730:         return $defquota;
1.472     raeburn  9731:     }
                   9732: }
                   9733: 
1.1075.2.41  raeburn  9734: ###############################################
                   9735: 
                   9736: =pod
                   9737: 
1.1075.2.42  raeburn  9738: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9739: 
                   9740: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9741: of existing file within authoring space will cause quota for the authoring
                   9742: space to be exceeded.
                   9743: 
                   9744: Same, if upload of a file directly to a course/community via Course Editor
                   9745: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9746: 
1.1075.2.61  raeburn  9747: Inputs: 7 
1.1075.2.42  raeburn  9748: 1. username or coursenum
1.1075.2.41  raeburn  9749: 2. domain
1.1075.2.42  raeburn  9750: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9751: 4. filename of file for which action is being requested
                   9752: 5. filesize (kB) of file
                   9753: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9754: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9755: 
                   9756: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9757:          otherwise return null.
                   9758: 
1.1075.2.42  raeburn  9759: =back
                   9760: 
1.1075.2.41  raeburn  9761: =cut
                   9762: 
1.1075.2.42  raeburn  9763: sub excess_filesize_warning {
1.1075.2.59  raeburn  9764:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9765:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9766:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9767:     if ($context eq 'author') {
                   9768:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9769:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9770:     } else {
                   9771:         foreach my $subdir ('docs','supplemental') {
                   9772:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9773:         }
                   9774:     }
1.1075.2.41  raeburn  9775:     $disk_quota = int($disk_quota * 1000);
                   9776:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9777:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9778:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9779:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9780:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9781:                             $disk_quota,$current_disk_usage).
                   9782:                '</p>';
                   9783:     }
                   9784:     return;
                   9785: }
                   9786: 
                   9787: ###############################################
                   9788: 
                   9789: 
1.384     raeburn  9790: sub get_secgrprole_info {
                   9791:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9792:     my %sections_count = &get_sections($cdom,$cnum);
                   9793:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9794:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9795:     my @groups = sort(keys(%curr_groups));
                   9796:     my $allroles = [];
                   9797:     my $rolehash;
                   9798:     my $accesshash = {
                   9799:                      active => 'Currently has access',
                   9800:                      future => 'Will have future access',
                   9801:                      previous => 'Previously had access',
                   9802:                   };
                   9803:     if ($needroles) {
                   9804:         $rolehash = {'all' => 'all'};
1.385     albertel 9805:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9806: 	if (&Apache::lonnet::error(%user_roles)) {
                   9807: 	    undef(%user_roles);
                   9808: 	}
                   9809:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9810:             my ($role)=split(/\:/,$item,2);
                   9811:             if ($role eq 'cr') { next; }
                   9812:             if ($role =~ /^cr/) {
                   9813:                 $$rolehash{$role} = (split('/',$role))[3];
                   9814:             } else {
                   9815:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9816:             }
                   9817:         }
                   9818:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9819:             push(@{$allroles},$key);
                   9820:         }
                   9821:         push (@{$allroles},'st');
                   9822:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9823:     }
                   9824:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9825: }
                   9826: 
1.555     raeburn  9827: sub user_picker {
1.1075.2.127  raeburn  9828:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9829:     my $currdom = $dom;
1.1075.2.114  raeburn  9830:     my @alldoms = &Apache::lonnet::all_domains();
                   9831:     if (@alldoms == 1) {
                   9832:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9833:                                                ['directorysrch'],$alldoms[0]);
                   9834:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9835:         my $showdom = $domdesc;
                   9836:         if ($showdom eq '') {
                   9837:             $showdom = $dom;
                   9838:         }
                   9839:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9840:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9841:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9842:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9843:             }
                   9844:         }
                   9845:     }
1.555     raeburn  9846:     my %curr_selected = (
                   9847:                         srchin => 'dom',
1.580     raeburn  9848:                         srchby => 'lastname',
1.555     raeburn  9849:                       );
                   9850:     my $srchterm;
1.625     raeburn  9851:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9852:         if ($srch->{'srchby'} ne '') {
                   9853:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9854:         }
                   9855:         if ($srch->{'srchin'} ne '') {
                   9856:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9857:         }
                   9858:         if ($srch->{'srchtype'} ne '') {
                   9859:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9860:         }
                   9861:         if ($srch->{'srchdomain'} ne '') {
                   9862:             $currdom = $srch->{'srchdomain'};
                   9863:         }
                   9864:         $srchterm = $srch->{'srchterm'};
                   9865:     }
1.1075.2.98  raeburn  9866:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9867:                     'usr'       => 'Search criteria',
1.563     raeburn  9868:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9869:                     'uname'     => 'username',
                   9870:                     'lastname'  => 'last name',
1.555     raeburn  9871:                     'lastfirst' => 'last name, first name',
1.558     albertel 9872:                     'crs'       => 'in this course',
1.576     raeburn  9873:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9874:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9875:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9876:                     'exact'     => 'is',
                   9877:                     'contains'  => 'contains',
1.569     raeburn  9878:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9879:                                        );
                   9880:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9881:                     'youm'      => "You must include some text to search for.",
                   9882:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9883:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9884:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9885:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9886:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9887:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9888:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9889:                                        );
1.1075.2.98  raeburn  9890:     &html_escape(\%html_lt);
                   9891:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9892:     my $domform;
1.1075.2.126  raeburn  9893:     my $allow_blank = 1;
1.1075.2.115  raeburn  9894:     if ($fixeddom) {
1.1075.2.126  raeburn  9895:         $allow_blank = 0;
                   9896:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9897:     } else {
1.1075.2.126  raeburn  9898:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9899:     }
1.563     raeburn  9900:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9901: 
                   9902:     my @srchins = ('crs','dom','alc','instd');
                   9903: 
                   9904:     foreach my $option (@srchins) {
                   9905:         # FIXME 'alc' option unavailable until 
                   9906:         #       loncreateuser::print_user_query_page()
                   9907:         #       has been completed.
                   9908:         next if ($option eq 'alc');
1.880     raeburn  9909:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9910:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9911:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9912:         if ($curr_selected{'srchin'} eq $option) {
                   9913:             $srchinsel .= ' 
1.1075.2.98  raeburn  9914:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9915:         } else {
                   9916:             $srchinsel .= '
1.1075.2.98  raeburn  9917:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9918:         }
1.555     raeburn  9919:     }
1.563     raeburn  9920:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9921: 
                   9922:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9923:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9924:         if ($curr_selected{'srchby'} eq $option) {
                   9925:             $srchbysel .= '
1.1075.2.98  raeburn  9926:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9927:         } else {
                   9928:             $srchbysel .= '
1.1075.2.98  raeburn  9929:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9930:          }
                   9931:     }
                   9932:     $srchbysel .= "\n  </select>\n";
                   9933: 
                   9934:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9935:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9936:         if ($curr_selected{'srchtype'} eq $option) {
                   9937:             $srchtypesel .= '
1.1075.2.98  raeburn  9938:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9939:         } else {
                   9940:             $srchtypesel .= '
1.1075.2.98  raeburn  9941:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9942:         }
                   9943:     }
                   9944:     $srchtypesel .= "\n  </select>\n";
                   9945: 
1.558     albertel 9946:     my ($newuserscript,$new_user_create);
1.994     raeburn  9947:     my $context_dom = $env{'request.role.domain'};
                   9948:     if ($context eq 'requestcrs') {
                   9949:         if ($env{'form.coursedom'} ne '') { 
                   9950:             $context_dom = $env{'form.coursedom'};
                   9951:         }
                   9952:     }
1.556     raeburn  9953:     if ($forcenewuser) {
1.576     raeburn  9954:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9955:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9956:                 if ($cancreate) {
                   9957:                     $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>';
                   9958:                 } else {
1.799     bisitz   9959:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9960:                     my %usertypetext = (
                   9961:                         official   => 'institutional',
                   9962:                         unofficial => 'non-institutional',
                   9963:                     );
1.799     bisitz   9964:                     $new_user_create = '<p class="LC_warning">'
                   9965:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9966:                                       .' '
                   9967:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9968:                                           ,'<a href="'.$helplink.'">','</a>')
                   9969:                                       .'</p><br />';
1.627     raeburn  9970:                 }
1.576     raeburn  9971:             }
                   9972:         }
                   9973: 
1.556     raeburn  9974:         $newuserscript = <<"ENDSCRIPT";
                   9975: 
1.570     raeburn  9976: function setSearch(createnew,callingForm) {
1.556     raeburn  9977:     if (createnew == 1) {
1.570     raeburn  9978:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9979:             if (callingForm.srchby.options[i].value == 'uname') {
                   9980:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9981:             }
                   9982:         }
1.570     raeburn  9983:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9984:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9985: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9986:             }
                   9987:         }
1.570     raeburn  9988:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9989:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9990:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9991:             }
                   9992:         }
1.570     raeburn  9993:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9994:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9995:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9996:             }
                   9997:         }
                   9998:     }
                   9999: }
                   10000: ENDSCRIPT
1.558     albertel 10001: 
1.556     raeburn  10002:     }
                   10003: 
1.555     raeburn  10004:     my $output = <<"END_BLOCK";
1.556     raeburn  10005: <script type="text/javascript">
1.824     bisitz   10006: // <![CDATA[
1.570     raeburn  10007: function validateEntry(callingForm) {
1.558     albertel 10008: 
1.556     raeburn  10009:     var checkok = 1;
1.558     albertel 10010:     var srchin;
1.570     raeburn  10011:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10012: 	if ( callingForm.srchin[i].checked ) {
                   10013: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10014: 	}
                   10015:     }
                   10016: 
1.570     raeburn  10017:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10018:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10019:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10020:     var srchterm =  callingForm.srchterm.value;
                   10021:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10022:     var msg = "";
                   10023: 
                   10024:     if (srchterm == "") {
                   10025:         checkok = 0;
1.1075.2.98  raeburn  10026:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10027:     }
                   10028: 
1.569     raeburn  10029:     if (srchtype== 'begins') {
                   10030:         if (srchterm.length < 2) {
                   10031:             checkok = 0;
1.1075.2.98  raeburn  10032:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10033:         }
                   10034:     }
                   10035: 
1.556     raeburn  10036:     if (srchtype== 'contains') {
                   10037:         if (srchterm.length < 3) {
                   10038:             checkok = 0;
1.1075.2.98  raeburn  10039:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10040:         }
                   10041:     }
                   10042:     if (srchin == 'instd') {
                   10043:         if (srchdomain == '') {
                   10044:             checkok = 0;
1.1075.2.98  raeburn  10045:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10046:         }
                   10047:     }
                   10048:     if (srchin == 'dom') {
                   10049:         if (srchdomain == '') {
                   10050:             checkok = 0;
1.1075.2.98  raeburn  10051:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10052:         }
                   10053:     }
                   10054:     if (srchby == 'lastfirst') {
                   10055:         if (srchterm.indexOf(",") == -1) {
                   10056:             checkok = 0;
1.1075.2.98  raeburn  10057:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10058:         }
                   10059:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10060:             checkok = 0;
1.1075.2.98  raeburn  10061:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10062:         }
                   10063:     }
                   10064:     if (checkok == 0) {
1.1075.2.98  raeburn  10065:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10066:         return;
                   10067:     }
                   10068:     if (checkok == 1) {
1.570     raeburn  10069:         callingForm.submit();
1.556     raeburn  10070:     }
                   10071: }
                   10072: 
                   10073: $newuserscript
                   10074: 
1.824     bisitz   10075: // ]]>
1.556     raeburn  10076: </script>
1.558     albertel 10077: 
                   10078: $new_user_create
                   10079: 
1.555     raeburn  10080: END_BLOCK
1.558     albertel 10081: 
1.876     raeburn  10082:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10083:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10084:                $domform.
                   10085:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10086:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10087:                $srchbysel.
                   10088:                $srchtypesel. 
                   10089:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10090:                $srchinsel.
                   10091:                &Apache::lonhtmlcommon::row_closure(1). 
                   10092:                &Apache::lonhtmlcommon::end_pick_box().
                   10093:                '<br />';
1.1075.2.114  raeburn  10094:     return ($output,1);
1.555     raeburn  10095: }
                   10096: 
1.612     raeburn  10097: sub user_rule_check {
1.615     raeburn  10098:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10099:     my ($response,%inst_response);
1.612     raeburn  10100:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10101:         if (keys(%{$usershash}) > 1) {
                   10102:             my (%by_username,%by_id,%userdoms);
                   10103:             my $checkid;
1.612     raeburn  10104:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10105:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10106:                     $checkid = 1;
                   10107:                 }
                   10108:             }
                   10109:             foreach my $user (keys(%{$usershash})) {
                   10110:                 my ($uname,$udom) = split(/:/,$user);
                   10111:                 if ($checkid) {
                   10112:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10113:                         if ($usershash->{$user}->{'id'} ne '') {
                   10114:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10115:                             $userdoms{$udom} = 1;
                   10116:                             if (ref($inst_results) eq 'HASH') {
                   10117:                                 $inst_results->{$uname.':'.$udom} = {};
                   10118:                             }
                   10119:                         }
                   10120:                     }
                   10121:                 } else {
                   10122:                     $by_username{$udom}{$uname} = 1;
                   10123:                     $userdoms{$udom} = 1;
                   10124:                     if (ref($inst_results) eq 'HASH') {
                   10125:                         $inst_results->{$uname.':'.$udom} = {};
                   10126:                     }
                   10127:                 }
                   10128:             }
                   10129:             foreach my $udom (keys(%userdoms)) {
                   10130:                 if (!$got_rules->{$udom}) {
                   10131:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10132:                                                              ['usercreation'],$udom);
                   10133:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10134:                         foreach my $item ('username','id') {
                   10135:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10136:                                 $$curr_rules{$udom}{$item} =
                   10137:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10138:                             }
                   10139:                         }
                   10140:                     }
                   10141:                     $got_rules->{$udom} = 1;
                   10142:                 }
                   10143:             }
                   10144:             if ($checkid) {
                   10145:                 foreach my $udom (keys(%by_id)) {
                   10146:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10147:                     if ($outcome eq 'ok') {
                   10148:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10149:                             my $uname = $by_id{$udom}{$id};
                   10150:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10151:                         }
                   10152:                         if (ref($results) eq 'HASH') {
                   10153:                             foreach my $uname (keys(%{$results})) {
                   10154:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10155:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10156:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10157:                                 }
                   10158:                             }
                   10159:                         }
                   10160:                     }
1.612     raeburn  10161:                 }
1.615     raeburn  10162:             } else {
1.1075.2.99  raeburn  10163:                 foreach my $udom (keys(%by_username)) {
                   10164:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10165:                     if ($outcome eq 'ok') {
                   10166:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10167:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10168:                         }
                   10169:                         if (ref($results) eq 'HASH') {
                   10170:                             foreach my $uname (keys(%{$results})) {
                   10171:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10172:                             }
                   10173:                         }
                   10174:                     }
                   10175:                 }
1.612     raeburn  10176:             }
1.1075.2.99  raeburn  10177:         } elsif (keys(%{$usershash}) == 1) {
                   10178:             my $user = (keys(%{$usershash}))[0];
                   10179:             my ($uname,$udom) = split(/:/,$user);
                   10180:             if (($udom ne '') && ($uname ne '')) {
                   10181:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10182:                     if (ref($checks) eq 'HASH') {
                   10183:                         if (defined($checks->{'username'})) {
                   10184:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10185:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10186:                         } elsif (defined($checks->{'id'})) {
                   10187:                             if ($usershash->{$user}->{'id'} ne '') {
                   10188:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10189:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10190:                                                                   $usershash->{$user}->{'id'});
                   10191:                             } else {
                   10192:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10193:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10194:                             }
                   10195:                         }
                   10196:                     } else {
                   10197:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10198:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10199:                        return;
                   10200:                     }
                   10201:                     if (!$got_rules->{$udom}) {
                   10202:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10203:                                                                  ['usercreation'],$udom);
                   10204:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10205:                             foreach my $item ('username','id') {
                   10206:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10207:                                    $$curr_rules{$udom}{$item} =
                   10208:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10209:                                 }
                   10210:                             }
1.585     raeburn  10211:                         }
1.1075.2.99  raeburn  10212:                         $got_rules->{$udom} = 1;
1.585     raeburn  10213:                     }
                   10214:                 }
1.1075.2.99  raeburn  10215:             } else {
                   10216:                 return;
                   10217:             }
                   10218:         } else {
                   10219:             return;
                   10220:         }
                   10221:         foreach my $user (keys(%{$usershash})) {
                   10222:             my ($uname,$udom) = split(/:/,$user);
                   10223:             next if (($udom eq '') || ($uname eq ''));
                   10224:             my $id;
                   10225:             if (ref($inst_results) eq 'HASH') {
                   10226:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10227:                     $id = $inst_results->{$user}->{'id'};
                   10228:                 }
                   10229:             }
                   10230:             if ($id eq '') {
                   10231:                 if (ref($usershash->{$user})) {
                   10232:                     $id = $usershash->{$user}->{'id'};
                   10233:                 }
1.585     raeburn  10234:             }
1.612     raeburn  10235:             foreach my $item (keys(%{$checks})) {
                   10236:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10237:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10238:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10239:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10240:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10241:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10242:                                 if ($rule_check{$rule}) {
                   10243:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10244:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10245:                                         if (ref($inst_results) eq 'HASH') {
                   10246:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10247:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10248:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10249:                                                 } elsif ($item eq 'id') {
                   10250:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10251:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10252:                                                     }
1.615     raeburn  10253:                                                 }
1.612     raeburn  10254:                                             }
                   10255:                                         }
1.615     raeburn  10256:                                     }
                   10257:                                     last;
1.585     raeburn  10258:                                 }
                   10259:                             }
                   10260:                         }
                   10261:                     }
                   10262:                 }
                   10263:             }
                   10264:         }
                   10265:     }
1.612     raeburn  10266:     return;
                   10267: }
                   10268: 
                   10269: sub user_rule_formats {
                   10270:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10271:     my %text = ( 
                   10272:                  'username' => 'Usernames',
                   10273:                  'id'       => 'IDs',
                   10274:                );
                   10275:     my $output;
                   10276:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10277:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10278:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10279:             $output = '<br />'.
                   10280:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10281:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10282:                       ' <ul>';
1.612     raeburn  10283:             foreach my $rule (@{$ruleorder}) {
                   10284:                 if (ref($curr_rules) eq 'ARRAY') {
                   10285:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10286:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10287:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10288:                                         $rules->{$rule}{'desc'}.'</li>';
                   10289:                         }
                   10290:                     }
                   10291:                 }
                   10292:             }
                   10293:             $output .= '</ul>';
                   10294:         }
                   10295:     }
                   10296:     return $output;
                   10297: }
                   10298: 
                   10299: sub instrule_disallow_msg {
1.615     raeburn  10300:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10301:     my $response;
                   10302:     my %text = (
                   10303:                   item   => 'username',
                   10304:                   items  => 'usernames',
                   10305:                   match  => 'matches',
                   10306:                   do     => 'does',
                   10307:                   action => 'a username',
                   10308:                   one    => 'one',
                   10309:                );
                   10310:     if ($count > 1) {
                   10311:         $text{'item'} = 'usernames';
                   10312:         $text{'match'} ='match';
                   10313:         $text{'do'} = 'do';
                   10314:         $text{'action'} = 'usernames',
                   10315:         $text{'one'} = 'ones';
                   10316:     }
                   10317:     if ($checkitem eq 'id') {
                   10318:         $text{'items'} = 'IDs';
                   10319:         $text{'item'} = 'ID';
                   10320:         $text{'action'} = 'an ID';
1.615     raeburn  10321:         if ($count > 1) {
                   10322:             $text{'item'} = 'IDs';
                   10323:             $text{'action'} = 'IDs';
                   10324:         }
1.612     raeburn  10325:     }
1.674     bisitz   10326:     $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  10327:     if ($mode eq 'upload') {
                   10328:         if ($checkitem eq 'username') {
                   10329:             $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'}.");
                   10330:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10331:             $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  10332:         }
1.669     raeburn  10333:     } elsif ($mode eq 'selfcreate') {
                   10334:         if ($checkitem eq 'id') {
                   10335:             $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.");
                   10336:         }
1.615     raeburn  10337:     } else {
                   10338:         if ($checkitem eq 'username') {
                   10339:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10340:         } elsif ($checkitem eq 'id') {
                   10341:             $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.");
                   10342:         }
1.612     raeburn  10343:     }
                   10344:     return $response;
1.585     raeburn  10345: }
                   10346: 
1.624     raeburn  10347: sub personal_data_fieldtitles {
                   10348:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10349:                         id => 'Student/Employee ID',
                   10350:                         permanentemail => 'E-mail address',
                   10351:                         lastname => 'Last Name',
                   10352:                         firstname => 'First Name',
                   10353:                         middlename => 'Middle Name',
                   10354:                         generation => 'Generation',
                   10355:                         gen => 'Generation',
1.765     raeburn  10356:                         inststatus => 'Affiliation',
1.624     raeburn  10357:                    );
                   10358:     return %fieldtitles;
                   10359: }
                   10360: 
1.642     raeburn  10361: sub sorted_inst_types {
                   10362:     my ($dom) = @_;
1.1075.2.70  raeburn  10363:     my ($usertypes,$order);
                   10364:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10365:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10366:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10367:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10368:     } else {
                   10369:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10370:     }
1.642     raeburn  10371:     my $othertitle = &mt('All users');
                   10372:     if ($env{'request.course.id'}) {
1.668     raeburn  10373:         $othertitle  = &mt('Any users');
1.642     raeburn  10374:     }
                   10375:     my @types;
                   10376:     if (ref($order) eq 'ARRAY') {
                   10377:         @types = @{$order};
                   10378:     }
                   10379:     if (@types == 0) {
                   10380:         if (ref($usertypes) eq 'HASH') {
                   10381:             @types = sort(keys(%{$usertypes}));
                   10382:         }
                   10383:     }
                   10384:     if (keys(%{$usertypes}) > 0) {
                   10385:         $othertitle = &mt('Other users');
                   10386:     }
                   10387:     return ($othertitle,$usertypes,\@types);
                   10388: }
                   10389: 
1.645     raeburn  10390: sub get_institutional_codes {
                   10391:     my ($settings,$allcourses,$LC_code) = @_;
                   10392: # Get complete list of course sections to update
                   10393:     my @currsections = ();
                   10394:     my @currxlists = ();
                   10395:     my $coursecode = $$settings{'internal.coursecode'};
                   10396: 
                   10397:     if ($$settings{'internal.sectionnums'} ne '') {
                   10398:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10399:     }
                   10400: 
                   10401:     if ($$settings{'internal.crosslistings'} ne '') {
                   10402:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10403:     }
                   10404: 
                   10405:     if (@currxlists > 0) {
                   10406:         foreach (@currxlists) {
                   10407:             if (m/^([^:]+):(\w*)$/) {
                   10408:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10409:                     push(@{$allcourses},$1);
1.645     raeburn  10410:                     $$LC_code{$1} = $2;
                   10411:                 }
                   10412:             }
                   10413:         }
                   10414:     }
                   10415:  
                   10416:     if (@currsections > 0) {
                   10417:         foreach (@currsections) {
                   10418:             if (m/^(\w+):(\w*)$/) {
                   10419:                 my $sec = $coursecode.$1;
                   10420:                 my $lc_sec = $2;
                   10421:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10422:                     push(@{$allcourses},$sec);
1.645     raeburn  10423:                     $$LC_code{$sec} = $lc_sec;
                   10424:                 }
                   10425:             }
                   10426:         }
                   10427:     }
                   10428:     return;
                   10429: }
                   10430: 
1.971     raeburn  10431: sub get_standard_codeitems {
                   10432:     return ('Year','Semester','Department','Number','Section');
                   10433: }
                   10434: 
1.112     bowersj2 10435: =pod
                   10436: 
1.780     raeburn  10437: =head1 Slot Helpers
                   10438: 
                   10439: =over 4
                   10440: 
                   10441: =item * sorted_slots()
                   10442: 
1.1040    raeburn  10443: Sorts an array of slot names in order of an optional sort key,
                   10444: default sort is by slot start time (earliest first). 
1.780     raeburn  10445: 
                   10446: Inputs:
                   10447: 
                   10448: =over 4
                   10449: 
                   10450: slotsarr  - Reference to array of unsorted slot names.
                   10451: 
                   10452: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10453: 
1.1040    raeburn  10454: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10455: 
1.549     albertel 10456: =back
                   10457: 
1.780     raeburn  10458: Returns:
                   10459: 
                   10460: =over 4
                   10461: 
1.1040    raeburn  10462: sorted   - An array of slot names sorted by a specified sort key 
                   10463:            (default sort key is start time of the slot).
1.780     raeburn  10464: 
                   10465: =back
                   10466: 
                   10467: =cut
                   10468: 
                   10469: 
                   10470: sub sorted_slots {
1.1040    raeburn  10471:     my ($slotsarr,$slots,$sortkey) = @_;
                   10472:     if ($sortkey eq '') {
                   10473:         $sortkey = 'starttime';
                   10474:     }
1.780     raeburn  10475:     my @sorted;
                   10476:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10477:         @sorted =
                   10478:             sort {
                   10479:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10480:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10481:                      }
                   10482:                      if (ref($slots->{$a})) { return -1;}
                   10483:                      if (ref($slots->{$b})) { return 1;}
                   10484:                      return 0;
                   10485:                  } @{$slotsarr};
                   10486:     }
                   10487:     return @sorted;
                   10488: }
                   10489: 
1.1040    raeburn  10490: =pod
                   10491: 
                   10492: =item * get_future_slots()
                   10493: 
                   10494: Inputs:
                   10495: 
                   10496: =over 4
                   10497: 
                   10498: cnum - course number
                   10499: 
                   10500: cdom - course domain
                   10501: 
                   10502: now - current UNIX time
                   10503: 
                   10504: symb - optional symb
                   10505: 
                   10506: =back
                   10507: 
                   10508: Returns:
                   10509: 
                   10510: =over 4
                   10511: 
                   10512: sorted_reservable - ref to array of student_schedulable slots currently 
                   10513:                     reservable, ordered by end date of reservation period.
                   10514: 
                   10515: reservable_now - ref to hash of student_schedulable slots currently
                   10516:                  reservable.
                   10517: 
                   10518:     Keys in inner hash are:
                   10519:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10520:     (b) endreserve: end date of reservation period.
                   10521:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10522:         selected.
1.1040    raeburn  10523: 
                   10524: sorted_future - ref to array of student_schedulable slots reservable in
                   10525:                 the future, ordered by start date of reservation period.
                   10526: 
                   10527: future_reservable - ref to hash of student_schedulable slots reservable
                   10528:                     in the future.
                   10529: 
                   10530:     Keys in inner hash are:
                   10531:     (a) symb: either blank or symb to which slot use is restricted.
                   10532:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10533:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10534:         selected.
1.1040    raeburn  10535: 
                   10536: =back
                   10537: 
                   10538: =cut
                   10539: 
                   10540: sub get_future_slots {
                   10541:     my ($cnum,$cdom,$now,$symb) = @_;
                   10542:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10543:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10544:     foreach my $slot (keys(%slots)) {
                   10545:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10546:         if ($symb) {
                   10547:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10548:                      ($slots{$slot}->{'symb'} ne $symb));
                   10549:         }
                   10550:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10551:             ($slots{$slot}->{'endtime'} > $now)) {
                   10552:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10553:                 my $userallowed = 0;
                   10554:                 if ($slots{$slot}->{'allowedsections'}) {
                   10555:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10556:                     if (!defined($env{'request.role.sec'})
                   10557:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10558:                         $userallowed=1;
                   10559:                     } else {
                   10560:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10561:                             $userallowed=1;
                   10562:                         }
                   10563:                     }
                   10564:                     unless ($userallowed) {
                   10565:                         if (defined($env{'request.course.groups'})) {
                   10566:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10567:                             foreach my $group (@groups) {
                   10568:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10569:                                     $userallowed=1;
                   10570:                                     last;
                   10571:                                 }
                   10572:                             }
                   10573:                         }
                   10574:                     }
                   10575:                 }
                   10576:                 if ($slots{$slot}->{'allowedusers'}) {
                   10577:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10578:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10579:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10580:                         $userallowed = 1;
                   10581:                     }
                   10582:                 }
                   10583:                 next unless($userallowed);
                   10584:             }
                   10585:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10586:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10587:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10588:             my $uniqueperiod;
                   10589:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10590:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10591:             }
1.1040    raeburn  10592:             if (($startreserve < $now) &&
                   10593:                 (!$endreserve || $endreserve > $now)) {
                   10594:                 my $lastres = $endreserve;
                   10595:                 if (!$lastres) {
                   10596:                     $lastres = $slots{$slot}->{'starttime'};
                   10597:                 }
                   10598:                 $reservable_now{$slot} = {
                   10599:                                            symb       => $symb,
1.1075.2.104  raeburn  10600:                                            endreserve => $lastres,
                   10601:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10602:                                          };
                   10603:             } elsif (($startreserve > $now) &&
                   10604:                      (!$endreserve || $endreserve > $startreserve)) {
                   10605:                 $future_reservable{$slot} = {
                   10606:                                               symb         => $symb,
1.1075.2.104  raeburn  10607:                                               startreserve => $startreserve,
                   10608:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10609:                                             };
                   10610:             }
                   10611:         }
                   10612:     }
                   10613:     my @unsorted_reservable = keys(%reservable_now);
                   10614:     if (@unsorted_reservable > 0) {
                   10615:         @sorted_reservable = 
                   10616:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10617:     }
                   10618:     my @unsorted_future = keys(%future_reservable);
                   10619:     if (@unsorted_future > 0) {
                   10620:         @sorted_future =
                   10621:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10622:     }
                   10623:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10624: }
1.780     raeburn  10625: 
                   10626: =pod
                   10627: 
1.1057    foxr     10628: =back
                   10629: 
1.549     albertel 10630: =head1 HTTP Helpers
                   10631: 
                   10632: =over 4
                   10633: 
1.648     raeburn  10634: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10635: 
1.258     albertel 10636: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10637: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10638: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10639: 
                   10640: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10641: $possible_names is an ref to an array of form element names.  As an example:
                   10642: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10643: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10644: 
                   10645: =cut
1.1       albertel 10646: 
1.6       albertel 10647: sub get_unprocessed_cgi {
1.25      albertel 10648:   my ($query,$possible_names)= @_;
1.26      matthew  10649:   # $Apache::lonxml::debug=1;
1.356     albertel 10650:   foreach my $pair (split(/&/,$query)) {
                   10651:     my ($name, $value) = split(/=/,$pair);
1.369     www      10652:     $name = &unescape($name);
1.25      albertel 10653:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10654:       $value =~ tr/+/ /;
                   10655:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10656:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10657:     }
1.16      harris41 10658:   }
1.6       albertel 10659: }
                   10660: 
1.112     bowersj2 10661: =pod
                   10662: 
1.648     raeburn  10663: =item * &cacheheader() 
1.112     bowersj2 10664: 
                   10665: returns cache-controlling header code
                   10666: 
                   10667: =cut
                   10668: 
1.7       albertel 10669: sub cacheheader {
1.258     albertel 10670:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10671:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10672:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10673:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10674:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10675:     return $output;
1.7       albertel 10676: }
                   10677: 
1.112     bowersj2 10678: =pod
                   10679: 
1.648     raeburn  10680: =item * &no_cache($r) 
1.112     bowersj2 10681: 
                   10682: specifies header code to not have cache
                   10683: 
                   10684: =cut
                   10685: 
1.9       albertel 10686: sub no_cache {
1.216     albertel 10687:     my ($r) = @_;
                   10688:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10689: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10690:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10691:     $r->no_cache(1);
                   10692:     $r->header_out("Expires" => $date);
                   10693:     $r->header_out("Pragma" => "no-cache");
1.123     www      10694: }
                   10695: 
                   10696: sub content_type {
1.181     albertel 10697:     my ($r,$type,$charset) = @_;
1.299     foxr     10698:     if ($r) {
                   10699: 	#  Note that printout.pl calls this with undef for $r.
                   10700: 	&no_cache($r);
                   10701:     }
1.258     albertel 10702:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10703:     unless ($charset) {
                   10704: 	$charset=&Apache::lonlocal::current_encoding;
                   10705:     }
                   10706:     if ($charset) { $type.='; charset='.$charset; }
                   10707:     if ($r) {
                   10708: 	$r->content_type($type);
                   10709:     } else {
                   10710: 	print("Content-type: $type\n\n");
                   10711:     }
1.9       albertel 10712: }
1.25      albertel 10713: 
1.112     bowersj2 10714: =pod
                   10715: 
1.648     raeburn  10716: =item * &add_to_env($name,$value) 
1.112     bowersj2 10717: 
1.258     albertel 10718: adds $name to the %env hash with value
1.112     bowersj2 10719: $value, if $name already exists, the entry is converted to an array
                   10720: reference and $value is added to the array.
                   10721: 
                   10722: =cut
                   10723: 
1.25      albertel 10724: sub add_to_env {
                   10725:   my ($name,$value)=@_;
1.258     albertel 10726:   if (defined($env{$name})) {
                   10727:     if (ref($env{$name})) {
1.25      albertel 10728:       #already have multiple values
1.258     albertel 10729:       push(@{ $env{$name} },$value);
1.25      albertel 10730:     } else {
                   10731:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10732:       my $first=$env{$name};
                   10733:       undef($env{$name});
                   10734:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10735:     }
                   10736:   } else {
1.258     albertel 10737:     $env{$name}=$value;
1.25      albertel 10738:   }
1.31      albertel 10739: }
1.149     albertel 10740: 
                   10741: =pod
                   10742: 
1.648     raeburn  10743: =item * &get_env_multiple($name) 
1.149     albertel 10744: 
1.258     albertel 10745: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10746: values may be defined and end up as an array ref.
                   10747: 
                   10748: returns an array of values
                   10749: 
                   10750: =cut
                   10751: 
                   10752: sub get_env_multiple {
                   10753:     my ($name) = @_;
                   10754:     my @values;
1.258     albertel 10755:     if (defined($env{$name})) {
1.149     albertel 10756:         # exists is it an array
1.258     albertel 10757:         if (ref($env{$name})) {
                   10758:             @values=@{ $env{$name} };
1.149     albertel 10759:         } else {
1.258     albertel 10760:             $values[0]=$env{$name};
1.149     albertel 10761:         }
                   10762:     }
                   10763:     return(@values);
                   10764: }
                   10765: 
1.660     raeburn  10766: sub ask_for_embedded_content {
                   10767:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10768:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10769:         %currsubfile,%unused,$rem);
1.1071    raeburn  10770:     my $counter = 0;
                   10771:     my $numnew = 0;
1.987     raeburn  10772:     my $numremref = 0;
                   10773:     my $numinvalid = 0;
                   10774:     my $numpathchg = 0;
                   10775:     my $numexisting = 0;
1.1071    raeburn  10776:     my $numunused = 0;
                   10777:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10778:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10779:     my $heading = &mt('Upload embedded files');
                   10780:     my $buttontext = &mt('Upload');
                   10781: 
1.1075.2.11  raeburn  10782:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10783:         if ($actionurl eq '/adm/dependencies') {
                   10784:             $navmap = Apache::lonnavmaps::navmap->new();
                   10785:         }
                   10786:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10787:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10788:     }
1.1075.2.35  raeburn  10789:     if (($actionurl eq '/adm/portfolio') ||
                   10790:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10791:         my $current_path='/';
                   10792:         if ($env{'form.currentpath'}) {
                   10793:             $current_path = $env{'form.currentpath'};
                   10794:         }
                   10795:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10796:             $udom = $cdom;
                   10797:             $uname = $cnum;
1.984     raeburn  10798:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10799:         } else {
                   10800:             $udom = $env{'user.domain'};
                   10801:             $uname = $env{'user.name'};
                   10802:             $url = '/userfiles/portfolio';
                   10803:         }
1.987     raeburn  10804:         $toplevel = $url.'/';
1.984     raeburn  10805:         $url .= $current_path;
                   10806:         $getpropath = 1;
1.987     raeburn  10807:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10808:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10809:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10810:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10811:         $toplevel = $url;
1.984     raeburn  10812:         if ($rest ne '') {
1.987     raeburn  10813:             $url .= $rest;
                   10814:         }
                   10815:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10816:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10817:             $url = $args->{'docs_url'};
                   10818:             $toplevel = $url;
1.1075.2.11  raeburn  10819:             if ($args->{'context'} eq 'paste') {
                   10820:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10821:                 ($path) =
                   10822:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10823:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10824:                 $fileloc =~ s{^/}{};
                   10825:             }
1.1071    raeburn  10826:         }
                   10827:     } elsif ($actionurl eq '/adm/dependencies') {
                   10828:         if ($env{'request.course.id'} ne '') {
                   10829:             if (ref($args) eq 'HASH') {
                   10830:                 $url = $args->{'docs_url'};
                   10831:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10832:                 $toplevel = $url;
                   10833:                 unless ($toplevel =~ m{^/}) {
                   10834:                     $toplevel = "/$url";
                   10835:                 }
1.1075.2.11  raeburn  10836:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10837:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10838:                     $path = $1;
                   10839:                 } else {
                   10840:                     ($path) =
                   10841:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10842:                 }
1.1075.2.79  raeburn  10843:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10844:                     $fileloc = $toplevel;
                   10845:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10846:                     my ($udom,$uname,$fname) =
                   10847:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10848:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10849:                 } else {
                   10850:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10851:                 }
1.1071    raeburn  10852:                 $fileloc =~ s{^/}{};
                   10853:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10854:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10855:             }
1.987     raeburn  10856:         }
1.1075.2.35  raeburn  10857:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10858:         $udom = $cdom;
                   10859:         $uname = $cnum;
                   10860:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10861:         $toplevel = $url;
                   10862:         $path = $url;
                   10863:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10864:         $fileloc =~ s{^/}{};
                   10865:     }
                   10866:     foreach my $file (keys(%{$allfiles})) {
                   10867:         my $embed_file;
                   10868:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10869:             $embed_file = $1;
                   10870:         } else {
                   10871:             $embed_file = $file;
                   10872:         }
1.1075.2.55  raeburn  10873:         my ($absolutepath,$cleaned_file);
                   10874:         if ($embed_file =~ m{^\w+://}) {
                   10875:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10876:             $newfiles{$cleaned_file} = 1;
                   10877:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10878:         } else {
1.1075.2.55  raeburn  10879:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10880:             if ($embed_file =~ m{^/}) {
                   10881:                 $absolutepath = $embed_file;
                   10882:             }
1.1075.2.47  raeburn  10883:             if ($cleaned_file =~ m{/}) {
                   10884:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10885:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10886:                 my $item = $fname;
                   10887:                 if ($path ne '') {
                   10888:                     $item = $path.'/'.$fname;
                   10889:                     $subdependencies{$path}{$fname} = 1;
                   10890:                 } else {
                   10891:                     $dependencies{$item} = 1;
                   10892:                 }
                   10893:                 if ($absolutepath) {
                   10894:                     $mapping{$item} = $absolutepath;
                   10895:                 } else {
                   10896:                     $mapping{$item} = $embed_file;
                   10897:                 }
                   10898:             } else {
                   10899:                 $dependencies{$embed_file} = 1;
                   10900:                 if ($absolutepath) {
1.1075.2.47  raeburn  10901:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10902:                 } else {
1.1075.2.47  raeburn  10903:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10904:                 }
                   10905:             }
1.984     raeburn  10906:         }
                   10907:     }
1.1071    raeburn  10908:     my $dirptr = 16384;
1.984     raeburn  10909:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10910:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10911:         if (($actionurl eq '/adm/portfolio') ||
                   10912:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10913:             my ($sublistref,$listerror) =
                   10914:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10915:             if (ref($sublistref) eq 'ARRAY') {
                   10916:                 foreach my $line (@{$sublistref}) {
                   10917:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10918:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10919:                 }
1.984     raeburn  10920:             }
1.987     raeburn  10921:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10922:             if (opendir(my $dir,$url.'/'.$path)) {
                   10923:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10924:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10925:             }
1.1075.2.11  raeburn  10926:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10927:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10928:                   ($args->{'context'} eq 'paste')) ||
                   10929:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10930:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10931:                 my $dir;
                   10932:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10933:                     $dir = $fileloc;
                   10934:                 } else {
                   10935:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10936:                 }
1.1071    raeburn  10937:                 if ($dir ne '') {
                   10938:                     my ($sublistref,$listerror) =
                   10939:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10940:                     if (ref($sublistref) eq 'ARRAY') {
                   10941:                         foreach my $line (@{$sublistref}) {
                   10942:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10943:                                 undef,$mtime)=split(/\&/,$line,12);
                   10944:                             unless (($testdir&$dirptr) ||
                   10945:                                     ($file_name =~ /^\.\.?$/)) {
                   10946:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10947:                             }
                   10948:                         }
                   10949:                     }
                   10950:                 }
1.984     raeburn  10951:             }
                   10952:         }
                   10953:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10954:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10955:                 my $item = $path.'/'.$file;
                   10956:                 unless ($mapping{$item} eq $item) {
                   10957:                     $pathchanges{$item} = 1;
                   10958:                 }
                   10959:                 $existing{$item} = 1;
                   10960:                 $numexisting ++;
                   10961:             } else {
                   10962:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10963:             }
                   10964:         }
1.1071    raeburn  10965:         if ($actionurl eq '/adm/dependencies') {
                   10966:             foreach my $path (keys(%currsubfile)) {
                   10967:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10968:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10969:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10970:                              next if (($rem ne '') &&
                   10971:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10972:                                        (ref($navmap) &&
                   10973:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10974:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10975:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10976:                              $unused{$path.'/'.$file} = 1; 
                   10977:                          }
                   10978:                     }
                   10979:                 }
                   10980:             }
                   10981:         }
1.984     raeburn  10982:     }
1.987     raeburn  10983:     my %currfile;
1.1075.2.35  raeburn  10984:     if (($actionurl eq '/adm/portfolio') ||
                   10985:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10986:         my ($dirlistref,$listerror) =
                   10987:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10988:         if (ref($dirlistref) eq 'ARRAY') {
                   10989:             foreach my $line (@{$dirlistref}) {
                   10990:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10991:                 $currfile{$file_name} = 1;
                   10992:             }
1.984     raeburn  10993:         }
1.987     raeburn  10994:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10995:         if (opendir(my $dir,$url)) {
1.987     raeburn  10996:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10997:             map {$currfile{$_} = 1;} @dir_list;
                   10998:         }
1.1075.2.11  raeburn  10999:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11000:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11001:               ($args->{'context'} eq 'paste')) ||
                   11002:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11003:         if ($env{'request.course.id'} ne '') {
                   11004:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11005:             if ($dir ne '') {
                   11006:                 my ($dirlistref,$listerror) =
                   11007:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11008:                 if (ref($dirlistref) eq 'ARRAY') {
                   11009:                     foreach my $line (@{$dirlistref}) {
                   11010:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11011:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11012:                         unless (($testdir&$dirptr) ||
                   11013:                                 ($file_name =~ /^\.\.?$/)) {
                   11014:                             $currfile{$file_name} = [$size,$mtime];
                   11015:                         }
                   11016:                     }
                   11017:                 }
                   11018:             }
                   11019:         }
1.984     raeburn  11020:     }
                   11021:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11022:         if (exists($currfile{$file})) {
1.987     raeburn  11023:             unless ($mapping{$file} eq $file) {
                   11024:                 $pathchanges{$file} = 1;
                   11025:             }
                   11026:             $existing{$file} = 1;
                   11027:             $numexisting ++;
                   11028:         } else {
1.984     raeburn  11029:             $newfiles{$file} = 1;
                   11030:         }
                   11031:     }
1.1071    raeburn  11032:     foreach my $file (keys(%currfile)) {
                   11033:         unless (($file eq $filename) ||
                   11034:                 ($file eq $filename.'.bak') ||
                   11035:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11036:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11037:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11038:                     next if (($rem ne '') &&
                   11039:                              (($env{"httpref.$rem".$file} ne '') ||
                   11040:                               (ref($navmap) &&
                   11041:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11042:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11043:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11044:                 }
1.1075.2.11  raeburn  11045:             }
1.1071    raeburn  11046:             $unused{$file} = 1;
                   11047:         }
                   11048:     }
1.1075.2.11  raeburn  11049:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11050:         ($args->{'context'} eq 'paste')) {
                   11051:         $counter = scalar(keys(%existing));
                   11052:         $numpathchg = scalar(keys(%pathchanges));
                   11053:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11054:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11055:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11056:         $counter = scalar(keys(%existing));
                   11057:         $numpathchg = scalar(keys(%pathchanges));
                   11058:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11059:     }
1.984     raeburn  11060:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11061:         if ($actionurl eq '/adm/dependencies') {
                   11062:             next if ($embed_file =~ m{^\w+://});
                   11063:         }
1.660     raeburn  11064:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11065:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11066:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11067:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11068:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11069:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11070:         }
1.1075.2.35  raeburn  11071:         $upload_output .= '</td>';
1.1071    raeburn  11072:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11073:             $upload_output.='<td align="right">'.
                   11074:                             '<span class="LC_info LC_fontsize_medium">'.
                   11075:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11076:             $numremref++;
1.660     raeburn  11077:         } elsif ($args->{'error_on_invalid_names'}
                   11078:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11079:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11080:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11081:             $numinvalid++;
1.660     raeburn  11082:         } else {
1.1075.2.35  raeburn  11083:             $upload_output .= '<td>'.
                   11084:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11085:                                                      $embed_file,\%mapping,
1.1071    raeburn  11086:                                                      $allfiles,$codebase,'upload');
                   11087:             $counter ++;
                   11088:             $numnew ++;
1.987     raeburn  11089:         }
                   11090:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11091:     }
                   11092:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11093:         if ($actionurl eq '/adm/dependencies') {
                   11094:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11095:             $modify_output .= &start_data_table_row().
                   11096:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11097:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11098:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11099:                               '<td>'.$size.'</td>'.
                   11100:                               '<td>'.$mtime.'</td>'.
                   11101:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11102:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11103:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11104:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11105:                               &embedded_file_element('upload_embedded',$counter,
                   11106:                                                      $embed_file,\%mapping,
                   11107:                                                      $allfiles,$codebase,'modify').
                   11108:                               '</div></td>'.
                   11109:                               &end_data_table_row()."\n";
                   11110:             $counter ++;
                   11111:         } else {
                   11112:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11113:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11114:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11115:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11116:                               &Apache::loncommon::end_data_table_row()."\n";
                   11117:         }
                   11118:     }
                   11119:     my $delidx = $counter;
                   11120:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11121:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11122:         $delete_output .= &start_data_table_row().
                   11123:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11124:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11125:                           '<td>'.$size.'</td>'.
                   11126:                           '<td>'.$mtime.'</td>'.
                   11127:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11128:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11129:                           &embedded_file_element('upload_embedded',$delidx,
                   11130:                                                  $oldfile,\%mapping,$allfiles,
                   11131:                                                  $codebase,'delete').'</td>'.
                   11132:                           &end_data_table_row()."\n"; 
                   11133:         $numunused ++;
                   11134:         $delidx ++;
1.987     raeburn  11135:     }
                   11136:     if ($upload_output) {
                   11137:         $upload_output = &start_data_table().
                   11138:                          $upload_output.
                   11139:                          &end_data_table()."\n";
                   11140:     }
1.1071    raeburn  11141:     if ($modify_output) {
                   11142:         $modify_output = &start_data_table().
                   11143:                          &start_data_table_header_row().
                   11144:                          '<th>'.&mt('File').'</th>'.
                   11145:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11146:                          '<th>'.&mt('Modified').'</th>'.
                   11147:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11148:                          &end_data_table_header_row().
                   11149:                          $modify_output.
                   11150:                          &end_data_table()."\n";
                   11151:     }
                   11152:     if ($delete_output) {
                   11153:         $delete_output = &start_data_table().
                   11154:                          &start_data_table_header_row().
                   11155:                          '<th>'.&mt('File').'</th>'.
                   11156:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11157:                          '<th>'.&mt('Modified').'</th>'.
                   11158:                          '<th>'.&mt('Delete?').'</th>'.
                   11159:                          &end_data_table_header_row().
                   11160:                          $delete_output.
                   11161:                          &end_data_table()."\n";
                   11162:     }
1.987     raeburn  11163:     my $applies = 0;
                   11164:     if ($numremref) {
                   11165:         $applies ++;
                   11166:     }
                   11167:     if ($numinvalid) {
                   11168:         $applies ++;
                   11169:     }
                   11170:     if ($numexisting) {
                   11171:         $applies ++;
                   11172:     }
1.1071    raeburn  11173:     if ($counter || $numunused) {
1.987     raeburn  11174:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11175:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11176:                   $state.'<h3>'.$heading.'</h3>'; 
                   11177:         if ($actionurl eq '/adm/dependencies') {
                   11178:             if ($numnew) {
                   11179:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11180:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11181:                            $upload_output.'<br />'."\n";
                   11182:             }
                   11183:             if ($numexisting) {
                   11184:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11185:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11186:                            $modify_output.'<br />'."\n";
                   11187:                            $buttontext = &mt('Save changes');
                   11188:             }
                   11189:             if ($numunused) {
                   11190:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11191:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11192:                            $delete_output.'<br />'."\n";
                   11193:                            $buttontext = &mt('Save changes');
                   11194:             }
                   11195:         } else {
                   11196:             $output .= $upload_output.'<br />'."\n";
                   11197:         }
                   11198:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11199:                    $counter.'" />'."\n";
                   11200:         if ($actionurl eq '/adm/dependencies') { 
                   11201:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11202:                        $numnew.'" />'."\n";
                   11203:         } elsif ($actionurl eq '') {
1.987     raeburn  11204:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11205:         }
                   11206:     } elsif ($applies) {
                   11207:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11208:         if ($applies > 1) {
                   11209:             $output .=  
1.1075.2.35  raeburn  11210:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11211:             if ($numremref) {
                   11212:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11213:             }
                   11214:             if ($numinvalid) {
                   11215:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11216:             }
                   11217:             if ($numexisting) {
                   11218:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11219:             }
                   11220:             $output .= '</ul><br />';
                   11221:         } elsif ($numremref) {
                   11222:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11223:         } elsif ($numinvalid) {
                   11224:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11225:         } elsif ($numexisting) {
                   11226:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11227:         }
                   11228:         $output .= $upload_output.'<br />';
                   11229:     }
                   11230:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11231:     $chgcount = $counter;
1.987     raeburn  11232:     if (keys(%pathchanges) > 0) {
                   11233:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11234:             if ($counter) {
1.987     raeburn  11235:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11236:                                                   $embed_file,\%mapping,
1.1071    raeburn  11237:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11238:             } else {
                   11239:                 $pathchange_output .= 
                   11240:                     &start_data_table_row().
                   11241:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11242:                     $chgcount.'" checked="checked" /></td>'.
                   11243:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11244:                     '<td>'.$embed_file.
                   11245:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11246:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11247:                     '</td>'.&end_data_table_row();
1.660     raeburn  11248:             }
1.987     raeburn  11249:             $numpathchg ++;
                   11250:             $chgcount ++;
1.660     raeburn  11251:         }
                   11252:     }
1.1075.2.35  raeburn  11253:     if (($counter) || ($numunused)) {
1.987     raeburn  11254:         if ($numpathchg) {
                   11255:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11256:                        $numpathchg.'" />'."\n";
                   11257:         }
                   11258:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11259:             ($actionurl eq '/adm/imsimport')) {
                   11260:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11261:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11262:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11263:         } elsif ($actionurl eq '/adm/dependencies') {
                   11264:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11265:         }
1.1075.2.35  raeburn  11266:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11267:     } elsif ($numpathchg) {
                   11268:         my %pathchange = ();
                   11269:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11270:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11271:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11272:         }
1.987     raeburn  11273:     }
1.1071    raeburn  11274:     return ($output,$counter,$numpathchg);
1.987     raeburn  11275: }
                   11276: 
1.1075.2.47  raeburn  11277: =pod
                   11278: 
                   11279: =item * clean_path($name)
                   11280: 
                   11281: Performs clean-up of directories, subdirectories and filename in an
                   11282: embedded object, referenced in an HTML file which is being uploaded
                   11283: to a course or portfolio, where
                   11284: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11285: checked.
                   11286: 
                   11287: Clean-up is similar to replacements in lonnet::clean_filename()
                   11288: except each / between sub-directory and next level is preserved.
                   11289: 
                   11290: =cut
                   11291: 
                   11292: sub clean_path {
                   11293:     my ($embed_file) = @_;
                   11294:     $embed_file =~s{^/+}{};
                   11295:     my @contents;
                   11296:     if ($embed_file =~ m{/}) {
                   11297:         @contents = split(/\//,$embed_file);
                   11298:     } else {
                   11299:         @contents = ($embed_file);
                   11300:     }
                   11301:     my $lastidx = scalar(@contents)-1;
                   11302:     for (my $i=0; $i<=$lastidx; $i++) {
                   11303:         $contents[$i]=~s{\\}{/}g;
                   11304:         $contents[$i]=~s/\s+/\_/g;
                   11305:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11306:         if ($i == $lastidx) {
                   11307:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11308:         }
                   11309:     }
                   11310:     if ($lastidx > 0) {
                   11311:         return join('/',@contents);
                   11312:     } else {
                   11313:         return $contents[0];
                   11314:     }
                   11315: }
                   11316: 
1.987     raeburn  11317: sub embedded_file_element {
1.1071    raeburn  11318:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11319:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11320:                    (ref($codebase) eq 'HASH'));
                   11321:     my $output;
1.1071    raeburn  11322:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11323:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11324:     }
                   11325:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11326:                &escape($embed_file).'" />';
                   11327:     unless (($context eq 'upload_embedded') && 
                   11328:             ($mapping->{$embed_file} eq $embed_file)) {
                   11329:         $output .='
                   11330:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11331:     }
                   11332:     my $attrib;
                   11333:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11334:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11335:     }
                   11336:     $output .=
                   11337:         "\n\t\t".
                   11338:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11339:         $attrib.'" />';
                   11340:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11341:         $output .=
                   11342:             "\n\t\t".
                   11343:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11344:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11345:     }
1.987     raeburn  11346:     return $output;
1.660     raeburn  11347: }
                   11348: 
1.1071    raeburn  11349: sub get_dependency_details {
                   11350:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11351:     my ($size,$mtime,$showsize,$showmtime);
                   11352:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11353:         if ($embed_file =~ m{/}) {
                   11354:             my ($path,$fname) = split(/\//,$embed_file);
                   11355:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11356:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11357:             }
                   11358:         } else {
                   11359:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11360:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11361:             }
                   11362:         }
                   11363:         $showsize = $size/1024.0;
                   11364:         $showsize = sprintf("%.1f",$showsize);
                   11365:         if ($mtime > 0) {
                   11366:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11367:         }
                   11368:     }
                   11369:     return ($showsize,$showmtime);
                   11370: }
                   11371: 
                   11372: sub ask_embedded_js {
                   11373:     return <<"END";
                   11374: <script type="text/javascript"">
                   11375: // <![CDATA[
                   11376: function toggleBrowse(counter) {
                   11377:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11378:     var fileid = document.getElementById('embedded_item_'+counter);
                   11379:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11380:     if (chkboxid.checked == true) {
                   11381:         uploaddivid.style.display='block';
                   11382:     } else {
                   11383:         uploaddivid.style.display='none';
                   11384:         fileid.value = '';
                   11385:     }
                   11386: }
                   11387: // ]]>
                   11388: </script>
                   11389: 
                   11390: END
                   11391: }
                   11392: 
1.661     raeburn  11393: sub upload_embedded {
                   11394:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11395:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11396:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11397:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11398:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11399:         my $orig_uploaded_filename =
                   11400:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11401:         foreach my $type ('orig','ref','attrib','codebase') {
                   11402:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11403:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11404:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11405:             }
                   11406:         }
1.661     raeburn  11407:         my ($path,$fname) =
                   11408:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11409:         # no path, whole string is fname
                   11410:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11411:         $fname = &Apache::lonnet::clean_filename($fname);
                   11412:         # See if there is anything left
                   11413:         next if ($fname eq '');
                   11414: 
                   11415:         # Check if file already exists as a file or directory.
                   11416:         my ($state,$msg);
                   11417:         if ($context eq 'portfolio') {
                   11418:             my $port_path = $dirpath;
                   11419:             if ($group ne '') {
                   11420:                 $port_path = "groups/$group/$port_path";
                   11421:             }
1.987     raeburn  11422:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11423:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11424:                                               $dir_root,$port_path,$disk_quota,
                   11425:                                               $current_disk_usage,$uname,$udom);
                   11426:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11427:                 || $state eq 'file_locked') {
1.661     raeburn  11428:                 $output .= $msg;
                   11429:                 next;
                   11430:             }
                   11431:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11432:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11433:             if ($state eq 'exists') {
                   11434:                 $output .= $msg;
                   11435:                 next;
                   11436:             }
                   11437:         }
                   11438:         # Check if extension is valid
                   11439:         if (($fname =~ /\.(\w+)$/) &&
                   11440:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11441:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11442:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11443:             next;
                   11444:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11445:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11446:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11447:             next;
                   11448:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11449:             $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  11450:             next;
                   11451:         }
                   11452:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11453:         my $subdir = $path;
                   11454:         $subdir =~ s{/+$}{};
1.661     raeburn  11455:         if ($context eq 'portfolio') {
1.984     raeburn  11456:             my $result;
                   11457:             if ($state eq 'existingfile') {
                   11458:                 $result=
                   11459:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11460:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11461:             } else {
1.984     raeburn  11462:                 $result=
                   11463:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11464:                                                     $dirpath.
1.1075.2.35  raeburn  11465:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11466:                 if ($result !~ m|^/uploaded/|) {
                   11467:                     $output .= '<span class="LC_error">'
                   11468:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11469:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11470:                                .'</span><br />';
                   11471:                     next;
                   11472:                 } else {
1.987     raeburn  11473:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11474:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11475:                 }
1.661     raeburn  11476:             }
1.1075.2.35  raeburn  11477:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11478:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11479:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11480:             my $result =
1.1075.2.35  raeburn  11481:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11482:             if ($result !~ m|^/uploaded/|) {
                   11483:                 $output .= '<span class="LC_error">'
                   11484:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11485:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11486:                            .'</span><br />';
                   11487:                     next;
                   11488:             } else {
                   11489:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11490:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11491:                 if ($context eq 'syllabus') {
                   11492:                     &Apache::lonnet::make_public_indefinitely($result);
                   11493:                 }
1.987     raeburn  11494:             }
1.661     raeburn  11495:         } else {
                   11496: # Save the file
                   11497:             my $target = $env{'form.embedded_item_'.$i};
                   11498:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11499:             my $dest = $fullpath.$fname;
                   11500:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11501:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11502:             my $count;
                   11503:             my $filepath = $dir_root;
1.1027    raeburn  11504:             foreach my $subdir (@parts) {
                   11505:                 $filepath .= "/$subdir";
                   11506:                 if (!-e $filepath) {
1.661     raeburn  11507:                     mkdir($filepath,0770);
                   11508:                 }
                   11509:             }
                   11510:             my $fh;
                   11511:             if (!open($fh,'>'.$dest)) {
                   11512:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11513:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11514:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11515:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11516:                            '</span><br />';
                   11517:             } else {
                   11518:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11519:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11520:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11521:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11522:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11523:                               '</span><br />';
                   11524:                 } else {
1.987     raeburn  11525:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11526:                                $url.'</span>').'<br />';
                   11527:                     unless ($context eq 'testbank') {
                   11528:                         $footer .= &mt('View embedded file: [_1]',
                   11529:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11530:                     }
                   11531:                 }
                   11532:                 close($fh);
                   11533:             }
                   11534:         }
                   11535:         if ($env{'form.embedded_ref_'.$i}) {
                   11536:             $pathchange{$i} = 1;
                   11537:         }
                   11538:     }
                   11539:     if ($output) {
                   11540:         $output = '<p>'.$output.'</p>';
                   11541:     }
                   11542:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11543:     $returnflag = 'ok';
1.1071    raeburn  11544:     my $numpathchgs = scalar(keys(%pathchange));
                   11545:     if ($numpathchgs > 0) {
1.987     raeburn  11546:         if ($context eq 'portfolio') {
                   11547:             $output .= '<p>'.&mt('or').'</p>';
                   11548:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11549:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11550:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11551:             $returnflag = 'modify_orightml';
                   11552:         }
                   11553:     }
1.1071    raeburn  11554:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11555: }
                   11556: 
                   11557: sub modify_html_form {
                   11558:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11559:     my $end = 0;
                   11560:     my $modifyform;
                   11561:     if ($context eq 'upload_embedded') {
                   11562:         return unless (ref($pathchange) eq 'HASH');
                   11563:         if ($env{'form.number_embedded_items'}) {
                   11564:             $end += $env{'form.number_embedded_items'};
                   11565:         }
                   11566:         if ($env{'form.number_pathchange_items'}) {
                   11567:             $end += $env{'form.number_pathchange_items'};
                   11568:         }
                   11569:         if ($end) {
                   11570:             for (my $i=0; $i<$end; $i++) {
                   11571:                 if ($i < $env{'form.number_embedded_items'}) {
                   11572:                     next unless($pathchange->{$i});
                   11573:                 }
                   11574:                 $modifyform .=
                   11575:                     &start_data_table_row().
                   11576:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11577:                     'checked="checked" /></td>'.
                   11578:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11579:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11580:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11581:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11582:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11583:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11584:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11585:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11586:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11587:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11588:                     &end_data_table_row();
1.1071    raeburn  11589:             }
1.987     raeburn  11590:         }
                   11591:     } else {
                   11592:         $modifyform = $pathchgtable;
                   11593:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11594:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11595:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11596:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11597:         }
                   11598:     }
                   11599:     if ($modifyform) {
1.1071    raeburn  11600:         if ($actionurl eq '/adm/dependencies') {
                   11601:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11602:         }
1.987     raeburn  11603:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11604:                '<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".
                   11605:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11606:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11607:                '</ol></p>'."\n".'<p>'.
                   11608:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11609:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11610:                &start_data_table()."\n".
                   11611:                &start_data_table_header_row().
                   11612:                '<th>'.&mt('Change?').'</th>'.
                   11613:                '<th>'.&mt('Current reference').'</th>'.
                   11614:                '<th>'.&mt('Required reference').'</th>'.
                   11615:                &end_data_table_header_row()."\n".
                   11616:                $modifyform.
                   11617:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11618:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11619:                '</form>'."\n";
                   11620:     }
                   11621:     return;
                   11622: }
                   11623: 
                   11624: sub modify_html_refs {
1.1075.2.35  raeburn  11625:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11626:     my $container;
                   11627:     if ($context eq 'portfolio') {
                   11628:         $container = $env{'form.container'};
                   11629:     } elsif ($context eq 'coursedoc') {
                   11630:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11631:     } elsif ($context eq 'manage_dependencies') {
                   11632:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11633:         $container = "/$container";
1.1075.2.35  raeburn  11634:     } elsif ($context eq 'syllabus') {
                   11635:         $container = $url;
1.987     raeburn  11636:     } else {
1.1027    raeburn  11637:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11638:     }
                   11639:     my (%allfiles,%codebase,$output,$content);
                   11640:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11641:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11642:         if (wantarray) {
                   11643:             return ('',0,0); 
                   11644:         } else {
                   11645:             return;
                   11646:         }
                   11647:     }
                   11648:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11649:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11650:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11651:             if (wantarray) {
                   11652:                 return ('',0,0);
                   11653:             } else {
                   11654:                 return;
                   11655:             }
                   11656:         } 
1.987     raeburn  11657:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11658:         if ($content eq '-1') {
                   11659:             if (wantarray) {
                   11660:                 return ('',0,0);
                   11661:             } else {
                   11662:                 return;
                   11663:             }
                   11664:         }
1.987     raeburn  11665:     } else {
1.1071    raeburn  11666:         unless ($container =~ /^\Q$dir_root\E/) {
                   11667:             if (wantarray) {
                   11668:                 return ('',0,0);
                   11669:             } else {
                   11670:                 return;
                   11671:             }
                   11672:         } 
1.1075.2.128  raeburn  11673:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11674:             $content = join('', <$fh>);
                   11675:             close($fh);
                   11676:         } else {
1.1071    raeburn  11677:             if (wantarray) {
                   11678:                 return ('',0,0);
                   11679:             } else {
                   11680:                 return;
                   11681:             }
1.987     raeburn  11682:         }
                   11683:     }
                   11684:     my ($count,$codebasecount) = (0,0);
                   11685:     my $mm = new File::MMagic;
                   11686:     my $mime_type = $mm->checktype_contents($content);
                   11687:     if ($mime_type eq 'text/html') {
                   11688:         my $parse_result = 
                   11689:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11690:                                                     \%codebase,\$content);
                   11691:         if ($parse_result eq 'ok') {
                   11692:             foreach my $i (@changes) {
                   11693:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11694:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11695:                 if ($allfiles{$ref}) {
                   11696:                     my $newname =  $orig;
                   11697:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11698:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11699:                     if ($attrib_regexp =~ /:/) {
                   11700:                         $attrib_regexp =~ s/\:/|/g;
                   11701:                     }
                   11702:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11703:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11704:                         $count += $numchg;
1.1075.2.35  raeburn  11705:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11706:                         delete($allfiles{$ref});
1.987     raeburn  11707:                     }
                   11708:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11709:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11710:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11711:                         $codebasecount ++;
                   11712:                     }
                   11713:                 }
                   11714:             }
1.1075.2.35  raeburn  11715:             my $skiprewrites;
1.987     raeburn  11716:             if ($count || $codebasecount) {
                   11717:                 my $saveresult;
1.1071    raeburn  11718:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11719:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11720:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11721:                     if ($url eq $container) {
                   11722:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11723:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11724:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11725:                                             $fname.'</span>').'</p>';
1.987     raeburn  11726:                     } else {
                   11727:                          $output = '<p class="LC_error">'.
                   11728:                                    &mt('Error: update failed for: [_1].',
                   11729:                                    '<span class="LC_filename">'.
                   11730:                                    $container.'</span>').'</p>';
                   11731:                     }
1.1075.2.35  raeburn  11732:                     if ($context eq 'syllabus') {
                   11733:                         unless ($saveresult eq 'ok') {
                   11734:                             $skiprewrites = 1;
                   11735:                         }
                   11736:                     }
1.987     raeburn  11737:                 } else {
1.1075.2.128  raeburn  11738:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11739:                         print $fh $content;
                   11740:                         close($fh);
                   11741:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11742:                                   $count,'<span class="LC_filename">'.
                   11743:                                   $container.'</span>').'</p>';
1.661     raeburn  11744:                     } else {
1.987     raeburn  11745:                          $output = '<p class="LC_error">'.
                   11746:                                    &mt('Error: could not update [_1].',
                   11747:                                    '<span class="LC_filename">'.
                   11748:                                    $container.'</span>').'</p>';
1.661     raeburn  11749:                     }
                   11750:                 }
                   11751:             }
1.1075.2.35  raeburn  11752:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11753:                 my ($actionurl,$state);
                   11754:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11755:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11756:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11757:                                               \%codebase,
                   11758:                                               {'context' => 'rewrites',
                   11759:                                                'ignore_remote_references' => 1,});
                   11760:                 if (ref($mapping) eq 'HASH') {
                   11761:                     my $rewrites = 0;
                   11762:                     foreach my $key (keys(%{$mapping})) {
                   11763:                         next if ($key =~ m{^https?://});
                   11764:                         my $ref = $mapping->{$key};
                   11765:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11766:                         my $attrib;
                   11767:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11768:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11769:                         }
                   11770:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11771:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11772:                             $rewrites += $numchg;
                   11773:                         }
                   11774:                     }
                   11775:                     if ($rewrites) {
                   11776:                         my $saveresult;
                   11777:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11778:                         if ($url eq $container) {
                   11779:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11780:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11781:                                             $count,'<span class="LC_filename">'.
                   11782:                                             $fname.'</span>').'</p>';
                   11783:                         } else {
                   11784:                             $output .= '<p class="LC_error">'.
                   11785:                                        &mt('Error: could not update links in [_1].',
                   11786:                                        '<span class="LC_filename">'.
                   11787:                                        $container.'</span>').'</p>';
                   11788: 
                   11789:                         }
                   11790:                     }
                   11791:                 }
                   11792:             }
1.987     raeburn  11793:         } else {
                   11794:             &logthis('Failed to parse '.$container.
                   11795:                      ' to modify references: '.$parse_result);
1.661     raeburn  11796:         }
                   11797:     }
1.1071    raeburn  11798:     if (wantarray) {
                   11799:         return ($output,$count,$codebasecount);
                   11800:     } else {
                   11801:         return $output;
                   11802:     }
1.661     raeburn  11803: }
                   11804: 
                   11805: sub check_for_existing {
                   11806:     my ($path,$fname,$element) = @_;
                   11807:     my ($state,$msg);
                   11808:     if (-d $path.'/'.$fname) {
                   11809:         $state = 'exists';
                   11810:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11811:     } elsif (-e $path.'/'.$fname) {
                   11812:         $state = 'exists';
                   11813:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11814:     }
                   11815:     if ($state eq 'exists') {
                   11816:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11817:     }
                   11818:     return ($state,$msg);
                   11819: }
                   11820: 
                   11821: sub check_for_upload {
                   11822:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11823:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11824:     my $filesize = length($env{'form.'.$element});
                   11825:     if (!$filesize) {
                   11826:         my $msg = '<span class="LC_error">'.
                   11827:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11828:                       '<span class="LC_filename">'.$fname.'</span>',
                   11829:                       $filesize).'<br />'.
1.1007    raeburn  11830:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11831:                   '</span>';
                   11832:         return ('zero_bytes',$msg);
                   11833:     }
                   11834:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11835:     my $getpropath = 1;
1.1021    raeburn  11836:     my ($dirlistref,$listerror) =
                   11837:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11838:     my $found_file = 0;
                   11839:     my $locked_file = 0;
1.991     raeburn  11840:     my @lockers;
                   11841:     my $navmap;
                   11842:     if ($env{'request.course.id'}) {
                   11843:         $navmap = Apache::lonnavmaps::navmap->new();
                   11844:     }
1.1021    raeburn  11845:     if (ref($dirlistref) eq 'ARRAY') {
                   11846:         foreach my $line (@{$dirlistref}) {
                   11847:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11848:             if ($file_name eq $fname){
                   11849:                 $file_name = $path.$file_name;
                   11850:                 if ($group ne '') {
                   11851:                     $file_name = $group.$file_name;
                   11852:                 }
                   11853:                 $found_file = 1;
                   11854:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11855:                     foreach my $lock (@lockers) {
                   11856:                         if (ref($lock) eq 'ARRAY') {
                   11857:                             my ($symb,$crsid) = @{$lock};
                   11858:                             if ($crsid eq $env{'request.course.id'}) {
                   11859:                                 if (ref($navmap)) {
                   11860:                                     my $res = $navmap->getBySymb($symb);
                   11861:                                     foreach my $part (@{$res->parts()}) { 
                   11862:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11863:                                         unless (($slot_status == $res->RESERVED) ||
                   11864:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11865:                                             $locked_file = 1;
                   11866:                                         }
1.991     raeburn  11867:                                     }
1.1021    raeburn  11868:                                 } else {
                   11869:                                     $locked_file = 1;
1.991     raeburn  11870:                                 }
                   11871:                             } else {
                   11872:                                 $locked_file = 1;
                   11873:                             }
                   11874:                         }
1.1021    raeburn  11875:                    }
                   11876:                 } else {
                   11877:                     my @info = split(/\&/,$rest);
                   11878:                     my $currsize = $info[6]/1000;
                   11879:                     if ($currsize < $filesize) {
                   11880:                         my $extra = $filesize - $currsize;
                   11881:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11882:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11883:                                       &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  11884:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11885:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11886:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11887:                             return ('will_exceed_quota',$msg);
                   11888:                         }
1.984     raeburn  11889:                     }
                   11890:                 }
1.661     raeburn  11891:             }
                   11892:         }
                   11893:     }
                   11894:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11895:         my $msg = '<p class="LC_warning">'.
                   11896:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11897:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11898:         return ('will_exceed_quota',$msg);
                   11899:     } elsif ($found_file) {
                   11900:         if ($locked_file) {
1.1075.2.69  raeburn  11901:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11902:             $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  11903:             $msg .= '</p>';
1.661     raeburn  11904:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11905:             return ('file_locked',$msg);
                   11906:         } else {
1.1075.2.69  raeburn  11907:             my $msg = '<p class="LC_error">';
1.984     raeburn  11908:             $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  11909:             $msg .= '</p>';
1.984     raeburn  11910:             return ('existingfile',$msg);
1.661     raeburn  11911:         }
                   11912:     }
                   11913: }
                   11914: 
1.987     raeburn  11915: sub check_for_traversal {
                   11916:     my ($path,$url,$toplevel) = @_;
                   11917:     my @parts=split(/\//,$path);
                   11918:     my $cleanpath;
                   11919:     my $fullpath = $url;
                   11920:     for (my $i=0;$i<@parts;$i++) {
                   11921:         next if ($parts[$i] eq '.');
                   11922:         if ($parts[$i] eq '..') {
                   11923:             $fullpath =~ s{([^/]+/)$}{};
                   11924:         } else {
                   11925:             $fullpath .= $parts[$i].'/';
                   11926:         }
                   11927:     }
                   11928:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11929:         $cleanpath = $1;
                   11930:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11931:         my $curr_toprel = $1;
                   11932:         my @parts = split(/\//,$curr_toprel);
                   11933:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11934:         my @urlparts = split(/\//,$url_toprel);
                   11935:         my $doubledots;
                   11936:         my $startdiff = -1;
                   11937:         for (my $i=0; $i<@urlparts; $i++) {
                   11938:             if ($startdiff == -1) {
                   11939:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11940:                     $startdiff = $i;
                   11941:                     $doubledots .= '../';
                   11942:                 }
                   11943:             } else {
                   11944:                 $doubledots .= '../';
                   11945:             }
                   11946:         }
                   11947:         if ($startdiff > -1) {
                   11948:             $cleanpath = $doubledots;
                   11949:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11950:                 $cleanpath .= $parts[$i].'/';
                   11951:             }
                   11952:         }
                   11953:     }
                   11954:     $cleanpath =~ s{(/)$}{};
                   11955:     return $cleanpath;
                   11956: }
1.31      albertel 11957: 
1.1053    raeburn  11958: sub is_archive_file {
                   11959:     my ($mimetype) = @_;
                   11960:     if (($mimetype eq 'application/octet-stream') ||
                   11961:         ($mimetype eq 'application/x-stuffit') ||
                   11962:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11963:         return 1;
                   11964:     }
                   11965:     return;
                   11966: }
                   11967: 
                   11968: sub decompress_form {
1.1065    raeburn  11969:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11970:     my %lt = &Apache::lonlocal::texthash (
                   11971:         this => 'This file is an archive file.',
1.1067    raeburn  11972:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11973:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11974:         youm => 'You may wish to extract its contents.',
                   11975:         extr => 'Extract contents',
1.1067    raeburn  11976:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11977:         proa => 'Process automatically?',
1.1053    raeburn  11978:         yes  => 'Yes',
                   11979:         no   => 'No',
1.1067    raeburn  11980:         fold => 'Title for folder containing movie',
                   11981:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11982:     );
1.1065    raeburn  11983:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11984:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11985:     my $info = &list_archive_contents($fileloc,\@paths);
                   11986:     if (@paths) {
                   11987:         foreach my $path (@paths) {
                   11988:             $path =~ s{^/}{};
1.1067    raeburn  11989:             if ($path =~ m{^([^/]+)/$}) {
                   11990:                 $topdir = $1;
                   11991:             }
1.1065    raeburn  11992:             if ($path =~ m{^([^/]+)/}) {
                   11993:                 $toplevel{$1} = $path;
                   11994:             } else {
                   11995:                 $toplevel{$path} = $path;
                   11996:             }
                   11997:         }
                   11998:     }
1.1067    raeburn  11999:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12000:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12001:                         "$topdir/media/",
                   12002:                         "$topdir/media/$topdir.mp4",
                   12003:                         "$topdir/media/FirstFrame.png",
                   12004:                         "$topdir/media/player.swf",
                   12005:                         "$topdir/media/swfobject.js",
                   12006:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12007:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12008:                          "$topdir/$topdir.mp4",
                   12009:                          "$topdir/$topdir\_config.xml",
                   12010:                          "$topdir/$topdir\_controller.swf",
                   12011:                          "$topdir/$topdir\_embed.css",
                   12012:                          "$topdir/$topdir\_First_Frame.png",
                   12013:                          "$topdir/$topdir\_player.html",
                   12014:                          "$topdir/$topdir\_Thumbnails.png",
                   12015:                          "$topdir/playerProductInstall.swf",
                   12016:                          "$topdir/scripts/",
                   12017:                          "$topdir/scripts/config_xml.js",
                   12018:                          "$topdir/scripts/handlebars.js",
                   12019:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12020:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12021:                          "$topdir/scripts/modernizr.js",
                   12022:                          "$topdir/scripts/player-min.js",
                   12023:                          "$topdir/scripts/swfobject.js",
                   12024:                          "$topdir/skins/",
                   12025:                          "$topdir/skins/configuration_express.xml",
                   12026:                          "$topdir/skins/express_show/",
                   12027:                          "$topdir/skins/express_show/player-min.css",
                   12028:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12029:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12030:                          "$topdir/$topdir.mp4",
                   12031:                          "$topdir/$topdir\_config.xml",
                   12032:                          "$topdir/$topdir\_controller.swf",
                   12033:                          "$topdir/$topdir\_embed.css",
                   12034:                          "$topdir/$topdir\_First_Frame.png",
                   12035:                          "$topdir/$topdir\_player.html",
                   12036:                          "$topdir/$topdir\_Thumbnails.png",
                   12037:                          "$topdir/playerProductInstall.swf",
                   12038:                          "$topdir/scripts/",
                   12039:                          "$topdir/scripts/config_xml.js",
                   12040:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12041:                          "$topdir/skins/",
                   12042:                          "$topdir/skins/configuration_express.xml",
                   12043:                          "$topdir/skins/express_show/",
                   12044:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12045:                          "$topdir/skins/express_show/spritesheet.png",
                   12046:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12047:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12048:         if (@diffs == 0) {
1.1075.2.59  raeburn  12049:             $is_camtasia = 6;
                   12050:         } else {
1.1075.2.81  raeburn  12051:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12052:             if (@diffs == 0) {
                   12053:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12054:             } else {
                   12055:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12056:                 if (@diffs == 0) {
                   12057:                     $is_camtasia = 8;
                   12058:                 }
1.1075.2.59  raeburn  12059:             }
1.1067    raeburn  12060:         }
                   12061:     }
                   12062:     my $output;
                   12063:     if ($is_camtasia) {
                   12064:         $output = <<"ENDCAM";
                   12065: <script type="text/javascript" language="Javascript">
                   12066: // <![CDATA[
                   12067: 
                   12068: function camtasiaToggle() {
                   12069:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12070:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12071:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12072:                 document.getElementById('camtasia_titles').style.display='block';
                   12073:             } else {
                   12074:                 document.getElementById('camtasia_titles').style.display='none';
                   12075:             }
                   12076:         }
                   12077:     }
                   12078:     return;
                   12079: }
                   12080: 
                   12081: // ]]>
                   12082: </script>
                   12083: <p>$lt{'camt'}</p>
                   12084: ENDCAM
1.1065    raeburn  12085:     } else {
1.1067    raeburn  12086:         $output = '<p>'.$lt{'this'};
                   12087:         if ($info eq '') {
                   12088:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12089:         } else {
                   12090:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12091:                        '<div><pre>'.$info.'</pre></div>';
                   12092:         }
1.1065    raeburn  12093:     }
1.1067    raeburn  12094:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12095:     my $duplicates;
                   12096:     my $num = 0;
                   12097:     if (ref($dirlist) eq 'ARRAY') {
                   12098:         foreach my $item (@{$dirlist}) {
                   12099:             if (ref($item) eq 'ARRAY') {
                   12100:                 if (exists($toplevel{$item->[0]})) {
                   12101:                     $duplicates .= 
                   12102:                         &start_data_table_row().
                   12103:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12104:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12105:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12106:                         'value="1" />'.&mt('Yes').'</label>'.
                   12107:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12108:                         '<td>'.$item->[0].'</td>';
                   12109:                     if ($item->[2]) {
                   12110:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12111:                     } else {
                   12112:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12113:                     }
                   12114:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12115:                                    '<td>'.
                   12116:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12117:                                    '</td>'.
                   12118:                                    &end_data_table_row();
                   12119:                     $num ++;
                   12120:                 }
                   12121:             }
                   12122:         }
                   12123:     }
                   12124:     my $itemcount;
                   12125:     if (@paths > 0) {
                   12126:         $itemcount = scalar(@paths);
                   12127:     } else {
                   12128:         $itemcount = 1;
                   12129:     }
1.1067    raeburn  12130:     if ($is_camtasia) {
                   12131:         $output .= $lt{'auto'}.'<br />'.
                   12132:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12133:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12134:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12135:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12136:                    $lt{'no'}.'</label></span><br />'.
                   12137:                    '<div id="camtasia_titles" style="display:block">'.
                   12138:                    &Apache::lonhtmlcommon::start_pick_box().
                   12139:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12140:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12141:                    &Apache::lonhtmlcommon::row_closure().
                   12142:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12143:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12144:                    &Apache::lonhtmlcommon::row_closure(1).
                   12145:                    &Apache::lonhtmlcommon::end_pick_box().
                   12146:                    '</div>';
                   12147:     }
1.1065    raeburn  12148:     $output .= 
                   12149:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12150:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12151:         "\n";
1.1065    raeburn  12152:     if ($duplicates ne '') {
                   12153:         $output .= '<p><span class="LC_warning">'.
                   12154:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12155:                    &start_data_table().
                   12156:                    &start_data_table_header_row().
                   12157:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12158:                    '<th>'.&mt('Name').'</th>'.
                   12159:                    '<th>'.&mt('Type').'</th>'.
                   12160:                    '<th>'.&mt('Size').'</th>'.
                   12161:                    '<th>'.&mt('Last modified').'</th>'.
                   12162:                    &end_data_table_header_row().
                   12163:                    $duplicates.
                   12164:                    &end_data_table().
                   12165:                    '</p>';
                   12166:     }
1.1067    raeburn  12167:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12168:     if (ref($hiddenelements) eq 'HASH') {
                   12169:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12170:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12171:         }
                   12172:     }
                   12173:     $output .= <<"END";
1.1067    raeburn  12174: <br />
1.1053    raeburn  12175: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12176: </form>
                   12177: $noextract
                   12178: END
                   12179:     return $output;
                   12180: }
                   12181: 
1.1065    raeburn  12182: sub decompression_utility {
                   12183:     my ($program) = @_;
                   12184:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12185:     my $location;
                   12186:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12187:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12188:                          '/usr/sbin/') {
                   12189:             if (-x $dir.$program) {
                   12190:                 $location = $dir.$program;
                   12191:                 last;
                   12192:             }
                   12193:         }
                   12194:     }
                   12195:     return $location;
                   12196: }
                   12197: 
                   12198: sub list_archive_contents {
                   12199:     my ($file,$pathsref) = @_;
                   12200:     my (@cmd,$output);
                   12201:     my $needsregexp;
                   12202:     if ($file =~ /\.zip$/) {
                   12203:         @cmd = (&decompression_utility('unzip'),"-l");
                   12204:         $needsregexp = 1;
                   12205:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12206:              ($file =~ /\.tgz$/)) {
                   12207:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12208:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12209:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12210:     } elsif ($file =~ m|\.tar$|) {
                   12211:         @cmd = (&decompression_utility('tar'),"-tf");
                   12212:     }
                   12213:     if (@cmd) {
                   12214:         undef($!);
                   12215:         undef($@);
                   12216:         if (open(my $fh,"-|", @cmd, $file)) {
                   12217:             while (my $line = <$fh>) {
                   12218:                 $output .= $line;
                   12219:                 chomp($line);
                   12220:                 my $item;
                   12221:                 if ($needsregexp) {
                   12222:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12223:                 } else {
                   12224:                     $item = $line;
                   12225:                 }
                   12226:                 if ($item ne '') {
                   12227:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12228:                         push(@{$pathsref},$item);
                   12229:                     } 
                   12230:                 }
                   12231:             }
                   12232:             close($fh);
                   12233:         }
                   12234:     }
                   12235:     return $output;
                   12236: }
                   12237: 
1.1053    raeburn  12238: sub decompress_uploaded_file {
                   12239:     my ($file,$dir) = @_;
                   12240:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12241:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12242:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12243:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12244:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12245:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12246:     my $decompressed = $env{'cgi.decompressed'};
                   12247:     &Apache::lonnet::delenv('cgi.file');
                   12248:     &Apache::lonnet::delenv('cgi.dir');
                   12249:     &Apache::lonnet::delenv('cgi.decompressed');
                   12250:     return ($decompressed,$result);
                   12251: }
                   12252: 
1.1055    raeburn  12253: sub process_decompression {
                   12254:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12255:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12256:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12257:                &mt('Unexpected file path.').'</p>'."\n";
                   12258:     }
                   12259:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12260:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12261:                &mt('Unexpected course context.').'</p>'."\n";
                   12262:     }
                   12263:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12264:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12265:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12266:     }
1.1055    raeburn  12267:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12268:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12269:         $error = &mt('Filename not a supported archive file type.').
                   12270:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12271:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12272:     } else {
                   12273:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12274:         if ($docuhome eq 'no_host') {
                   12275:             $error = &mt('Could not determine home server for course.');
                   12276:         } else {
                   12277:             my @ids=&Apache::lonnet::current_machine_ids();
                   12278:             my $currdir = "$dir_root/$destination";
                   12279:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12280:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12281:                        "$dir_root/$destination";
                   12282:             } else {
                   12283:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12284:                        "$dir_root/$docudom/$docuname/$destination";
                   12285:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12286:                     $error = &mt('Archive file not found.');
                   12287:                 }
                   12288:             }
1.1065    raeburn  12289:             my (@to_overwrite,@to_skip);
                   12290:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12291:                 my $total = $env{'form.archive_overwrite_total'};
                   12292:                 for (my $i=0; $i<$total; $i++) {
                   12293:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12294:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12295:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12296:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12297:                     }
                   12298:                 }
                   12299:             }
                   12300:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12301:             my $numoverwrite = scalar(@to_overwrite);
                   12302:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12303:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12304:             } elsif ($dir eq '') {
1.1055    raeburn  12305:                 $error = &mt('Directory containing archive file unavailable.');
                   12306:             } elsif (!$error) {
1.1065    raeburn  12307:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12308:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12309:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12310:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12311:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12312:                         ($decompressed,$display) =
                   12313:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12314:                         foreach my $item (@to_skip) {
                   12315:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12316:                                 if (-f "$dir/$tempdir/$item") {
                   12317:                                     unlink("$dir/$tempdir/$item");
                   12318:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12319:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12320:                                 }
                   12321:                             }
                   12322:                         }
                   12323:                         foreach my $item (@to_overwrite) {
                   12324:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12325:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12326:                                     if (-f "$dir/$item") {
                   12327:                                         unlink("$dir/$item");
                   12328:                                     } elsif (-d "$dir/$item") {
                   12329:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12330:                                     }
                   12331:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12332:                                 }
1.1065    raeburn  12333:                             }
                   12334:                         }
1.1075.2.128  raeburn  12335:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12336:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12337:                         }
1.1065    raeburn  12338:                     }
                   12339:                 } else {
                   12340:                     ($decompressed,$display) = 
                   12341:                         &decompress_uploaded_file($file,$dir);
                   12342:                 }
1.1055    raeburn  12343:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12344:                     $output = '<p class="LC_info">'.
                   12345:                               &mt('Files extracted successfully from archive.').
                   12346:                               '</p>'."\n";
1.1055    raeburn  12347:                     my ($warning,$result,@contents);
                   12348:                     my ($newdirlistref,$newlisterror) =
                   12349:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12350:                                                  $docuname,1);
                   12351:                     my (%is_dir,%changes,@newitems);
                   12352:                     my $dirptr = 16384;
1.1065    raeburn  12353:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12354:                         foreach my $dir_line (@{$newdirlistref}) {
                   12355:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12356:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12357:                                 push(@newitems,$item);
                   12358:                                 if ($dirptr&$testdir) {
                   12359:                                     $is_dir{$item} = 1;
                   12360:                                 }
                   12361:                                 $changes{$item} = 1;
                   12362:                             }
                   12363:                         }
                   12364:                     }
                   12365:                     if (keys(%changes) > 0) {
                   12366:                         foreach my $item (sort(@newitems)) {
                   12367:                             if ($changes{$item}) {
                   12368:                                 push(@contents,$item);
                   12369:                             }
                   12370:                         }
                   12371:                     }
                   12372:                     if (@contents > 0) {
1.1067    raeburn  12373:                         my $wantform;
                   12374:                         unless ($env{'form.autoextract_camtasia'}) {
                   12375:                             $wantform = 1;
                   12376:                         }
1.1056    raeburn  12377:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12378:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12379:                                                                 $currdir,\%is_dir,
                   12380:                                                                 \%children,\%parent,
1.1056    raeburn  12381:                                                                 \@contents,\%dirorder,
                   12382:                                                                 \%titles,$wantform);
1.1055    raeburn  12383:                         if ($datatable ne '') {
                   12384:                             $output .= &archive_options_form('decompressed',$datatable,
                   12385:                                                              $count,$hiddenelem);
1.1065    raeburn  12386:                             my $startcount = 6;
1.1055    raeburn  12387:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12388:                                                            \%titles,\%children);
1.1055    raeburn  12389:                         }
1.1067    raeburn  12390:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12391:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12392:                             my %displayed;
                   12393:                             my $total = 1;
                   12394:                             $env{'form.archive_directory'} = [];
                   12395:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12396:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12397:                                 $path =~ s{/$}{};
                   12398:                                 my $item;
                   12399:                                 if ($path ne '') {
                   12400:                                     $item = "$path/$titles{$i}";
                   12401:                                 } else {
                   12402:                                     $item = $titles{$i};
                   12403:                                 }
                   12404:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12405:                                 if ($item eq $contents[0]) {
                   12406:                                     push(@{$env{'form.archive_directory'}},$i);
                   12407:                                     $env{'form.archive_'.$i} = 'display';
                   12408:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12409:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12410:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12411:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12412:                                     $env{'form.archive_'.$i} = 'display';
                   12413:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12414:                                     $displayed{'web'} = $i;
                   12415:                                 } else {
1.1075.2.59  raeburn  12416:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12417:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12418:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12419:                                         push(@{$env{'form.archive_directory'}},$i);
                   12420:                                     }
                   12421:                                     $env{'form.archive_'.$i} = 'dependency';
                   12422:                                 }
                   12423:                                 $total ++;
                   12424:                             }
                   12425:                             for (my $i=1; $i<$total; $i++) {
                   12426:                                 next if ($i == $displayed{'web'});
                   12427:                                 next if ($i == $displayed{'folder'});
                   12428:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12429:                             }
                   12430:                             $env{'form.phase'} = 'decompress_cleanup';
                   12431:                             $env{'form.archivedelete'} = 1;
                   12432:                             $env{'form.archive_count'} = $total-1;
                   12433:                             $output .=
                   12434:                                 &process_extracted_files('coursedocs',$docudom,
                   12435:                                                          $docuname,$destination,
                   12436:                                                          $dir_root,$hiddenelem);
                   12437:                         }
1.1055    raeburn  12438:                     } else {
                   12439:                         $warning = &mt('No new items extracted from archive file.');
                   12440:                     }
                   12441:                 } else {
                   12442:                     $output = $display;
                   12443:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12444:                 }
                   12445:             }
                   12446:         }
                   12447:     }
                   12448:     if ($error) {
                   12449:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12450:                    $error.'</p>'."\n";
                   12451:     }
                   12452:     if ($warning) {
                   12453:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12454:     }
                   12455:     return $output;
                   12456: }
                   12457: 
                   12458: sub get_extracted {
1.1056    raeburn  12459:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12460:         $titles,$wantform) = @_;
1.1055    raeburn  12461:     my $count = 0;
                   12462:     my $depth = 0;
                   12463:     my $datatable;
1.1056    raeburn  12464:     my @hierarchy;
1.1055    raeburn  12465:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12466:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12467:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12468:     foreach my $item (@{$contents}) {
                   12469:         $count ++;
1.1056    raeburn  12470:         @{$dirorder->{$count}} = @hierarchy;
                   12471:         $titles->{$count} = $item;
1.1055    raeburn  12472:         &archive_hierarchy($depth,$count,$parent,$children);
                   12473:         if ($wantform) {
                   12474:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12475:                                        $currdir,$depth,$count);
                   12476:         }
                   12477:         if ($is_dir->{$item}) {
                   12478:             $depth ++;
1.1056    raeburn  12479:             push(@hierarchy,$count);
                   12480:             $parent->{$depth} = $count;
1.1055    raeburn  12481:             $datatable .=
                   12482:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12483:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12484:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12485:             $depth --;
1.1056    raeburn  12486:             pop(@hierarchy);
1.1055    raeburn  12487:         }
                   12488:     }
                   12489:     return ($count,$datatable);
                   12490: }
                   12491: 
                   12492: sub recurse_extracted_archive {
1.1056    raeburn  12493:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12494:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12495:     my $result='';
1.1056    raeburn  12496:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12497:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12498:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12499:         return $result;
                   12500:     }
                   12501:     my $dirptr = 16384;
                   12502:     my ($newdirlistref,$newlisterror) =
                   12503:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12504:     if (ref($newdirlistref) eq 'ARRAY') {
                   12505:         foreach my $dir_line (@{$newdirlistref}) {
                   12506:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12507:             unless ($item =~ /^\.+$/) {
                   12508:                 $$count ++;
1.1056    raeburn  12509:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12510:                 $titles->{$$count} = $item;
1.1055    raeburn  12511:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12512: 
1.1055    raeburn  12513:                 my $is_dir;
                   12514:                 if ($dirptr&$testdir) {
                   12515:                     $is_dir = 1;
                   12516:                 }
                   12517:                 if ($wantform) {
                   12518:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12519:                 }
                   12520:                 if ($is_dir) {
                   12521:                     $$depth ++;
1.1056    raeburn  12522:                     push(@{$hierarchy},$$count);
                   12523:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12524:                     $result .=
                   12525:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12526:                                                    $docuname,$depth,$count,
1.1056    raeburn  12527:                                                    $hierarchy,$dirorder,$children,
                   12528:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12529:                     $$depth --;
1.1056    raeburn  12530:                     pop(@{$hierarchy});
1.1055    raeburn  12531:                 }
                   12532:             }
                   12533:         }
                   12534:     }
                   12535:     return $result;
                   12536: }
                   12537: 
                   12538: sub archive_hierarchy {
                   12539:     my ($depth,$count,$parent,$children) =@_;
                   12540:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12541:         if (exists($parent->{$depth})) {
                   12542:              $children->{$parent->{$depth}} .= $count.':';
                   12543:         }
                   12544:     }
                   12545:     return;
                   12546: }
                   12547: 
                   12548: sub archive_row {
                   12549:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12550:     my ($name) = ($item =~ m{([^/]+)$});
                   12551:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12552:                                        'display'    => 'Add as file',
1.1055    raeburn  12553:                                        'dependency' => 'Include as dependency',
                   12554:                                        'discard'    => 'Discard',
                   12555:                                       );
                   12556:     if ($is_dir) {
1.1059    raeburn  12557:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12558:     }
1.1056    raeburn  12559:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12560:     my $offset = 0;
1.1055    raeburn  12561:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12562:         $offset ++;
1.1065    raeburn  12563:         if ($action ne 'display') {
                   12564:             $offset ++;
                   12565:         }  
1.1055    raeburn  12566:         $output .= '<td><span class="LC_nobreak">'.
                   12567:                    '<label><input type="radio" name="archive_'.$count.
                   12568:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12569:         my $text = $choices{$action};
                   12570:         if ($is_dir) {
                   12571:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12572:             if ($action eq 'display') {
1.1059    raeburn  12573:                 $text = &mt('Add as folder');
1.1055    raeburn  12574:             }
1.1056    raeburn  12575:         } else {
                   12576:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12577: 
                   12578:         }
                   12579:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12580:         if ($action eq 'dependency') {
                   12581:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12582:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12583:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12584:                        '<option value=""></option>'."\n".
                   12585:                        '</select>'."\n".
                   12586:                        '</div>';
1.1059    raeburn  12587:         } elsif ($action eq 'display') {
                   12588:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12589:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12590:                        '</div>';
1.1055    raeburn  12591:         }
1.1056    raeburn  12592:         $output .= '</td>';
1.1055    raeburn  12593:     }
                   12594:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12595:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12596:     for (my $i=0; $i<$depth; $i++) {
                   12597:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12598:     }
                   12599:     if ($is_dir) {
                   12600:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12601:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12602:     } else {
                   12603:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12604:     }
                   12605:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12606:                &end_data_table_row();
                   12607:     return $output;
                   12608: }
                   12609: 
                   12610: sub archive_options_form {
1.1065    raeburn  12611:     my ($form,$display,$count,$hiddenelem) = @_;
                   12612:     my %lt = &Apache::lonlocal::texthash(
                   12613:                perm => 'Permanently remove archive file?',
                   12614:                hows => 'How should each extracted item be incorporated in the course?',
                   12615:                cont => 'Content actions for all',
                   12616:                addf => 'Add as folder/file',
                   12617:                incd => 'Include as dependency for a displayed file',
                   12618:                disc => 'Discard',
                   12619:                no   => 'No',
                   12620:                yes  => 'Yes',
                   12621:                save => 'Save',
                   12622:     );
                   12623:     my $output = <<"END";
                   12624: <form name="$form" method="post" action="">
                   12625: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12626: <label>
                   12627:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12628: </label>
                   12629: &nbsp;
                   12630: <label>
                   12631:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12632: </span>
                   12633: </p>
                   12634: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12635: <br />$lt{'hows'}
                   12636: <div class="LC_columnSection">
                   12637:   <fieldset>
                   12638:     <legend>$lt{'cont'}</legend>
                   12639:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12640:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12641:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12642:   </fieldset>
                   12643: </div>
                   12644: END
                   12645:     return $output.
1.1055    raeburn  12646:            &start_data_table()."\n".
1.1065    raeburn  12647:            $display."\n".
1.1055    raeburn  12648:            &end_data_table()."\n".
                   12649:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12650:            $hiddenelem.
1.1065    raeburn  12651:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12652:            '</form>';
                   12653: }
                   12654: 
                   12655: sub archive_javascript {
1.1056    raeburn  12656:     my ($startcount,$numitems,$titles,$children) = @_;
                   12657:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12658:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12659:     my $scripttag = <<START;
                   12660: <script type="text/javascript">
                   12661: // <![CDATA[
                   12662: 
                   12663: function checkAll(form,prefix) {
                   12664:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12665:     for (var i=0; i < form.elements.length; i++) {
                   12666:         var id = form.elements[i].id;
                   12667:         if ((id != '') && (id != undefined)) {
                   12668:             if (idstr.test(id)) {
                   12669:                 if (form.elements[i].type == 'radio') {
                   12670:                     form.elements[i].checked = true;
1.1056    raeburn  12671:                     var nostart = i-$startcount;
1.1059    raeburn  12672:                     var offset = nostart%7;
                   12673:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12674:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12675:                 }
                   12676:             }
                   12677:         }
                   12678:     }
                   12679: }
                   12680: 
                   12681: function propagateCheck(form,count) {
                   12682:     if (count > 0) {
1.1059    raeburn  12683:         var startelement = $startcount + ((count-1) * 7);
                   12684:         for (var j=1; j<6; j++) {
                   12685:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12686:                 var item = startelement + j; 
                   12687:                 if (form.elements[item].type == 'radio') {
                   12688:                     if (form.elements[item].checked) {
                   12689:                         containerCheck(form,count,j);
                   12690:                         break;
                   12691:                     }
1.1055    raeburn  12692:                 }
                   12693:             }
                   12694:         }
                   12695:     }
                   12696: }
                   12697: 
                   12698: numitems = $numitems
1.1056    raeburn  12699: var titles = new Array(numitems);
                   12700: var parents = new Array(numitems);
1.1055    raeburn  12701: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12702:     parents[i] = new Array;
1.1055    raeburn  12703: }
1.1059    raeburn  12704: var maintitle = '$maintitle';
1.1055    raeburn  12705: 
                   12706: START
                   12707: 
1.1056    raeburn  12708:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12709:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12710:         for (my $i=0; $i<@contents; $i ++) {
                   12711:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12712:         }
                   12713:     }
                   12714: 
1.1056    raeburn  12715:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12716:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12717:     }
                   12718: 
1.1055    raeburn  12719:     $scripttag .= <<END;
                   12720: 
                   12721: function containerCheck(form,count,offset) {
                   12722:     if (count > 0) {
1.1056    raeburn  12723:         dependencyCheck(form,count,offset);
1.1059    raeburn  12724:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12725:         form.elements[item].checked = true;
                   12726:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12727:             if (parents[count].length > 0) {
                   12728:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12729:                     containerCheck(form,parents[count][j],offset);
                   12730:                 }
                   12731:             }
                   12732:         }
                   12733:     }
                   12734: }
                   12735: 
                   12736: function dependencyCheck(form,count,offset) {
                   12737:     if (count > 0) {
1.1059    raeburn  12738:         var chosen = (offset+$startcount)+7*(count-1);
                   12739:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12740:         var currtype = form.elements[depitem].type;
                   12741:         if (form.elements[chosen].value == 'dependency') {
                   12742:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12743:             form.elements[depitem].options.length = 0;
                   12744:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12745:             for (var i=1; i<=numitems; i++) {
                   12746:                 if (i == count) {
                   12747:                     continue;
                   12748:                 }
1.1059    raeburn  12749:                 var startelement = $startcount + (i-1) * 7;
                   12750:                 for (var j=1; j<6; j++) {
                   12751:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12752:                         var item = startelement + j;
                   12753:                         if (form.elements[item].type == 'radio') {
                   12754:                             if (form.elements[item].checked) {
                   12755:                                 if (form.elements[item].value == 'display') {
                   12756:                                     var n = form.elements[depitem].options.length;
                   12757:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12758:                                 }
                   12759:                             }
                   12760:                         }
                   12761:                     }
                   12762:                 }
                   12763:             }
                   12764:         } else {
                   12765:             document.getElementById('arc_depon_'+count).style.display='none';
                   12766:             form.elements[depitem].options.length = 0;
                   12767:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12768:         }
1.1059    raeburn  12769:         titleCheck(form,count,offset);
1.1056    raeburn  12770:     }
                   12771: }
                   12772: 
                   12773: function propagateSelect(form,count,offset) {
                   12774:     if (count > 0) {
1.1065    raeburn  12775:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12776:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12777:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12778:             if (parents[count].length > 0) {
                   12779:                 for (var j=0; j<parents[count].length; j++) {
                   12780:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12781:                 }
                   12782:             }
                   12783:         }
                   12784:     }
                   12785: }
1.1056    raeburn  12786: 
                   12787: function containerSelect(form,count,offset,picked) {
                   12788:     if (count > 0) {
1.1065    raeburn  12789:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12790:         if (form.elements[item].type == 'radio') {
                   12791:             if (form.elements[item].value == 'dependency') {
                   12792:                 if (form.elements[item+1].type == 'select-one') {
                   12793:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12794:                         if (form.elements[item+1].options[i].value == picked) {
                   12795:                             form.elements[item+1].selectedIndex = i;
                   12796:                             break;
                   12797:                         }
                   12798:                     }
                   12799:                 }
                   12800:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12801:                     if (parents[count].length > 0) {
                   12802:                         for (var j=0; j<parents[count].length; j++) {
                   12803:                             containerSelect(form,parents[count][j],offset,picked);
                   12804:                         }
                   12805:                     }
                   12806:                 }
                   12807:             }
                   12808:         }
                   12809:     }
                   12810: }
                   12811: 
1.1059    raeburn  12812: function titleCheck(form,count,offset) {
                   12813:     if (count > 0) {
                   12814:         var chosen = (offset+$startcount)+7*(count-1);
                   12815:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12816:         var currtype = form.elements[depitem].type;
                   12817:         if (form.elements[chosen].value == 'display') {
                   12818:             document.getElementById('arc_title_'+count).style.display='block';
                   12819:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12820:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12821:             }
                   12822:         } else {
                   12823:             document.getElementById('arc_title_'+count).style.display='none';
                   12824:             if (currtype == 'text') { 
                   12825:                 document.getElementById('archive_title_'+count).value='';
                   12826:             }
                   12827:         }
                   12828:     }
                   12829:     return;
                   12830: }
                   12831: 
1.1055    raeburn  12832: // ]]>
                   12833: </script>
                   12834: END
                   12835:     return $scripttag;
                   12836: }
                   12837: 
                   12838: sub process_extracted_files {
1.1067    raeburn  12839:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12840:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12841:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12842:     my @ids=&Apache::lonnet::current_machine_ids();
                   12843:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12844:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12845:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12846:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12847:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12848:         $pathtocheck = "$dir_root/$destination";
                   12849:         $dir = $dir_root;
                   12850:         $ishome = 1;
                   12851:     } else {
                   12852:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12853:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12854:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12855:     }
                   12856:     my $currdir = "$dir_root/$destination";
                   12857:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12858:     if ($env{'form.folderpath'}) {
                   12859:         my @items = split('&',$env{'form.folderpath'});
                   12860:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12861:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12862:             $containers{'0'}='page';
                   12863:         } else {
                   12864:             $containers{'0'}='sequence';
                   12865:         }
1.1055    raeburn  12866:     }
                   12867:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12868:     if ($numitems) {
                   12869:         for (my $i=1; $i<=$numitems; $i++) {
                   12870:             my $path = $env{'form.archive_content_'.$i};
                   12871:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12872:                 my $item = $1;
                   12873:                 $toplevelitems{$item} = $i;
                   12874:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12875:                     $is_dir{$item} = 1;
                   12876:                 }
                   12877:             }
                   12878:         }
                   12879:     }
1.1067    raeburn  12880:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12881:     if (keys(%toplevelitems) > 0) {
                   12882:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12883:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12884:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12885:     }
1.1066    raeburn  12886:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12887:     if ($numitems) {
                   12888:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12889:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12890:             my $path = $env{'form.archive_content_'.$i};
                   12891:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12892:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12893:                     if ($prefix ne '' && $path ne '') {
                   12894:                         if (-e $prefix.$path) {
1.1066    raeburn  12895:                             if ((@archdirs > 0) && 
                   12896:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12897:                                 $todeletedir{$prefix.$path} = 1;
                   12898:                             } else {
                   12899:                                 $todelete{$prefix.$path} = 1;
                   12900:                             }
1.1055    raeburn  12901:                         }
                   12902:                     }
                   12903:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12904:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12905:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12906:                     $docstitle = $env{'form.archive_title_'.$i};
                   12907:                     if ($docstitle eq '') {
                   12908:                         $docstitle = $title;
                   12909:                     }
1.1055    raeburn  12910:                     $outer = 0;
1.1056    raeburn  12911:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12912:                         if (@{$dirorder{$i}} > 0) {
                   12913:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12914:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12915:                                     $outer = $item;
                   12916:                                     last;
                   12917:                                 }
                   12918:                             }
                   12919:                         }
                   12920:                     }
                   12921:                     my ($errtext,$fatal) = 
                   12922:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12923:                                                '/'.$folders{$outer}.'.'.
                   12924:                                                $containers{$outer});
                   12925:                     next if ($fatal);
                   12926:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12927:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12928:                             $mapinner{$i} = time;
1.1055    raeburn  12929:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12930:                             $containers{$i} = 'sequence';
                   12931:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12932:                                       $folders{$i}.'.'.$containers{$i};
                   12933:                             my $newidx = &LONCAPA::map::getresidx();
                   12934:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12935:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12936:                             push(@LONCAPA::map::order,$newidx);
                   12937:                             my ($outtext,$errtext) =
                   12938:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12939:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12940:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12941:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12942:                             unless ($errtext) {
1.1075.2.128  raeburn  12943:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12944:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12945:                                             '</li>'."\n";
1.1067    raeburn  12946:                             }
1.1055    raeburn  12947:                         }
                   12948:                     } else {
                   12949:                         if ($context eq 'coursedocs') {
                   12950:                             my $newidx=&LONCAPA::map::getresidx();
                   12951:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12952:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12953:                                       $title;
1.1075.2.128  raeburn  12954:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12955:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12956:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12957:                                 }
1.1075.2.128  raeburn  12958:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12959:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12960:                                 }
                   12961:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12962:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12963:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12964:                                         unless ($ishome) {
                   12965:                                             my $fetch = "$newdest{$i}/$title";
                   12966:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12967:                                             $prompttofetch{$fetch} = 1;
                   12968:                                         }
                   12969:                                    }
                   12970:                                 }
                   12971:                                 $LONCAPA::map::resources[$newidx]=
                   12972:                                     $docstitle.':'.$url.':false:normal:res';
                   12973:                                 push(@LONCAPA::map::order, $newidx);
                   12974:                                 my ($outtext,$errtext)=
                   12975:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12976:                                                             $docuname.'/'.$folders{$outer}.
                   12977:                                                             '.'.$containers{$outer},1,1);
                   12978:                                 unless ($errtext) {
                   12979:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12980:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12981:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12982:                                                    '</li>'."\n";
                   12983:                                     }
1.1067    raeburn  12984:                                 }
1.1075.2.128  raeburn  12985:                             } else {
                   12986:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12987:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  12988:                             }
1.1055    raeburn  12989:                         }
                   12990:                     }
1.1075.2.11  raeburn  12991:                 }
                   12992:             } else {
1.1075.2.128  raeburn  12993:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12994:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  12995:             }
                   12996:         }
                   12997:         for (my $i=1; $i<=$numitems; $i++) {
                   12998:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12999:             my $path = $env{'form.archive_content_'.$i};
                   13000:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13001:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13002:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13003:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13004:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13005:                         my ($itemidx,$fullpath,$relpath);
                   13006:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13007:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13008:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13009:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13010:                                     $itemidx = $j;
1.1056    raeburn  13011:                                 }
                   13012:                             }
1.1075.2.11  raeburn  13013:                         }
                   13014:                         if ($itemidx eq '') {
                   13015:                             $itemidx =  0;
                   13016:                         }
                   13017:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13018:                             if ($mapinner{$referrer{$i}}) {
                   13019:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13020:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13021:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13022:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13023:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13024:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13025:                                             if (!-e $fullpath) {
                   13026:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13027:                                             }
                   13028:                                         }
1.1075.2.11  raeburn  13029:                                     } else {
                   13030:                                         last;
1.1056    raeburn  13031:                                     }
1.1075.2.11  raeburn  13032:                                 }
                   13033:                             }
                   13034:                         } elsif ($newdest{$referrer{$i}}) {
                   13035:                             $fullpath = $newdest{$referrer{$i}};
                   13036:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13037:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13038:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13039:                                     last;
                   13040:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13041:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13042:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13043:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13044:                                         if (!-e $fullpath) {
                   13045:                                             mkdir($fullpath,0755);
1.1056    raeburn  13046:                                         }
                   13047:                                     }
1.1075.2.11  raeburn  13048:                                 } else {
                   13049:                                     last;
1.1056    raeburn  13050:                                 }
1.1075.2.11  raeburn  13051:                             }
                   13052:                         }
                   13053:                         if ($fullpath ne '') {
                   13054:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13055:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13056:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13057:                                 }
1.1075.2.11  raeburn  13058:                             }
                   13059:                             if (-e "$fullpath/$title") {
                   13060:                                 my $showpath;
                   13061:                                 if ($relpath ne '') {
                   13062:                                     $showpath = "$relpath/$title";
                   13063:                                 } else {
                   13064:                                     $showpath = "/$title";
1.1056    raeburn  13065:                                 }
1.1075.2.128  raeburn  13066:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13067:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13068:                                            '</li>'."\n";
                   13069:                                 unless ($ishome) {
                   13070:                                     my $fetch = "$fullpath/$title";
                   13071:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13072:                                     $prompttofetch{$fetch} = 1;
                   13073:                                 }
1.1055    raeburn  13074:                             }
                   13075:                         }
                   13076:                     }
1.1075.2.11  raeburn  13077:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13078:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13079:                                     &HTML::Entities::encode($path,'<>&"'),
                   13080:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13081:                                 '<br />';
1.1055    raeburn  13082:                 }
                   13083:             } else {
1.1075.2.128  raeburn  13084:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13085:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13086:             }
                   13087:         }
                   13088:         if (keys(%todelete)) {
                   13089:             foreach my $key (keys(%todelete)) {
                   13090:                 unlink($key);
1.1066    raeburn  13091:             }
                   13092:         }
                   13093:         if (keys(%todeletedir)) {
                   13094:             foreach my $key (keys(%todeletedir)) {
                   13095:                 rmdir($key);
                   13096:             }
                   13097:         }
                   13098:         foreach my $dir (sort(keys(%is_dir))) {
                   13099:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13100:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13101:             }
                   13102:         }
1.1067    raeburn  13103:         if ($result ne '') {
                   13104:             $output .= '<ul>'."\n".
                   13105:                        $result."\n".
                   13106:                        '</ul>';
                   13107:         }
                   13108:         unless ($ishome) {
                   13109:             my $replicationfail;
                   13110:             foreach my $item (keys(%prompttofetch)) {
                   13111:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13112:                 unless ($fetchresult eq 'ok') {
                   13113:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13114:                 }
                   13115:             }
                   13116:             if ($replicationfail) {
                   13117:                 $output .= '<p class="LC_error">'.
                   13118:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13119:                            $replicationfail.
                   13120:                            '</ul></p>';
                   13121:             }
                   13122:         }
1.1055    raeburn  13123:     } else {
                   13124:         $warning = &mt('No items found in archive.');
                   13125:     }
                   13126:     if ($error) {
                   13127:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13128:                    $error.'</p>'."\n";
                   13129:     }
                   13130:     if ($warning) {
                   13131:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13132:     }
                   13133:     return $output;
                   13134: }
                   13135: 
1.1066    raeburn  13136: sub cleanup_empty_dirs {
                   13137:     my ($path) = @_;
                   13138:     if (($path ne '') && (-d $path)) {
                   13139:         if (opendir(my $dirh,$path)) {
                   13140:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13141:             my $numitems = 0;
                   13142:             foreach my $item (@dircontents) {
                   13143:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13144:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13145:                     if (-e "$path/$item") {
                   13146:                         $numitems ++;
                   13147:                     }
                   13148:                 } else {
                   13149:                     $numitems ++;
                   13150:                 }
                   13151:             }
                   13152:             if ($numitems == 0) {
                   13153:                 rmdir($path);
                   13154:             }
                   13155:             closedir($dirh);
                   13156:         }
                   13157:     }
                   13158:     return;
                   13159: }
                   13160: 
1.41      ng       13161: =pod
1.45      matthew  13162: 
1.1075.2.56  raeburn  13163: =item * &get_folder_hierarchy()
1.1068    raeburn  13164: 
                   13165: Provides hierarchy of names of folders/sub-folders containing the current
                   13166: item,
                   13167: 
                   13168: Inputs: 3
                   13169:      - $navmap - navmaps object
                   13170: 
                   13171:      - $map - url for map (either the trigger itself, or map containing
                   13172:                            the resource, which is the trigger).
                   13173: 
                   13174:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13175: 
                   13176: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13177: 
                   13178: =cut
                   13179: 
                   13180: sub get_folder_hierarchy {
                   13181:     my ($navmap,$map,$showitem) = @_;
                   13182:     my @pathitems;
                   13183:     if (ref($navmap)) {
                   13184:         my $mapres = $navmap->getResourceByUrl($map);
                   13185:         if (ref($mapres)) {
                   13186:             my $pcslist = $mapres->map_hierarchy();
                   13187:             if ($pcslist ne '') {
                   13188:                 my @pcs = split(/,/,$pcslist);
                   13189:                 foreach my $pc (@pcs) {
                   13190:                     if ($pc == 1) {
1.1075.2.38  raeburn  13191:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13192:                     } else {
                   13193:                         my $res = $navmap->getByMapPc($pc);
                   13194:                         if (ref($res)) {
                   13195:                             my $title = $res->compTitle();
                   13196:                             $title =~ s/\W+/_/g;
                   13197:                             if ($title ne '') {
                   13198:                                 push(@pathitems,$title);
                   13199:                             }
                   13200:                         }
                   13201:                     }
                   13202:                 }
                   13203:             }
1.1071    raeburn  13204:             if ($showitem) {
                   13205:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13206:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13207:                 } else {
                   13208:                     my $maptitle = $mapres->compTitle();
                   13209:                     $maptitle =~ s/\W+/_/g;
                   13210:                     if ($maptitle ne '') {
                   13211:                         push(@pathitems,$maptitle);
                   13212:                     }
1.1068    raeburn  13213:                 }
                   13214:             }
                   13215:         }
                   13216:     }
                   13217:     return @pathitems;
                   13218: }
                   13219: 
                   13220: =pod
                   13221: 
1.1015    raeburn  13222: =item * &get_turnedin_filepath()
                   13223: 
                   13224: Determines path in a user's portfolio file for storage of files uploaded
                   13225: to a specific essayresponse or dropbox item.
                   13226: 
                   13227: Inputs: 3 required + 1 optional.
                   13228: $symb is symb for resource, $uname and $udom are for current user (required).
                   13229: $caller is optional (can be "submission", if routine is called when storing
                   13230: an upoaded file when "Submit Answer" button was pressed).
                   13231: 
                   13232: Returns array containing $path and $multiresp. 
                   13233: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13234: than one file upload item.  Callers of routine should append partid as a 
                   13235: subdirectory to $path in cases where $multiresp is 1.
                   13236: 
                   13237: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13238: 
                   13239: =cut
                   13240: 
                   13241: sub get_turnedin_filepath {
                   13242:     my ($symb,$uname,$udom,$caller) = @_;
                   13243:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13244:     my $turnindir;
                   13245:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13246:     $turnindir = $userhash{'turnindir'};
                   13247:     my ($path,$multiresp);
                   13248:     if ($turnindir eq '') {
                   13249:         if ($caller eq 'submission') {
                   13250:             $turnindir = &mt('turned in');
                   13251:             $turnindir =~ s/\W+/_/g;
                   13252:             my %newhash = (
                   13253:                             'turnindir' => $turnindir,
                   13254:                           );
                   13255:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13256:         }
                   13257:     }
                   13258:     if ($turnindir ne '') {
                   13259:         $path = '/'.$turnindir.'/';
                   13260:         my ($multipart,$turnin,@pathitems);
                   13261:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13262:         if (defined($navmap)) {
                   13263:             my $mapres = $navmap->getResourceByUrl($map);
                   13264:             if (ref($mapres)) {
                   13265:                 my $pcslist = $mapres->map_hierarchy();
                   13266:                 if ($pcslist ne '') {
                   13267:                     foreach my $pc (split(/,/,$pcslist)) {
                   13268:                         my $res = $navmap->getByMapPc($pc);
                   13269:                         if (ref($res)) {
                   13270:                             my $title = $res->compTitle();
                   13271:                             $title =~ s/\W+/_/g;
                   13272:                             if ($title ne '') {
1.1075.2.48  raeburn  13273:                                 if (($pc > 1) && (length($title) > 12)) {
                   13274:                                     $title = substr($title,0,12);
                   13275:                                 }
1.1015    raeburn  13276:                                 push(@pathitems,$title);
                   13277:                             }
                   13278:                         }
                   13279:                     }
                   13280:                 }
                   13281:                 my $maptitle = $mapres->compTitle();
                   13282:                 $maptitle =~ s/\W+/_/g;
                   13283:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13284:                     if (length($maptitle) > 12) {
                   13285:                         $maptitle = substr($maptitle,0,12);
                   13286:                     }
1.1015    raeburn  13287:                     push(@pathitems,$maptitle);
                   13288:                 }
                   13289:                 unless ($env{'request.state'} eq 'construct') {
                   13290:                     my $res = $navmap->getBySymb($symb);
                   13291:                     if (ref($res)) {
                   13292:                         my $partlist = $res->parts();
                   13293:                         my $totaluploads = 0;
                   13294:                         if (ref($partlist) eq 'ARRAY') {
                   13295:                             foreach my $part (@{$partlist}) {
                   13296:                                 my @types = $res->responseType($part);
                   13297:                                 my @ids = $res->responseIds($part);
                   13298:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13299:                                     if ($types[$i] eq 'essay') {
                   13300:                                         my $partid = $part.'_'.$ids[$i];
                   13301:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13302:                                             $totaluploads ++;
                   13303:                                         }
                   13304:                                     }
                   13305:                                 }
                   13306:                             }
                   13307:                             if ($totaluploads > 1) {
                   13308:                                 $multiresp = 1;
                   13309:                             }
                   13310:                         }
                   13311:                     }
                   13312:                 }
                   13313:             } else {
                   13314:                 return;
                   13315:             }
                   13316:         } else {
                   13317:             return;
                   13318:         }
                   13319:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13320:         $restitle =~ s/\W+/_/g;
                   13321:         if ($restitle eq '') {
                   13322:             $restitle = ($resurl =~ m{/[^/]+$});
                   13323:             if ($restitle eq '') {
                   13324:                 $restitle = time;
                   13325:             }
                   13326:         }
1.1075.2.48  raeburn  13327:         if (length($restitle) > 12) {
                   13328:             $restitle = substr($restitle,0,12);
                   13329:         }
1.1015    raeburn  13330:         push(@pathitems,$restitle);
                   13331:         $path .= join('/',@pathitems);
                   13332:     }
                   13333:     return ($path,$multiresp);
                   13334: }
                   13335: 
                   13336: =pod
                   13337: 
1.464     albertel 13338: =back
1.41      ng       13339: 
1.112     bowersj2 13340: =head1 CSV Upload/Handling functions
1.38      albertel 13341: 
1.41      ng       13342: =over 4
                   13343: 
1.648     raeburn  13344: =item * &upfile_store($r)
1.41      ng       13345: 
                   13346: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13347: needs $env{'form.upfile'}
1.41      ng       13348: returns $datatoken to be put into hidden field
                   13349: 
                   13350: =cut
1.31      albertel 13351: 
                   13352: sub upfile_store {
                   13353:     my $r=shift;
1.258     albertel 13354:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13355:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13356:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13357:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13358: 
1.1075.2.128  raeburn  13359:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13360:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13361:                                      time.'_'.$$);
                   13362:     return if ($datatoken eq '');
                   13363: 
1.31      albertel 13364:     {
1.158     raeburn  13365:         my $datafile = $r->dir_config('lonDaemons').
                   13366:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13367:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13368:             print $fh $env{'form.upfile'};
1.158     raeburn  13369:             close($fh);
                   13370:         }
1.31      albertel 13371:     }
                   13372:     return $datatoken;
                   13373: }
                   13374: 
1.56      matthew  13375: =pod
                   13376: 
1.1075.2.128  raeburn  13377: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13378: 
                   13379: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13380: $datatoken is the name to assign to the temporary file.
1.258     albertel 13381: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13382: 
                   13383: =cut
1.31      albertel 13384: 
                   13385: sub load_tmp_file {
1.1075.2.128  raeburn  13386:     my ($r,$datatoken) = @_;
                   13387:     return if ($datatoken eq '');
1.31      albertel 13388:     my @studentdata=();
                   13389:     {
1.158     raeburn  13390:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13391:                               '/tmp/'.$datatoken.'.tmp';
                   13392:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13393:             @studentdata=<$fh>;
                   13394:             close($fh);
                   13395:         }
1.31      albertel 13396:     }
1.258     albertel 13397:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13398: }
                   13399: 
1.1075.2.128  raeburn  13400: sub valid_datatoken {
                   13401:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13402:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13403:         return $datatoken;
                   13404:     }
                   13405:     return;
                   13406: }
                   13407: 
1.56      matthew  13408: =pod
                   13409: 
1.648     raeburn  13410: =item * &upfile_record_sep()
1.41      ng       13411: 
                   13412: Separate uploaded file into records
                   13413: returns array of records,
1.258     albertel 13414: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13415: 
                   13416: =cut
1.31      albertel 13417: 
                   13418: sub upfile_record_sep {
1.258     albertel 13419:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13420:     } else {
1.248     albertel 13421: 	my @records;
1.258     albertel 13422: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13423: 	    if ($line=~/^\s*$/) { next; }
                   13424: 	    push(@records,$line);
                   13425: 	}
                   13426: 	return @records;
1.31      albertel 13427:     }
                   13428: }
                   13429: 
1.56      matthew  13430: =pod
                   13431: 
1.648     raeburn  13432: =item * &record_sep($record)
1.41      ng       13433: 
1.258     albertel 13434: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13435: 
                   13436: =cut
                   13437: 
1.263     www      13438: sub takeleft {
                   13439:     my $index=shift;
                   13440:     return substr('0000'.$index,-4,4);
                   13441: }
                   13442: 
1.31      albertel 13443: sub record_sep {
                   13444:     my $record=shift;
                   13445:     my %components=();
1.258     albertel 13446:     if ($env{'form.upfiletype'} eq 'xml') {
                   13447:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13448:         my $i=0;
1.356     albertel 13449:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13450:             $field=~s/^(\"|\')//;
                   13451:             $field=~s/(\"|\')$//;
1.263     www      13452:             $components{&takeleft($i)}=$field;
1.31      albertel 13453:             $i++;
                   13454:         }
1.258     albertel 13455:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13456:         my $i=0;
1.356     albertel 13457:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13458:             $field=~s/^(\"|\')//;
                   13459:             $field=~s/(\"|\')$//;
1.263     www      13460:             $components{&takeleft($i)}=$field;
1.31      albertel 13461:             $i++;
                   13462:         }
                   13463:     } else {
1.561     www      13464:         my $separator=',';
1.480     banghart 13465:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13466:             $separator=';';
1.480     banghart 13467:         }
1.31      albertel 13468:         my $i=0;
1.561     www      13469: # the character we are looking for to indicate the end of a quote or a record 
                   13470:         my $looking_for=$separator;
                   13471: # do not add the characters to the fields
                   13472:         my $ignore=0;
                   13473: # we just encountered a separator (or the beginning of the record)
                   13474:         my $just_found_separator=1;
                   13475: # store the field we are working on here
                   13476:         my $field='';
                   13477: # work our way through all characters in record
                   13478:         foreach my $character ($record=~/(.)/g) {
                   13479:             if ($character eq $looking_for) {
                   13480:                if ($character ne $separator) {
                   13481: # Found the end of a quote, again looking for separator
                   13482:                   $looking_for=$separator;
                   13483:                   $ignore=1;
                   13484:                } else {
                   13485: # Found a separator, store away what we got
                   13486:                   $components{&takeleft($i)}=$field;
                   13487: 	          $i++;
                   13488:                   $just_found_separator=1;
                   13489:                   $ignore=0;
                   13490:                   $field='';
                   13491:                }
                   13492:                next;
                   13493:             }
                   13494: # single or double quotation marks after a separator indicate beginning of a quote
                   13495: # we are now looking for the end of the quote and need to ignore separators
                   13496:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13497:                $looking_for=$character;
                   13498:                next;
                   13499:             }
                   13500: # ignore would be true after we reached the end of a quote
                   13501:             if ($ignore) { next; }
                   13502:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13503:             $field.=$character;
                   13504:             $just_found_separator=0; 
1.31      albertel 13505:         }
1.561     www      13506: # catch the very last entry, since we never encountered the separator
                   13507:         $components{&takeleft($i)}=$field;
1.31      albertel 13508:     }
                   13509:     return %components;
                   13510: }
                   13511: 
1.144     matthew  13512: ######################################################
                   13513: ######################################################
                   13514: 
1.56      matthew  13515: =pod
                   13516: 
1.648     raeburn  13517: =item * &upfile_select_html()
1.41      ng       13518: 
1.144     matthew  13519: Return HTML code to select a file from the users machine and specify 
                   13520: the file type.
1.41      ng       13521: 
                   13522: =cut
                   13523: 
1.144     matthew  13524: ######################################################
                   13525: ######################################################
1.31      albertel 13526: sub upfile_select_html {
1.144     matthew  13527:     my %Types = (
                   13528:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13529:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13530:                  space => &mt('Space separated'),
                   13531:                  tab   => &mt('Tabulator separated'),
                   13532: #                 xml   => &mt('HTML/XML'),
                   13533:                  );
                   13534:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13535:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13536:     foreach my $type (sort(keys(%Types))) {
                   13537:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13538:     }
                   13539:     $Str .= "</select>\n";
                   13540:     return $Str;
1.31      albertel 13541: }
                   13542: 
1.301     albertel 13543: sub get_samples {
                   13544:     my ($records,$toget) = @_;
                   13545:     my @samples=({});
                   13546:     my $got=0;
                   13547:     foreach my $rec (@$records) {
                   13548: 	my %temp = &record_sep($rec);
                   13549: 	if (! grep(/\S/, values(%temp))) { next; }
                   13550: 	if (%temp) {
                   13551: 	    $samples[$got]=\%temp;
                   13552: 	    $got++;
                   13553: 	    if ($got == $toget) { last; }
                   13554: 	}
                   13555:     }
                   13556:     return \@samples;
                   13557: }
                   13558: 
1.144     matthew  13559: ######################################################
                   13560: ######################################################
                   13561: 
1.56      matthew  13562: =pod
                   13563: 
1.648     raeburn  13564: =item * &csv_print_samples($r,$records)
1.41      ng       13565: 
                   13566: Prints a table of sample values from each column uploaded $r is an
                   13567: Apache Request ref, $records is an arrayref from
                   13568: &Apache::loncommon::upfile_record_sep
                   13569: 
                   13570: =cut
                   13571: 
1.144     matthew  13572: ######################################################
                   13573: ######################################################
1.31      albertel 13574: sub csv_print_samples {
                   13575:     my ($r,$records) = @_;
1.662     bisitz   13576:     my $samples = &get_samples($records,5);
1.301     albertel 13577: 
1.594     raeburn  13578:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13579:               &start_data_table_header_row());
1.356     albertel 13580:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13581:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13582:     $r->print(&end_data_table_header_row());
1.301     albertel 13583:     foreach my $hash (@$samples) {
1.594     raeburn  13584: 	$r->print(&start_data_table_row());
1.356     albertel 13585: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13586: 	    $r->print('<td>');
1.356     albertel 13587: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13588: 	    $r->print('</td>');
                   13589: 	}
1.594     raeburn  13590: 	$r->print(&end_data_table_row());
1.31      albertel 13591:     }
1.594     raeburn  13592:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13593: }
                   13594: 
1.144     matthew  13595: ######################################################
                   13596: ######################################################
                   13597: 
1.56      matthew  13598: =pod
                   13599: 
1.648     raeburn  13600: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13601: 
                   13602: Prints a table to create associations between values and table columns.
1.144     matthew  13603: 
1.41      ng       13604: $r is an Apache Request ref,
                   13605: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13606: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13607: 
                   13608: =cut
                   13609: 
1.144     matthew  13610: ######################################################
                   13611: ######################################################
1.31      albertel 13612: sub csv_print_select_table {
                   13613:     my ($r,$records,$d) = @_;
1.301     albertel 13614:     my $i=0;
                   13615:     my $samples = &get_samples($records,1);
1.144     matthew  13616:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13617: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13618:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13619:               '<th>'.&mt('Column').'</th>'.
                   13620:               &end_data_table_header_row()."\n");
1.356     albertel 13621:     foreach my $array_ref (@$d) {
                   13622: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13623: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13624: 
1.875     bisitz   13625: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13626: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13627: 	$r->print('<option value="none"></option>');
1.356     albertel 13628: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13629: 	    $r->print('<option value="'.$sample.'"'.
                   13630:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13631:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13632: 	}
1.594     raeburn  13633: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13634: 	$i++;
                   13635:     }
1.594     raeburn  13636:     $r->print(&end_data_table());
1.31      albertel 13637:     $i--;
                   13638:     return $i;
                   13639: }
1.56      matthew  13640: 
1.144     matthew  13641: ######################################################
                   13642: ######################################################
                   13643: 
1.56      matthew  13644: =pod
1.31      albertel 13645: 
1.648     raeburn  13646: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13647: 
                   13648: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13649: 
                   13650: $r is an Apache Request ref,
                   13651: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13652: $d is an array of 2 element arrays (internal name, displayed name)
                   13653: 
                   13654: =cut
                   13655: 
1.144     matthew  13656: ######################################################
                   13657: ######################################################
1.31      albertel 13658: sub csv_samples_select_table {
                   13659:     my ($r,$records,$d) = @_;
                   13660:     my $i=0;
1.144     matthew  13661:     #
1.662     bisitz   13662:     my $max_samples = 5;
                   13663:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13664:     $r->print(&start_data_table().
                   13665:               &start_data_table_header_row().'<th>'.
                   13666:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13667:               &end_data_table_header_row());
1.301     albertel 13668: 
                   13669:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13670: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13671: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13672: 	foreach my $option (@$d) {
                   13673: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13674: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13675:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13676:                       $display.'</option>');
1.31      albertel 13677: 	}
                   13678: 	$r->print('</select></td><td>');
1.662     bisitz   13679: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13680: 	    if (defined($samples->[$line]{$key})) { 
                   13681: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13682: 	    }
                   13683: 	}
1.594     raeburn  13684: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13685: 	$i++;
                   13686:     }
1.594     raeburn  13687:     $r->print(&end_data_table());
1.31      albertel 13688:     $i--;
                   13689:     return($i);
1.115     matthew  13690: }
                   13691: 
1.144     matthew  13692: ######################################################
                   13693: ######################################################
                   13694: 
1.115     matthew  13695: =pod
                   13696: 
1.648     raeburn  13697: =item * &clean_excel_name($name)
1.115     matthew  13698: 
                   13699: Returns a replacement for $name which does not contain any illegal characters.
                   13700: 
                   13701: =cut
                   13702: 
1.144     matthew  13703: ######################################################
                   13704: ######################################################
1.115     matthew  13705: sub clean_excel_name {
                   13706:     my ($name) = @_;
                   13707:     $name =~ s/[:\*\?\/\\]//g;
                   13708:     if (length($name) > 31) {
                   13709:         $name = substr($name,0,31);
                   13710:     }
                   13711:     return $name;
1.25      albertel 13712: }
1.84      albertel 13713: 
1.85      albertel 13714: =pod
                   13715: 
1.648     raeburn  13716: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13717: 
                   13718: Returns either 1 or undef
                   13719: 
                   13720: 1 if the part is to be hidden, undef if it is to be shown
                   13721: 
                   13722: Arguments are:
                   13723: 
                   13724: $id the id of the part to be checked
                   13725: $symb, optional the symb of the resource to check
                   13726: $udom, optional the domain of the user to check for
                   13727: $uname, optional the username of the user to check for
                   13728: 
                   13729: =cut
1.84      albertel 13730: 
                   13731: sub check_if_partid_hidden {
                   13732:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13733:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13734: 					 $symb,$udom,$uname);
1.141     albertel 13735:     my $truth=1;
                   13736:     #if the string starts with !, then the list is the list to show not hide
                   13737:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13738:     my @hiddenlist=split(/,/,$hiddenparts);
                   13739:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13740: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13741:     }
1.141     albertel 13742:     return !$truth;
1.84      albertel 13743: }
1.127     matthew  13744: 
1.138     matthew  13745: 
                   13746: ############################################################
                   13747: ############################################################
                   13748: 
                   13749: =pod
                   13750: 
1.157     matthew  13751: =back 
                   13752: 
1.138     matthew  13753: =head1 cgi-bin script and graphing routines
                   13754: 
1.157     matthew  13755: =over 4
                   13756: 
1.648     raeburn  13757: =item * &get_cgi_id()
1.138     matthew  13758: 
                   13759: Inputs: none
                   13760: 
                   13761: Returns an id which can be used to pass environment variables
                   13762: to various cgi-bin scripts.  These environment variables will
                   13763: be removed from the users environment after a given time by
                   13764: the routine &Apache::lonnet::transfer_profile_to_env.
                   13765: 
                   13766: =cut
                   13767: 
                   13768: ############################################################
                   13769: ############################################################
1.152     albertel 13770: my $uniq=0;
1.136     matthew  13771: sub get_cgi_id {
1.154     albertel 13772:     $uniq=($uniq+1)%100000;
1.280     albertel 13773:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13774: }
                   13775: 
1.127     matthew  13776: ############################################################
                   13777: ############################################################
                   13778: 
                   13779: =pod
                   13780: 
1.648     raeburn  13781: =item * &DrawBarGraph()
1.127     matthew  13782: 
1.138     matthew  13783: Facilitates the plotting of data in a (stacked) bar graph.
                   13784: Puts plot definition data into the users environment in order for 
                   13785: graph.png to plot it.  Returns an <img> tag for the plot.
                   13786: The bars on the plot are labeled '1','2',...,'n'.
                   13787: 
                   13788: Inputs:
                   13789: 
                   13790: =over 4
                   13791: 
                   13792: =item $Title: string, the title of the plot
                   13793: 
                   13794: =item $xlabel: string, text describing the X-axis of the plot
                   13795: 
                   13796: =item $ylabel: string, text describing the Y-axis of the plot
                   13797: 
                   13798: =item $Max: scalar, the maximum Y value to use in the plot
                   13799: If $Max is < any data point, the graph will not be rendered.
                   13800: 
1.140     matthew  13801: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13802: they are plotted.  If undefined, default values will be used.
                   13803: 
1.178     matthew  13804: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13805: 
1.138     matthew  13806: =item @Values: An array of array references.  Each array reference holds data
                   13807: to be plotted in a stacked bar chart.
                   13808: 
1.239     matthew  13809: =item If the final element of @Values is a hash reference the key/value
                   13810: pairs will be added to the graph definition.
                   13811: 
1.138     matthew  13812: =back
                   13813: 
                   13814: Returns:
                   13815: 
                   13816: An <img> tag which references graph.png and the appropriate identifying
                   13817: information for the plot.
                   13818: 
1.127     matthew  13819: =cut
                   13820: 
                   13821: ############################################################
                   13822: ############################################################
1.134     matthew  13823: sub DrawBarGraph {
1.178     matthew  13824:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13825:     #
                   13826:     if (! defined($colors)) {
                   13827:         $colors = ['#33ff00', 
                   13828:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13829:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13830:                   ]; 
                   13831:     }
1.228     matthew  13832:     my $extra_settings = {};
                   13833:     if (ref($Values[-1]) eq 'HASH') {
                   13834:         $extra_settings = pop(@Values);
                   13835:     }
1.127     matthew  13836:     #
1.136     matthew  13837:     my $identifier = &get_cgi_id();
                   13838:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13839:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13840:         return '';
                   13841:     }
1.225     matthew  13842:     #
                   13843:     my @Labels;
                   13844:     if (defined($labels)) {
                   13845:         @Labels = @$labels;
                   13846:     } else {
                   13847:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13848:             push(@Labels,$i+1);
1.225     matthew  13849:         }
                   13850:     }
                   13851:     #
1.129     matthew  13852:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13853:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13854:     my %ValuesHash;
                   13855:     my $NumSets=1;
                   13856:     foreach my $array (@Values) {
                   13857:         next if (! ref($array));
1.136     matthew  13858:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13859:             join(',',@$array);
1.129     matthew  13860:     }
1.127     matthew  13861:     #
1.136     matthew  13862:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13863:     if ($NumBars < 3) {
                   13864:         $width = 120+$NumBars*32;
1.220     matthew  13865:         $xskip = 1;
1.225     matthew  13866:         $bar_width = 30;
                   13867:     } elsif ($NumBars < 5) {
                   13868:         $width = 120+$NumBars*20;
                   13869:         $xskip = 1;
                   13870:         $bar_width = 20;
1.220     matthew  13871:     } elsif ($NumBars < 10) {
1.136     matthew  13872:         $width = 120+$NumBars*15;
                   13873:         $xskip = 1;
                   13874:         $bar_width = 15;
                   13875:     } elsif ($NumBars <= 25) {
                   13876:         $width = 120+$NumBars*11;
                   13877:         $xskip = 5;
                   13878:         $bar_width = 8;
                   13879:     } elsif ($NumBars <= 50) {
                   13880:         $width = 120+$NumBars*8;
                   13881:         $xskip = 5;
                   13882:         $bar_width = 4;
                   13883:     } else {
                   13884:         $width = 120+$NumBars*8;
                   13885:         $xskip = 5;
                   13886:         $bar_width = 4;
                   13887:     }
                   13888:     #
1.137     matthew  13889:     $Max = 1 if ($Max < 1);
                   13890:     if ( int($Max) < $Max ) {
                   13891:         $Max++;
                   13892:         $Max = int($Max);
                   13893:     }
1.127     matthew  13894:     $Title  = '' if (! defined($Title));
                   13895:     $xlabel = '' if (! defined($xlabel));
                   13896:     $ylabel = '' if (! defined($ylabel));
1.369     www      13897:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13898:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13899:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13900:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13901:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13902:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13903:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13904:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13905:     $ValuesHash{$id.'.height'}   = $height;
                   13906:     $ValuesHash{$id.'.width'}    = $width;
                   13907:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13908:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13909:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13910:     #
1.228     matthew  13911:     # Deal with other parameters
                   13912:     while (my ($key,$value) = each(%$extra_settings)) {
                   13913:         $ValuesHash{$id.'.'.$key} = $value;
                   13914:     }
                   13915:     #
1.646     raeburn  13916:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13917:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13918: }
                   13919: 
                   13920: ############################################################
                   13921: ############################################################
                   13922: 
                   13923: =pod
                   13924: 
1.648     raeburn  13925: =item * &DrawXYGraph()
1.137     matthew  13926: 
1.138     matthew  13927: Facilitates the plotting of data in an XY graph.
                   13928: Puts plot definition data into the users environment in order for 
                   13929: graph.png to plot it.  Returns an <img> tag for the plot.
                   13930: 
                   13931: Inputs:
                   13932: 
                   13933: =over 4
                   13934: 
                   13935: =item $Title: string, the title of the plot
                   13936: 
                   13937: =item $xlabel: string, text describing the X-axis of the plot
                   13938: 
                   13939: =item $ylabel: string, text describing the Y-axis of the plot
                   13940: 
                   13941: =item $Max: scalar, the maximum Y value to use in the plot
                   13942: If $Max is < any data point, the graph will not be rendered.
                   13943: 
                   13944: =item $colors: Array ref containing the hex color codes for the data to be 
                   13945: plotted in.  If undefined, default values will be used.
                   13946: 
                   13947: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13948: 
                   13949: =item $Ydata: Array ref containing Array refs.  
1.185     www      13950: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13951: 
                   13952: =item %Values: hash indicating or overriding any default values which are 
                   13953: passed to graph.png.  
                   13954: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13955: 
                   13956: =back
                   13957: 
                   13958: Returns:
                   13959: 
                   13960: An <img> tag which references graph.png and the appropriate identifying
                   13961: information for the plot.
                   13962: 
1.137     matthew  13963: =cut
                   13964: 
                   13965: ############################################################
                   13966: ############################################################
                   13967: sub DrawXYGraph {
                   13968:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13969:     #
                   13970:     # Create the identifier for the graph
                   13971:     my $identifier = &get_cgi_id();
                   13972:     my $id = 'cgi.'.$identifier;
                   13973:     #
                   13974:     $Title  = '' if (! defined($Title));
                   13975:     $xlabel = '' if (! defined($xlabel));
                   13976:     $ylabel = '' if (! defined($ylabel));
                   13977:     my %ValuesHash = 
                   13978:         (
1.369     www      13979:          $id.'.title'  => &escape($Title),
                   13980:          $id.'.xlabel' => &escape($xlabel),
                   13981:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13982:          $id.'.y_max_value'=> $Max,
                   13983:          $id.'.labels'     => join(',',@$Xlabels),
                   13984:          $id.'.PlotType'   => 'XY',
                   13985:          );
                   13986:     #
                   13987:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13988:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13989:     }
                   13990:     #
                   13991:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13992:         return '';
                   13993:     }
                   13994:     my $NumSets=1;
1.138     matthew  13995:     foreach my $array (@{$Ydata}){
1.137     matthew  13996:         next if (! ref($array));
                   13997:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13998:     }
1.138     matthew  13999:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14000:     #
                   14001:     # Deal with other parameters
                   14002:     while (my ($key,$value) = each(%Values)) {
                   14003:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14004:     }
                   14005:     #
1.646     raeburn  14006:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14007:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14008: }
                   14009: 
                   14010: ############################################################
                   14011: ############################################################
                   14012: 
                   14013: =pod
                   14014: 
1.648     raeburn  14015: =item * &DrawXYYGraph()
1.138     matthew  14016: 
                   14017: Facilitates the plotting of data in an XY graph with two Y axes.
                   14018: Puts plot definition data into the users environment in order for 
                   14019: graph.png to plot it.  Returns an <img> tag for the plot.
                   14020: 
                   14021: Inputs:
                   14022: 
                   14023: =over 4
                   14024: 
                   14025: =item $Title: string, the title of the plot
                   14026: 
                   14027: =item $xlabel: string, text describing the X-axis of the plot
                   14028: 
                   14029: =item $ylabel: string, text describing the Y-axis of the plot
                   14030: 
                   14031: =item $colors: Array ref containing the hex color codes for the data to be 
                   14032: plotted in.  If undefined, default values will be used.
                   14033: 
                   14034: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14035: 
                   14036: =item $Ydata1: The first data set
                   14037: 
                   14038: =item $Min1: The minimum value of the left Y-axis
                   14039: 
                   14040: =item $Max1: The maximum value of the left Y-axis
                   14041: 
                   14042: =item $Ydata2: The second data set
                   14043: 
                   14044: =item $Min2: The minimum value of the right Y-axis
                   14045: 
                   14046: =item $Max2: The maximum value of the left Y-axis
                   14047: 
                   14048: =item %Values: hash indicating or overriding any default values which are 
                   14049: passed to graph.png.  
                   14050: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14051: 
                   14052: =back
                   14053: 
                   14054: Returns:
                   14055: 
                   14056: An <img> tag which references graph.png and the appropriate identifying
                   14057: information for the plot.
1.136     matthew  14058: 
                   14059: =cut
                   14060: 
                   14061: ############################################################
                   14062: ############################################################
1.137     matthew  14063: sub DrawXYYGraph {
                   14064:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14065:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14066:     #
                   14067:     # Create the identifier for the graph
                   14068:     my $identifier = &get_cgi_id();
                   14069:     my $id = 'cgi.'.$identifier;
                   14070:     #
                   14071:     $Title  = '' if (! defined($Title));
                   14072:     $xlabel = '' if (! defined($xlabel));
                   14073:     $ylabel = '' if (! defined($ylabel));
                   14074:     my %ValuesHash = 
                   14075:         (
1.369     www      14076:          $id.'.title'  => &escape($Title),
                   14077:          $id.'.xlabel' => &escape($xlabel),
                   14078:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14079:          $id.'.labels' => join(',',@$Xlabels),
                   14080:          $id.'.PlotType' => 'XY',
                   14081:          $id.'.NumSets' => 2,
1.137     matthew  14082:          $id.'.two_axes' => 1,
                   14083:          $id.'.y1_max_value' => $Max1,
                   14084:          $id.'.y1_min_value' => $Min1,
                   14085:          $id.'.y2_max_value' => $Max2,
                   14086:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14087:          );
                   14088:     #
1.137     matthew  14089:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14090:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14091:     }
                   14092:     #
                   14093:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14094:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14095:         return '';
                   14096:     }
                   14097:     my $NumSets=1;
1.137     matthew  14098:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14099:         next if (! ref($array));
                   14100:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14101:     }
                   14102:     #
                   14103:     # Deal with other parameters
                   14104:     while (my ($key,$value) = each(%Values)) {
                   14105:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14106:     }
                   14107:     #
1.646     raeburn  14108:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14109:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14110: }
                   14111: 
                   14112: ############################################################
                   14113: ############################################################
                   14114: 
                   14115: =pod
                   14116: 
1.157     matthew  14117: =back 
                   14118: 
1.139     matthew  14119: =head1 Statistics helper routines?  
                   14120: 
                   14121: Bad place for them but what the hell.
                   14122: 
1.157     matthew  14123: =over 4
                   14124: 
1.648     raeburn  14125: =item * &chartlink()
1.139     matthew  14126: 
                   14127: Returns a link to the chart for a specific student.  
                   14128: 
                   14129: Inputs:
                   14130: 
                   14131: =over 4
                   14132: 
                   14133: =item $linktext: The text of the link
                   14134: 
                   14135: =item $sname: The students username
                   14136: 
                   14137: =item $sdomain: The students domain
                   14138: 
                   14139: =back
                   14140: 
1.157     matthew  14141: =back
                   14142: 
1.139     matthew  14143: =cut
                   14144: 
                   14145: ############################################################
                   14146: ############################################################
                   14147: sub chartlink {
                   14148:     my ($linktext, $sname, $sdomain) = @_;
                   14149:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14150:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14151:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14152:        '">'.$linktext.'</a>';
1.153     matthew  14153: }
                   14154: 
                   14155: #######################################################
                   14156: #######################################################
                   14157: 
                   14158: =pod
                   14159: 
                   14160: =head1 Course Environment Routines
1.157     matthew  14161: 
                   14162: =over 4
1.153     matthew  14163: 
1.648     raeburn  14164: =item * &restore_course_settings()
1.153     matthew  14165: 
1.648     raeburn  14166: =item * &store_course_settings()
1.153     matthew  14167: 
                   14168: Restores/Store indicated form parameters from the course environment.
                   14169: Will not overwrite existing values of the form parameters.
                   14170: 
                   14171: Inputs: 
                   14172: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14173: 
                   14174: a hash ref describing the data to be stored.  For example:
                   14175:    
                   14176: %Save_Parameters = ('Status' => 'scalar',
                   14177:     'chartoutputmode' => 'scalar',
                   14178:     'chartoutputdata' => 'scalar',
                   14179:     'Section' => 'array',
1.373     raeburn  14180:     'Group' => 'array',
1.153     matthew  14181:     'StudentData' => 'array',
                   14182:     'Maps' => 'array');
                   14183: 
                   14184: Returns: both routines return nothing
                   14185: 
1.631     raeburn  14186: =back
                   14187: 
1.153     matthew  14188: =cut
                   14189: 
                   14190: #######################################################
                   14191: #######################################################
                   14192: sub store_course_settings {
1.496     albertel 14193:     return &store_settings($env{'request.course.id'},@_);
                   14194: }
                   14195: 
                   14196: sub store_settings {
1.153     matthew  14197:     # save to the environment
                   14198:     # appenv the same items, just to be safe
1.300     albertel 14199:     my $udom  = $env{'user.domain'};
                   14200:     my $uname = $env{'user.name'};
1.496     albertel 14201:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14202:     my %SaveHash;
                   14203:     my %AppHash;
                   14204:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14205:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14206:         my $envname = 'environment.'.$basename;
1.258     albertel 14207:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14208:             # Save this value away
                   14209:             if ($type eq 'scalar' &&
1.258     albertel 14210:                 (! exists($env{$envname}) || 
                   14211:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14212:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14213:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14214:             } elsif ($type eq 'array') {
                   14215:                 my $stored_form;
1.258     albertel 14216:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14217:                     $stored_form = join(',',
                   14218:                                         map {
1.369     www      14219:                                             &escape($_);
1.258     albertel 14220:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14221:                 } else {
                   14222:                     $stored_form = 
1.369     www      14223:                         &escape($env{'form.'.$setting});
1.153     matthew  14224:                 }
                   14225:                 # Determine if the array contents are the same.
1.258     albertel 14226:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14227:                     $SaveHash{$basename} = $stored_form;
                   14228:                     $AppHash{$envname}   = $stored_form;
                   14229:                 }
                   14230:             }
                   14231:         }
                   14232:     }
                   14233:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14234:                                           $udom,$uname);
1.153     matthew  14235:     if ($put_result !~ /^(ok|delayed)/) {
                   14236:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14237:                                  'got error:'.$put_result);
                   14238:     }
                   14239:     # Make sure these settings stick around in this session, too
1.646     raeburn  14240:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14241:     return;
                   14242: }
                   14243: 
                   14244: sub restore_course_settings {
1.499     albertel 14245:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14246: }
                   14247: 
                   14248: sub restore_settings {
                   14249:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14250:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14251:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14252:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14253:             '.'.$setting;
1.258     albertel 14254:         if (exists($env{$envname})) {
1.153     matthew  14255:             if ($type eq 'scalar') {
1.258     albertel 14256:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14257:             } elsif ($type eq 'array') {
1.258     albertel 14258:                 $env{'form.'.$setting} = [ 
1.153     matthew  14259:                                            map { 
1.369     www      14260:                                                &unescape($_); 
1.258     albertel 14261:                                            } split(',',$env{$envname})
1.153     matthew  14262:                                            ];
                   14263:             }
                   14264:         }
                   14265:     }
1.127     matthew  14266: }
                   14267: 
1.618     raeburn  14268: #######################################################
                   14269: #######################################################
                   14270: 
                   14271: =pod
                   14272: 
                   14273: =head1 Domain E-mail Routines  
                   14274: 
                   14275: =over 4
                   14276: 
1.648     raeburn  14277: =item * &build_recipient_list()
1.618     raeburn  14278: 
1.1075.2.44  raeburn  14279: Build recipient lists for following types of e-mail:
1.766     raeburn  14280: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14281: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14282: module change checking, student/employee ID conflict checks, as
                   14283: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14284: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14285: 
                   14286: Inputs:
1.1075.2.44  raeburn  14287: defmail (scalar - email address of default recipient),
                   14288: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14289: requestsmail, updatesmail, or idconflictsmail).
                   14290: 
1.619     raeburn  14291: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14292: 
                   14293: origmail (scalar - email address of recipient from loncapa.conf,
                   14294: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14295: 
1.1075.2.139  raeburn  14296: $requname username of requester (if mailing type is helpdeskmail)
                   14297: 
                   14298: $requdom domain of requester (if mailing type is helpdeskmail)
                   14299: 
                   14300: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14301: 
1.655     raeburn  14302: Returns: comma separated list of addresses to which to send e-mail.
                   14303: 
                   14304: =back
1.618     raeburn  14305: 
                   14306: =cut
                   14307: 
                   14308: ############################################################
                   14309: ############################################################
                   14310: sub build_recipient_list {
1.1075.2.139  raeburn  14311:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14312:     my @recipients;
1.1075.2.122  raeburn  14313:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14314:     my %domconfig =
1.1075.2.122  raeburn  14315:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14316:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14317:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14318:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14319:                 my @contacts = ('adminemail','supportemail');
                   14320:                 foreach my $item (@contacts) {
                   14321:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14322:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14323:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14324:                             push(@recipients,$addr);
                   14325:                         }
1.619     raeburn  14326:                     }
1.1075.2.122  raeburn  14327:                 }
                   14328:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14329:                 if ($mailing eq 'helpdeskmail') {
                   14330:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14331:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14332:                         my @ok_bccs;
                   14333:                         foreach my $bcc (@bccs) {
                   14334:                             $bcc =~ s/^\s+//g;
                   14335:                             $bcc =~ s/\s+$//g;
                   14336:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14337:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14338:                                     push(@ok_bccs,$bcc);
                   14339:                                 }
                   14340:                             }
                   14341:                         }
                   14342:                         if (@ok_bccs > 0) {
                   14343:                             $allbcc = join(', ',@ok_bccs);
                   14344:                         }
                   14345:                     }
                   14346:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14347:                 }
                   14348:             }
1.766     raeburn  14349:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14350:             $lastresort = $origmail;
1.618     raeburn  14351:         }
1.1075.2.139  raeburn  14352:         if ($mailing eq 'helpdeskmail') {
                   14353:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14354:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14355:                 my ($inststatus,$inststatus_checked);
                   14356:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14357:                     ($env{'user.domain'} ne 'public')) {
                   14358:                     $inststatus_checked = 1;
                   14359:                     $inststatus = $env{'environment.inststatus'};
                   14360:                 }
                   14361:                 unless ($inststatus_checked) {
                   14362:                     if (($requname ne '') && ($requdom ne '')) {
                   14363:                         if (($requname =~ /^$match_username$/) &&
                   14364:                             ($requdom =~ /^$match_domain$/) &&
                   14365:                             (&Apache::lonnet::domain($requdom))) {
                   14366:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14367:                                                                       $requdom);
                   14368:                             unless ($requhome eq 'no_host') {
                   14369:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14370:                                 $inststatus = $userenv{'inststatus'};
                   14371:                                 $inststatus_checked = 1;
                   14372:                             }
                   14373:                         }
                   14374:                     }
                   14375:                 }
                   14376:                 unless ($inststatus_checked) {
                   14377:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14378:                         my %srch = (srchby     => 'email',
                   14379:                                     srchdomain => $defdom,
                   14380:                                     srchterm   => $reqemail,
                   14381:                                     srchtype   => 'exact');
                   14382:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14383:                         foreach my $uname (keys(%srch_results)) {
                   14384:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14385:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14386:                                 $inststatus_checked = 1;
                   14387:                                 last;
                   14388:                             }
                   14389:                         }
                   14390:                         unless ($inststatus_checked) {
                   14391:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14392:                             if ($dirsrchres eq 'ok') {
                   14393:                                 foreach my $uname (keys(%srch_results)) {
                   14394:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14395:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14396:                                         $inststatus_checked = 1;
                   14397:                                         last;
                   14398:                                     }
                   14399:                                 }
                   14400:                             }
                   14401:                         }
                   14402:                     }
                   14403:                 }
                   14404:                 if ($inststatus ne '') {
                   14405:                     foreach my $status (split(/\:/,$inststatus)) {
                   14406:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14407:                             my @contacts = ('adminemail','supportemail');
                   14408:                             foreach my $item (@contacts) {
                   14409:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14410:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14411:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14412:                                         push(@recipients,$addr);
                   14413:                                     }
                   14414:                                 }
                   14415:                             }
                   14416:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14417:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14418:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14419:                                 my @ok_bccs;
                   14420:                                 foreach my $bcc (@bccs) {
                   14421:                                     $bcc =~ s/^\s+//g;
                   14422:                                     $bcc =~ s/\s+$//g;
                   14423:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14424:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14425:                                             push(@ok_bccs,$bcc);
                   14426:                                         }
                   14427:                                     }
                   14428:                                 }
                   14429:                                 if (@ok_bccs > 0) {
                   14430:                                     $allbcc = join(', ',@ok_bccs);
                   14431:                                 }
                   14432:                             }
                   14433:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14434:                             last;
                   14435:                         }
                   14436:                     }
                   14437:                 }
                   14438:             }
                   14439:         }
1.619     raeburn  14440:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14441:         $lastresort = $origmail;
                   14442:     }
1.1075.2.128  raeburn  14443:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14444:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14445:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14446:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14447:             my %what = (
                   14448:                           perlvar => 1,
                   14449:                        );
                   14450:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14451:             if ($primary) {
                   14452:                 my $gotaddr;
                   14453:                 my ($result,$returnhash) =
                   14454:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14455:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14456:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14457:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14458:                         $gotaddr = 1;
                   14459:                     }
                   14460:                 }
                   14461:                 unless ($gotaddr) {
                   14462:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14463:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14464:                     unless ($uintdom eq $intdom) {
                   14465:                         my %domconfig =
                   14466:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14467:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14468:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14469:                                 my @contacts = ('adminemail','supportemail');
                   14470:                                 foreach my $item (@contacts) {
                   14471:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14472:                                         my $addr = $domconfig{'contacts'}{$item};
                   14473:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14474:                                             push(@recipients,$addr);
                   14475:                                         }
                   14476:                                     }
                   14477:                                 }
                   14478:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14479:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14480:                                 }
                   14481:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14482:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14483:                                     my @ok_bccs;
                   14484:                                     foreach my $bcc (@bccs) {
                   14485:                                         $bcc =~ s/^\s+//g;
                   14486:                                         $bcc =~ s/\s+$//g;
                   14487:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14488:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14489:                                                 push(@ok_bccs,$bcc);
                   14490:                                             }
                   14491:                                         }
                   14492:                                     }
                   14493:                                     if (@ok_bccs > 0) {
                   14494:                                         $allbcc = join(', ',@ok_bccs);
                   14495:                                     }
                   14496:                                 }
                   14497:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14498:                             }
                   14499:                         }
                   14500:                     }
                   14501:                 }
                   14502:             }
                   14503:         }
1.618     raeburn  14504:     }
1.688     raeburn  14505:     if (defined($defmail)) {
                   14506:         if ($defmail ne '') {
                   14507:             push(@recipients,$defmail);
                   14508:         }
1.618     raeburn  14509:     }
                   14510:     if ($otheremails) {
1.619     raeburn  14511:         my @others;
                   14512:         if ($otheremails =~ /,/) {
                   14513:             @others = split(/,/,$otheremails);
1.618     raeburn  14514:         } else {
1.619     raeburn  14515:             push(@others,$otheremails);
                   14516:         }
                   14517:         foreach my $addr (@others) {
                   14518:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14519:                 push(@recipients,$addr);
                   14520:             }
1.618     raeburn  14521:         }
                   14522:     }
1.1075.2.128  raeburn  14523:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14524:         if ((!@recipients) && ($lastresort ne '')) {
                   14525:             push(@recipients,$lastresort);
                   14526:         }
                   14527:     } elsif ($lastresort ne '') {
                   14528:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14529:             push(@recipients,$lastresort);
                   14530:         }
                   14531:     }
                   14532:     my $recipientlist = join(',',@recipients);
                   14533:     if (wantarray) {
                   14534:         return ($recipientlist,$allbcc,$addtext);
                   14535:     } else {
                   14536:         return $recipientlist;
                   14537:     }
1.618     raeburn  14538: }
                   14539: 
1.127     matthew  14540: ############################################################
                   14541: ############################################################
1.154     albertel 14542: 
1.655     raeburn  14543: =pod
                   14544: 
                   14545: =head1 Course Catalog Routines
                   14546: 
                   14547: =over 4
                   14548: 
                   14549: =item * &gather_categories()
                   14550: 
                   14551: Converts category definitions - keys of categories hash stored in  
                   14552: coursecategories in configuration.db on the primary library server in a 
                   14553: domain - to an array.  Also generates javascript and idx hash used to 
                   14554: generate Domain Coordinator interface for editing Course Categories.
                   14555: 
                   14556: Inputs:
1.663     raeburn  14557: 
1.655     raeburn  14558: categories (reference to hash of category definitions).
1.663     raeburn  14559: 
1.655     raeburn  14560: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14561:       categories and subcategories).
1.663     raeburn  14562: 
1.655     raeburn  14563: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14564:       editing Course Categories).
1.663     raeburn  14565: 
1.655     raeburn  14566: jsarray (reference to array of categories used to create Javascript arrays for
                   14567:          Domain Coordinator interface for editing Course Categories).
                   14568: 
                   14569: Returns: nothing
                   14570: 
                   14571: Side effects: populates cats, idx and jsarray. 
                   14572: 
                   14573: =cut
                   14574: 
                   14575: sub gather_categories {
                   14576:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14577:     my %counters;
                   14578:     my $num = 0;
                   14579:     foreach my $item (keys(%{$categories})) {
                   14580:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14581:         if ($container eq '' && $depth == 0) {
                   14582:             $cats->[$depth][$categories->{$item}] = $cat;
                   14583:         } else {
                   14584:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14585:         }
                   14586:         my ($escitem,$tail) = split(/:/,$item,2);
                   14587:         if ($counters{$tail} eq '') {
                   14588:             $counters{$tail} = $num;
                   14589:             $num ++;
                   14590:         }
                   14591:         if (ref($idx) eq 'HASH') {
                   14592:             $idx->{$item} = $counters{$tail};
                   14593:         }
                   14594:         if (ref($jsarray) eq 'ARRAY') {
                   14595:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14596:         }
                   14597:     }
                   14598:     return;
                   14599: }
                   14600: 
                   14601: =pod
                   14602: 
                   14603: =item * &extract_categories()
                   14604: 
                   14605: Used to generate breadcrumb trails for course categories.
                   14606: 
                   14607: Inputs:
1.663     raeburn  14608: 
1.655     raeburn  14609: categories (reference to hash of category definitions).
1.663     raeburn  14610: 
1.655     raeburn  14611: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14612:       categories and subcategories).
1.663     raeburn  14613: 
1.655     raeburn  14614: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14615: 
1.655     raeburn  14616: allitems (reference to hash - key is category key 
                   14617:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14618: 
1.655     raeburn  14619: idx (reference to hash of counters used in Domain Coordinator interface for
                   14620:       editing Course Categories).
1.663     raeburn  14621: 
1.655     raeburn  14622: jsarray (reference to array of categories used to create Javascript arrays for
                   14623:          Domain Coordinator interface for editing Course Categories).
                   14624: 
1.665     raeburn  14625: subcats (reference to hash of arrays containing all subcategories within each 
                   14626:          category, -recursive)
                   14627: 
1.1075.2.132  raeburn  14628: maxd (reference to hash used to hold max depth for all top-level categories).
                   14629: 
1.655     raeburn  14630: Returns: nothing
                   14631: 
                   14632: Side effects: populates trails and allitems hash references.
                   14633: 
                   14634: =cut
                   14635: 
                   14636: sub extract_categories {
1.1075.2.132  raeburn  14637:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14638:     if (ref($categories) eq 'HASH') {
                   14639:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14640:         if (ref($cats->[0]) eq 'ARRAY') {
                   14641:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14642:                 my $name = $cats->[0][$i];
                   14643:                 my $item = &escape($name).'::0';
                   14644:                 my $trailstr;
                   14645:                 if ($name eq 'instcode') {
                   14646:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14647:                 } elsif ($name eq 'communities') {
                   14648:                     $trailstr = &mt('Communities');
1.655     raeburn  14649:                 } else {
                   14650:                     $trailstr = $name;
                   14651:                 }
                   14652:                 if ($allitems->{$item} eq '') {
                   14653:                     push(@{$trails},$trailstr);
                   14654:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14655:                 }
                   14656:                 my @parents = ($name);
                   14657:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14658:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14659:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14660:                         if (ref($subcats) eq 'HASH') {
                   14661:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14662:                         }
1.1075.2.132  raeburn  14663:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14664:                     }
                   14665:                 } else {
                   14666:                     if (ref($subcats) eq 'HASH') {
                   14667:                         $subcats->{$item} = [];
1.655     raeburn  14668:                     }
1.1075.2.132  raeburn  14669:                     if (ref($maxd) eq 'HASH') {
                   14670:                         $maxd->{$name} = 1;
                   14671:                     }
1.655     raeburn  14672:                 }
                   14673:             }
                   14674:         }
                   14675:     }
                   14676:     return;
                   14677: }
                   14678: 
                   14679: =pod
                   14680: 
1.1075.2.56  raeburn  14681: =item * &recurse_categories()
1.655     raeburn  14682: 
                   14683: Recursively used to generate breadcrumb trails for course categories.
                   14684: 
                   14685: Inputs:
1.663     raeburn  14686: 
1.655     raeburn  14687: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14688:       categories and subcategories).
1.663     raeburn  14689: 
1.655     raeburn  14690: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14691: 
                   14692: category (current course category, for which breadcrumb trail is being generated).
                   14693: 
                   14694: trails (reference to array of breadcrumb trails for each category).
                   14695: 
1.655     raeburn  14696: allitems (reference to hash - key is category key
                   14697:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14698: 
1.655     raeburn  14699: parents (array containing containers directories for current category, 
                   14700:          back to top level). 
                   14701: 
                   14702: Returns: nothing
                   14703: 
                   14704: Side effects: populates trails and allitems hash references
                   14705: 
                   14706: =cut
                   14707: 
                   14708: sub recurse_categories {
1.1075.2.132  raeburn  14709:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14710:     my $shallower = $depth - 1;
                   14711:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14712:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14713:             my $name = $cats->[$depth]{$category}[$k];
                   14714:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14715:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14716:             if ($allitems->{$item} eq '') {
                   14717:                 push(@{$trails},$trailstr);
                   14718:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14719:             }
                   14720:             my $deeper = $depth+1;
                   14721:             push(@{$parents},$category);
1.665     raeburn  14722:             if (ref($subcats) eq 'HASH') {
                   14723:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14724:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14725:                     my $higher;
                   14726:                     if ($j > 0) {
                   14727:                         $higher = &escape($parents->[$j]).':'.
                   14728:                                   &escape($parents->[$j-1]).':'.$j;
                   14729:                     } else {
                   14730:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14731:                     }
                   14732:                     push(@{$subcats->{$higher}},$subcat);
                   14733:                 }
                   14734:             }
                   14735:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14736:                                 $subcats,$maxd);
1.655     raeburn  14737:             pop(@{$parents});
                   14738:         }
                   14739:     } else {
                   14740:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14741:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14742:         if ($allitems->{$item} eq '') {
                   14743:             push(@{$trails},$trailstr);
                   14744:             $allitems->{$item} = scalar(@{$trails})-1;
                   14745:         }
1.1075.2.132  raeburn  14746:         if (ref($maxd) eq 'HASH') {
                   14747:             if ($depth > $maxd->{$parents->[0]}) {
                   14748:                 $maxd->{$parents->[0]} = $depth;
                   14749:             }
                   14750:         }
1.655     raeburn  14751:     }
                   14752:     return;
                   14753: }
                   14754: 
1.663     raeburn  14755: =pod
                   14756: 
1.1075.2.56  raeburn  14757: =item * &assign_categories_table()
1.663     raeburn  14758: 
                   14759: Create a datatable for display of hierarchical categories in a domain,
                   14760: with checkboxes to allow a course to be categorized. 
                   14761: 
                   14762: Inputs:
                   14763: 
                   14764: cathash - reference to hash of categories defined for the domain (from
                   14765:           configuration.db)
                   14766: 
                   14767: currcat - scalar with an & separated list of categories assigned to a course. 
                   14768: 
1.919     raeburn  14769: type    - scalar contains course type (Course or Community).
                   14770: 
1.1075.2.117  raeburn  14771: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14772:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14773: 
1.663     raeburn  14774: Returns: $output (markup to be displayed) 
                   14775: 
                   14776: =cut
                   14777: 
                   14778: sub assign_categories_table {
1.1075.2.117  raeburn  14779:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14780:     my $output;
                   14781:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14782:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14783:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14784:         $maxdepth = scalar(@cats);
                   14785:         if (@cats > 0) {
                   14786:             my $itemcount = 0;
                   14787:             if (ref($cats[0]) eq 'ARRAY') {
                   14788:                 my @currcategories;
                   14789:                 if ($currcat ne '') {
                   14790:                     @currcategories = split('&',$currcat);
                   14791:                 }
1.919     raeburn  14792:                 my $table;
1.663     raeburn  14793:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14794:                     my $parent = $cats[0][$i];
1.919     raeburn  14795:                     next if ($parent eq 'instcode');
                   14796:                     if ($type eq 'Community') {
                   14797:                         next unless ($parent eq 'communities');
                   14798:                     } else {
                   14799:                         next if ($parent eq 'communities');
                   14800:                     }
1.663     raeburn  14801:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14802:                     my $item = &escape($parent).'::0';
                   14803:                     my $checked = '';
                   14804:                     if (@currcategories > 0) {
                   14805:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14806:                             $checked = ' checked="checked"';
1.663     raeburn  14807:                         }
                   14808:                     }
1.919     raeburn  14809:                     my $parent_title = $parent;
                   14810:                     if ($parent eq 'communities') {
                   14811:                         $parent_title = &mt('Communities');
                   14812:                     }
                   14813:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14814:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14815:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14816:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14817:                     my $depth = 1;
                   14818:                     push(@path,$parent);
1.1075.2.117  raeburn  14819:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14820:                     pop(@path);
1.919     raeburn  14821:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14822:                     $itemcount ++;
                   14823:                 }
1.919     raeburn  14824:                 if ($itemcount) {
                   14825:                     $output = &Apache::loncommon::start_data_table().
                   14826:                               $table.
                   14827:                               &Apache::loncommon::end_data_table();
                   14828:                 }
1.663     raeburn  14829:             }
                   14830:         }
                   14831:     }
                   14832:     return $output;
                   14833: }
                   14834: 
                   14835: =pod
                   14836: 
1.1075.2.56  raeburn  14837: =item * &assign_category_rows()
1.663     raeburn  14838: 
                   14839: Create a datatable row for display of nested categories in a domain,
                   14840: with checkboxes to allow a course to be categorized,called recursively.
                   14841: 
                   14842: Inputs:
                   14843: 
                   14844: itemcount - track row number for alternating colors
                   14845: 
                   14846: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14847:       categories and subcategories.
                   14848: 
                   14849: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14850: 
                   14851: parent - parent of current category item
                   14852: 
                   14853: path - Array containing all categories back up through the hierarchy from the
                   14854:        current category to the top level.
                   14855: 
                   14856: currcategories - reference to array of current categories assigned to the course
                   14857: 
1.1075.2.117  raeburn  14858: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14859:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14860: 
1.663     raeburn  14861: Returns: $output (markup to be displayed).
                   14862: 
                   14863: =cut
                   14864: 
                   14865: sub assign_category_rows {
1.1075.2.117  raeburn  14866:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14867:     my ($text,$name,$item,$chgstr);
                   14868:     if (ref($cats) eq 'ARRAY') {
                   14869:         my $maxdepth = scalar(@{$cats});
                   14870:         if (ref($cats->[$depth]) eq 'HASH') {
                   14871:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14872:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14873:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14874:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14875:                 for (my $j=0; $j<$numchildren; $j++) {
                   14876:                     $name = $cats->[$depth]{$parent}[$j];
                   14877:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14878:                     my $deeper = $depth+1;
                   14879:                     my $checked = '';
                   14880:                     if (ref($currcategories) eq 'ARRAY') {
                   14881:                         if (@{$currcategories} > 0) {
                   14882:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14883:                                 $checked = ' checked="checked"';
1.663     raeburn  14884:                             }
                   14885:                         }
                   14886:                     }
1.664     raeburn  14887:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14888:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14889:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14890:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14891:                              '</td><td>';
1.663     raeburn  14892:                     if (ref($path) eq 'ARRAY') {
                   14893:                         push(@{$path},$name);
1.1075.2.117  raeburn  14894:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14895:                         pop(@{$path});
                   14896:                     }
                   14897:                     $text .= '</td></tr>';
                   14898:                 }
                   14899:                 $text .= '</table></td>';
                   14900:             }
                   14901:         }
                   14902:     }
                   14903:     return $text;
                   14904: }
                   14905: 
1.1075.2.69  raeburn  14906: =pod
                   14907: 
                   14908: =back
                   14909: 
                   14910: =cut
                   14911: 
1.655     raeburn  14912: ############################################################
                   14913: ############################################################
                   14914: 
                   14915: 
1.443     albertel 14916: sub commit_customrole {
1.664     raeburn  14917:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14918:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14919:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14920:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14921:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14922:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14923:                  '</b><br />';
                   14924:     return $output;
                   14925: }
                   14926: 
                   14927: sub commit_standardrole {
1.1075.2.31  raeburn  14928:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14929:     my ($output,$logmsg,$linefeed);
                   14930:     if ($context eq 'auto') {
                   14931:         $linefeed = "\n";
                   14932:     } else {
                   14933:         $linefeed = "<br />\n";
                   14934:     }  
1.443     albertel 14935:     if ($three eq 'st') {
1.541     raeburn  14936:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14937:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14938:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14939:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14940:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14941:         } else {
1.541     raeburn  14942:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14943:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14944:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14945:             if ($context eq 'auto') {
                   14946:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14947:             } else {
                   14948:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14949:                &mt('Add to classlist').': <b>ok</b>';
                   14950:             }
                   14951:             $output .= $linefeed;
1.443     albertel 14952:         }
                   14953:     } else {
                   14954:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14955:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14956:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14957:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14958:         if ($context eq 'auto') {
                   14959:             $output .= $result.$linefeed;
                   14960:         } else {
                   14961:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14962:         }
1.443     albertel 14963:     }
                   14964:     return $output;
                   14965: }
                   14966: 
                   14967: sub commit_studentrole {
1.1075.2.31  raeburn  14968:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14969:         $credits) = @_;
1.626     raeburn  14970:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14971:     if ($context eq 'auto') {
                   14972:         $linefeed = "\n";
                   14973:     } else {
                   14974:         $linefeed = '<br />'."\n";
                   14975:     }
1.443     albertel 14976:     if (defined($one) && defined($two)) {
                   14977:         my $cid=$one.'_'.$two;
                   14978:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14979:         my $secchange = 0;
                   14980:         my $expire_role_result;
                   14981:         my $modify_section_result;
1.628     raeburn  14982:         if ($oldsec ne '-1') { 
                   14983:             if ($oldsec ne $sec) {
1.443     albertel 14984:                 $secchange = 1;
1.628     raeburn  14985:                 my $now = time;
1.443     albertel 14986:                 my $uurl='/'.$cid;
                   14987:                 $uurl=~s/\_/\//g;
                   14988:                 if ($oldsec) {
                   14989:                     $uurl.='/'.$oldsec;
                   14990:                 }
1.626     raeburn  14991:                 $oldsecurl = $uurl;
1.628     raeburn  14992:                 $expire_role_result = 
1.652     raeburn  14993:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14994:                 if ($env{'request.course.sec'} ne '') { 
                   14995:                     if ($expire_role_result eq 'refused') {
                   14996:                         my @roles = ('st');
                   14997:                         my @statuses = ('previous');
                   14998:                         my @roledoms = ($one);
                   14999:                         my $withsec = 1;
                   15000:                         my %roleshash = 
                   15001:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15002:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15003:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15004:                             my ($oldstart,$oldend) = 
                   15005:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15006:                             if ($oldend > 0 && $oldend <= $now) {
                   15007:                                 $expire_role_result = 'ok';
                   15008:                             }
                   15009:                         }
                   15010:                     }
                   15011:                 }
1.443     albertel 15012:                 $result = $expire_role_result;
                   15013:             }
                   15014:         }
                   15015:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15016:             $modify_section_result = 
                   15017:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15018:                                                            undef,undef,undef,$sec,
                   15019:                                                            $end,$start,'','',$cid,
                   15020:                                                            '',$context,$credits);
1.443     albertel 15021:             if ($modify_section_result =~ /^ok/) {
                   15022:                 if ($secchange == 1) {
1.628     raeburn  15023:                     if ($sec eq '') {
                   15024:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15025:                     } else {
                   15026:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15027:                     }
1.443     albertel 15028:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15029:                     if ($sec eq '') {
                   15030:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15031:                     } else {
                   15032:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15033:                     }
1.443     albertel 15034:                 } else {
1.628     raeburn  15035:                     if ($sec eq '') {
                   15036:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15037:                     } else {
                   15038:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15039:                     }
1.443     albertel 15040:                 }
                   15041:             } else {
1.628     raeburn  15042:                 if ($secchange) {       
                   15043:                     $$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;
                   15044:                 } else {
                   15045:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15046:                 }
1.443     albertel 15047:             }
                   15048:             $result = $modify_section_result;
                   15049:         } elsif ($secchange == 1) {
1.628     raeburn  15050:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15051:                 $$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  15052:             } else {
                   15053:                 $$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;
                   15054:             }
1.626     raeburn  15055:             if ($expire_role_result eq 'refused') {
                   15056:                 my $newsecurl = '/'.$cid;
                   15057:                 $newsecurl =~ s/\_/\//g;
                   15058:                 if ($sec ne '') {
                   15059:                     $newsecurl.='/'.$sec;
                   15060:                 }
                   15061:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15062:                     if ($sec eq '') {
                   15063:                         $$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;
                   15064:                     } else {
                   15065:                         $$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;
                   15066:                     }
                   15067:                 }
                   15068:             }
1.443     albertel 15069:         }
                   15070:     } else {
1.626     raeburn  15071:         $$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 15072:         $result = "error: incomplete course id\n";
                   15073:     }
                   15074:     return $result;
                   15075: }
                   15076: 
1.1075.2.25  raeburn  15077: sub show_role_extent {
                   15078:     my ($scope,$context,$role) = @_;
                   15079:     $scope =~ s{^/}{};
                   15080:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15081:     push(@courseroles,'co');
                   15082:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15083:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15084:         $scope =~ s{/}{_};
                   15085:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15086:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15087:         my ($audom,$auname) = split(/\//,$scope);
                   15088:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15089:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15090:     } else {
                   15091:         $scope =~ s{/$}{};
                   15092:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15093:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15094:     }
                   15095: }
                   15096: 
1.443     albertel 15097: ############################################################
                   15098: ############################################################
                   15099: 
1.566     albertel 15100: sub check_clone {
1.578     raeburn  15101:     my ($args,$linefeed) = @_;
1.566     albertel 15102:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15103:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15104:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.141.  .5(raebu 15105:20):     my $clonetitle;
                   15106:20):     my @clonemsg;
1.566     albertel 15107:     my $can_clone = 0;
1.944     raeburn  15108:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15109:     if ($lctype ne 'community') {
                   15110:         $lctype = 'course';
                   15111:     }
1.566     albertel 15112:     if ($clonehome eq 'no_host') {
1.944     raeburn  15113:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.141.  .5(raebu 15114:20):             push(@clonemsg,({
                   15115:20):                               mt => 'No new community created.',
                   15116:20):                               args => [],
                   15117:20):                             },
                   15118:20):                             {
                   15119:20):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15120:20):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15121:20):                             }));
1.908     raeburn  15122:         } else {
1.1075.2.141.  .5(raebu 15123:20):             push(@clonemsg,({
                   15124:20):                               mt => 'No new course created.',
                   15125:20):                               args => [],
                   15126:20):                             },
                   15127:20):                             {
                   15128:20):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15129:20):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15130:20):                             }));
                   15131:20):         }
1.566     albertel 15132:     } else {
                   15133: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.141.  .5(raebu 15134:20):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15135:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15136:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.141.  .5(raebu 15137:20):                 push(@clonemsg,({
                   15138:20):                                   mt => 'No new community created.',
                   15139:20):                                   args => [],
                   15140:20):                                 },
                   15141:20):                                 {
                   15142:20):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15143:20):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15144:20):                                 }));
                   15145:20):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15146:             }
                   15147:         }
1.1075.2.119  raeburn  15148: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15149:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15150: 	    $can_clone = 1;
                   15151: 	} else {
1.1075.2.95  raeburn  15152: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15153: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15154:             if ($clonehash{'cloners'} eq '') {
                   15155:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15156:                 if ($domdefs{'canclone'}) {
                   15157:                     unless ($domdefs{'canclone'} eq 'none') {
                   15158:                         if ($domdefs{'canclone'} eq 'domain') {
                   15159:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15160:                                 $can_clone = 1;
                   15161:                             }
                   15162:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15163:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15164:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15165:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15166:                                 $can_clone = 1;
                   15167:                             }
                   15168:                         }
                   15169:                     }
1.908     raeburn  15170:                 }
1.1075.2.95  raeburn  15171:             } else {
                   15172: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15173:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15174:                     $can_clone = 1;
1.1075.2.95  raeburn  15175:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15176:                     $can_clone = 1;
1.1075.2.96  raeburn  15177:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15178:                     $can_clone = 1;
1.1075.2.95  raeburn  15179:                 }
                   15180:                 unless ($can_clone) {
1.1075.2.96  raeburn  15181:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15182:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15183:                         my (%gotdomdefaults,%gotcodedefaults);
                   15184:                         foreach my $cloner (@cloners) {
                   15185:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15186:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15187:                                 my (%codedefaults,@code_order);
                   15188:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15189:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15190:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15191:                                     }
                   15192:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15193:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15194:                                     }
                   15195:                                 } else {
                   15196:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15197:                                                                             \%codedefaults,
                   15198:                                                                             \@code_order);
                   15199:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15200:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15201:                                 }
                   15202:                                 if (@code_order > 0) {
                   15203:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15204:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15205:                                                                                 $args->{'crscode'})) {
                   15206:                                         $can_clone = 1;
                   15207:                                         last;
                   15208:                                     }
                   15209:                                 }
                   15210:                             }
                   15211:                         }
                   15212:                     }
1.1075.2.96  raeburn  15213:                 }
                   15214:             }
                   15215:             unless ($can_clone) {
                   15216:                 my $ccrole = 'cc';
                   15217:                 if ($args->{'crstype'} eq 'Community') {
                   15218:                     $ccrole = 'co';
                   15219:                 }
                   15220:                 my %roleshash =
                   15221:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15222:                                                   $args->{'ccdomain'},
                   15223:                                                   'userroles',['active'],[$ccrole],
                   15224:                                                   [$args->{'clonedomain'}]);
                   15225:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15226:                     $can_clone = 1;
                   15227:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15228:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15229:                     $can_clone = 1;
1.1075.2.95  raeburn  15230:                 }
                   15231:             }
                   15232:             unless ($can_clone) {
                   15233:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.141.  .5(raebu 15234:20):                     push(@clonemsg,({
                   15235:20):                                       mt => 'No new community created.',
                   15236:20):                                       args => [],
                   15237:20):                                     },
                   15238:20):                                     {
                   15239:20):                                       mt => 'The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',
                   15240:20):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15241:20):                                     }));
1.1075.2.95  raeburn  15242:                 } else {
1.1075.2.141.  .5(raebu 15243:20):                     push(@clonemsg,({
                   15244:20):                                       mt => 'No new course created.',
                   15245:20):                                       args => [],
                   15246:20):                                     },
                   15247:20):                                     {
                   15248:20):                                       mt => 'The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',
                   15249:20):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   15250:20):                                     }));
                   15251:20):                 }
1.566     albertel 15252: 	    }
1.578     raeburn  15253:         }
1.566     albertel 15254:     }
1.1075.2.141.  .5(raebu 15255:20):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15256: }
                   15257: 
1.444     albertel 15258: sub construct_course {
1.1075.2.119  raeburn  15259:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.141.  .5(raebu 15260:20):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   15261:20):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  15262:     my $linefeed =  '<br />'."\n";
                   15263:     if ($context eq 'auto') {
                   15264:         $linefeed = "\n";
                   15265:     }
1.566     albertel 15266: 
                   15267: #
                   15268: # Are we cloning?
                   15269: #
1.1075.2.141.  .5(raebu 15270:20):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 15271:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.141.  .5(raebu 15272:20): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 15273:         if (!$can_clone) {
1.1075.2.141.  .5(raebu 15274:20): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 15275: 	}
                   15276:     }
                   15277: 
1.444     albertel 15278: #
                   15279: # Open course
                   15280: #
                   15281:     my $crstype = lc($args->{'crstype'});
                   15282:     my %cenv=();
                   15283:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15284:                                              $args->{'cdescr'},
                   15285:                                              $args->{'curl'},
                   15286:                                              $args->{'course_home'},
                   15287:                                              $args->{'nonstandard'},
                   15288:                                              $args->{'crscode'},
                   15289:                                              $args->{'ccuname'}.':'.
                   15290:                                              $args->{'ccdomain'},
1.882     raeburn  15291:                                              $args->{'crstype'},
1.1075.2.141.  .5(raebu 15292:20):                                              $cnum,$context,$category,
                   15293:20):                                              $callercontext);
1.444     albertel 15294: 
                   15295:     # Note: The testing routines depend on this being output; see 
                   15296:     # Utils::Course. This needs to at least be output as a comment
                   15297:     # if anyone ever decides to not show this, and Utils::Course::new
                   15298:     # will need to be suitably modified.
1.1075.2.141.  .5(raebu 15299:20):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15300:20):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15301:20):     } else {
                   15302:20):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   15303:20):     }
1.943     raeburn  15304:     if ($$courseid =~ /^error:/) {
1.1075.2.141.  .5(raebu 15305:20):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15306:     }
                   15307: 
1.444     albertel 15308: #
                   15309: # Check if created correctly
                   15310: #
1.479     albertel 15311:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15312:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15313:     if ($crsuhome eq 'no_host') {
1.1075.2.141.  .5(raebu 15314:20):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   15315:20):             $outcome .= &mt_user($user_lh,
                   15316:20):                             'Course creation failed, unrecognized course home server.');
                   15317:20):         } else {
                   15318:20):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   15319:20):         }
                   15320:20):         $outcome .= $linefeed;
                   15321:20):         return (0,$outcome,$clonemsgref);
1.943     raeburn  15322:     }
1.541     raeburn  15323:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15324: 
1.444     albertel 15325: #
1.566     albertel 15326: # Do the cloning
                   15327: #   
1.1075.2.141.  .5(raebu 15328:20):     my @clonemsg;
1.566     albertel 15329:     if ($can_clone && $cloneid) {
1.1075.2.141.  .5(raebu 15330:20):         push(@clonemsg,
                   15331:20):                       {
                   15332:20):                           mt => 'Created [_1] by cloning from [_2]',
                   15333:20):                           args => [$crstype,$clonetitle],
                   15334:20):                       });
1.566     albertel 15335: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15336: # Copy all files
1.1075.2.141.  .5(raebu 15337:20):         my @info =
                   15338:20): 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   15339:20):                                                      $args->{'dateshift'},$args->{'crscode'},
                   15340:20):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   15341:20):                                                      $args->{'tinyurls'});
                   15342:20):         if (@info) {
                   15343:20):             push(@clonemsg,@info);
                   15344:20):         }
1.444     albertel 15345: # Restore URL
1.566     albertel 15346: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15347: # Restore title
1.566     albertel 15348: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15349: # Restore creation date, creator and creation context.
                   15350:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15351:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15352:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15353: # Mark as cloned
1.566     albertel 15354: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15355: # Need to clone grading mode
                   15356:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15357:         $cenv{'grading'}=$newenv{'grading'};
                   15358: # Do not clone these environment entries
                   15359:         &Apache::lonnet::del('environment',
                   15360:                   ['default_enrollment_start_date',
                   15361:                    'default_enrollment_end_date',
                   15362:                    'question.email',
                   15363:                    'policy.email',
                   15364:                    'comment.email',
                   15365:                    'pch.users.denied',
1.725     raeburn  15366:                    'plc.users.denied',
                   15367:                    'hidefromcat',
1.1075.2.36  raeburn  15368:                    'checkforpriv',
1.1075.2.59  raeburn  15369:                    'categories',
                   15370:                    'internal.uniquecode'],
1.638     www      15371:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15372:         if ($args->{'textbook'}) {
                   15373:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15374:         }
1.444     albertel 15375:     }
1.566     albertel 15376: 
1.444     albertel 15377: #
                   15378: # Set environment (will override cloned, if existing)
                   15379: #
                   15380:     my @sections = ();
                   15381:     my @xlists = ();
                   15382:     if ($args->{'crstype'}) {
                   15383:         $cenv{'type'}=$args->{'crstype'};
                   15384:     }
                   15385:     if ($args->{'crsid'}) {
                   15386:         $cenv{'courseid'}=$args->{'crsid'};
                   15387:     }
                   15388:     if ($args->{'crscode'}) {
                   15389:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15390:     }
                   15391:     if ($args->{'crsquota'} ne '') {
                   15392:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15393:     } else {
                   15394:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15395:     }
                   15396:     if ($args->{'ccuname'}) {
                   15397:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15398:                                         ':'.$args->{'ccdomain'};
                   15399:     } else {
                   15400:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15401:     }
1.1075.2.31  raeburn  15402:     if ($args->{'defaultcredits'}) {
                   15403:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15404:     }
1.444     albertel 15405:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15406:     if ($args->{'crssections'}) {
                   15407:         $cenv{'internal.sectionnums'} = '';
                   15408:         if ($args->{'crssections'} =~ m/,/) {
                   15409:             @sections = split/,/,$args->{'crssections'};
                   15410:         } else {
                   15411:             $sections[0] = $args->{'crssections'};
                   15412:         }
                   15413:         if (@sections > 0) {
                   15414:             foreach my $item (@sections) {
                   15415:                 my ($sec,$gp) = split/:/,$item;
                   15416:                 my $class = $args->{'crscode'}.$sec;
                   15417:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15418:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15419:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15420:                     push(@badclasses,$class);
1.444     albertel 15421:                 }
                   15422:             }
                   15423:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15424:         }
                   15425:     }
                   15426: # do not hide course coordinator from staff listing, 
                   15427: # even if privileged
                   15428:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15429: # add course coordinator's domain to domains to check for privileged users
                   15430: # if different to course domain
                   15431:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15432:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15433:     }
1.444     albertel 15434: # add crosslistings
                   15435:     if ($args->{'crsxlist'}) {
                   15436:         $cenv{'internal.crosslistings'}='';
                   15437:         if ($args->{'crsxlist'} =~ m/,/) {
                   15438:             @xlists = split/,/,$args->{'crsxlist'};
                   15439:         } else {
                   15440:             $xlists[0] = $args->{'crsxlist'};
                   15441:         }
                   15442:         if (@xlists > 0) {
                   15443:             foreach my $item (@xlists) {
                   15444:                 my ($xl,$gp) = split/:/,$item;
                   15445:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15446:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15447:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15448:                     push(@badclasses,$xl);
1.444     albertel 15449:                 }
                   15450:             }
                   15451:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15452:         }
                   15453:     }
                   15454:     if ($args->{'autoadds'}) {
                   15455:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15456:     }
                   15457:     if ($args->{'autodrops'}) {
                   15458:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15459:     }
                   15460: # check for notification of enrollment changes
                   15461:     my @notified = ();
                   15462:     if ($args->{'notify_owner'}) {
                   15463:         if ($args->{'ccuname'} ne '') {
                   15464:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15465:         }
                   15466:     }
                   15467:     if ($args->{'notify_dc'}) {
                   15468:         if ($uname ne '') { 
1.630     raeburn  15469:             push(@notified,$uname.':'.$udom);
1.444     albertel 15470:         }
                   15471:     }
                   15472:     if (@notified > 0) {
                   15473:         my $notifylist;
                   15474:         if (@notified > 1) {
                   15475:             $notifylist = join(',',@notified);
                   15476:         } else {
                   15477:             $notifylist = $notified[0];
                   15478:         }
                   15479:         $cenv{'internal.notifylist'} = $notifylist;
                   15480:     }
                   15481:     if (@badclasses > 0) {
                   15482:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15483:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15484:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15485:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15486:         );
1.1075.2.119  raeburn  15487:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15488:                            &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  15489:         if ($context eq 'auto') {
                   15490:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15491:         } else {
1.566     albertel 15492:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15493:         }
                   15494:         foreach my $item (@badclasses) {
1.541     raeburn  15495:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15496:                 $outcome .= " - $item\n";
1.541     raeburn  15497:             } else {
1.1075.2.119  raeburn  15498:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15499:             }
1.1075.2.119  raeburn  15500:         }
                   15501:         if ($context eq 'auto') {
                   15502:             $outcome .= $linefeed;
                   15503:         } else {
                   15504:             $outcome .= "</ul><br /><br /></div>\n";
                   15505:         }
1.444     albertel 15506:     }
                   15507:     if ($args->{'no_end_date'}) {
                   15508:         $args->{'endaccess'} = 0;
                   15509:     }
                   15510:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15511:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15512:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15513:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15514:     if ($args->{'showphotos'}) {
                   15515:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15516:     }
                   15517:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15518:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15519:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15520:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15521:             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'); 
                   15522:             if ($context eq 'auto') {
                   15523:                 $outcome .= $krb_msg;
                   15524:             } else {
1.566     albertel 15525:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15526:             }
                   15527:             $outcome .= $linefeed;
1.444     albertel 15528:         }
                   15529:     }
                   15530:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15531:        if ($args->{'setpolicy'}) {
                   15532:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15533:        }
                   15534:        if ($args->{'setcontent'}) {
                   15535:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15536:        }
1.1075.2.110  raeburn  15537:        if ($args->{'setcomment'}) {
                   15538:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15539:        }
1.444     albertel 15540:     }
                   15541:     if ($args->{'reshome'}) {
                   15542: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15543: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15544:     }
                   15545: #
                   15546: # course has keyed access
                   15547: #
                   15548:     if ($args->{'setkeys'}) {
                   15549:        $cenv{'keyaccess'}='yes';
                   15550:     }
                   15551: # if specified, key authority is not course, but user
                   15552: # only active if keyaccess is yes
                   15553:     if ($args->{'keyauth'}) {
1.487     albertel 15554: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15555: 	$user = &LONCAPA::clean_username($user);
                   15556: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15557: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15558: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15559: 	}
                   15560:     }
                   15561: 
1.1075.2.59  raeburn  15562: #
                   15563: #  generate and store uniquecode (available to course requester), if course should have one.
                   15564: #
                   15565:     if ($args->{'uniquecode'}) {
                   15566:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15567:         if ($code) {
                   15568:             $cenv{'internal.uniquecode'} = $code;
                   15569:             my %crsinfo =
                   15570:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15571:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15572:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15573:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15574:             }
                   15575:             if (ref($coderef)) {
                   15576:                 $$coderef = $code;
                   15577:             }
                   15578:         }
                   15579:     }
                   15580: 
1.444     albertel 15581:     if ($args->{'disresdis'}) {
                   15582:         $cenv{'pch.roles.denied'}='st';
                   15583:     }
                   15584:     if ($args->{'disablechat'}) {
                   15585:         $cenv{'plc.roles.denied'}='st';
                   15586:     }
                   15587: 
                   15588:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15589:     # course
                   15590:     $cenv{'course.helper.not.run'} = 1;
                   15591:     #
                   15592:     # Use new Randomseed
                   15593:     #
                   15594:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15595:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15596:     #
                   15597:     # The encryption code and receipt prefix for this course
                   15598:     #
                   15599:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15600:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15601:     #
                   15602:     # By default, use standard grading
                   15603:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15604: 
1.541     raeburn  15605:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15606:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15607: #
                   15608: # Open all assignments
                   15609: #
                   15610:     if ($args->{'openall'}) {
1.1075.2.141.  .4(raebu 15611:20):        my $opendate = time;
                   15612:20):        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15613:20):            $opendate = $args->{'openallfrom'};
                   15614:20):        }
1.444     albertel 15615:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.141.  .4(raebu 15616:20):        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15617:                            $storeunder.'.type' => 'date_start');
1.1075.2.141.  .4(raebu 15618:20):        $outcome .= &mt('All assignments open starting [_1]',
                   15619:20):                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15620:20):                    &Apache::lonnet::cput
                   15621:20):                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15622:    }
                   15623: #
                   15624: # Set first page
                   15625: #
                   15626:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15627: 	    || ($cloneid)) {
1.445     albertel 15628: 	use LONCAPA::map;
1.444     albertel 15629: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15630: 
                   15631: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15632:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15633: 
1.444     albertel 15634:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15635:         my $title; my $url;
                   15636:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15637: 	    $title=&mt('Syllabus');
1.444     albertel 15638:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15639:         } else {
1.963     raeburn  15640:             $title=&mt('Table of Contents');
1.444     albertel 15641:             $url='/adm/navmaps';
                   15642:         }
1.445     albertel 15643: 
                   15644:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15645: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15646: 
                   15647: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15648:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15649:     }
1.566     albertel 15650: 
1.1075.2.141.  .5(raebu 15651:20):     return (1,$outcome,\@clonemsg);
1.444     albertel 15652: }
                   15653: 
1.1075.2.59  raeburn  15654: sub make_unique_code {
                   15655:     my ($cdom,$cnum) = @_;
                   15656:     # get lock on uniquecodes db
                   15657:     my $lockhash = {
                   15658:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15659:                                                   ':'.$env{'user.domain'},
                   15660:                    };
                   15661:     my $tries = 0;
                   15662:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15663:     my ($code,$error);
                   15664: 
                   15665:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15666:         $tries ++;
                   15667:         sleep 1;
                   15668:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15669:     }
                   15670:     if ($gotlock eq 'ok') {
                   15671:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15672:         my $gotcode;
                   15673:         my $attempts = 0;
                   15674:         while ((!$gotcode) && ($attempts < 100)) {
                   15675:             $code = &generate_code();
                   15676:             if (!exists($currcodes{$code})) {
                   15677:                 $gotcode = 1;
                   15678:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15679:                     $error = 'nostore';
                   15680:                 }
                   15681:             }
                   15682:             $attempts ++;
                   15683:         }
                   15684:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15685:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15686:     } else {
                   15687:         $error = 'nolock';
                   15688:     }
                   15689:     return ($code,$error);
                   15690: }
                   15691: 
                   15692: sub generate_code {
                   15693:     my $code;
                   15694:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15695:     for (my $i=0; $i<6; $i++) {
                   15696:         my $lettnum = int (rand 2);
                   15697:         my $item = '';
                   15698:         if ($lettnum) {
                   15699:             $item = $letts[int( rand(18) )];
                   15700:         } else {
                   15701:             $item = 1+int( rand(8) );
                   15702:         }
                   15703:         $code .= $item;
                   15704:     }
                   15705:     return $code;
                   15706: }
                   15707: 
1.444     albertel 15708: ############################################################
                   15709: ############################################################
                   15710: 
1.953     droeschl 15711: #SD
                   15712: # only Community and Course, or anything else?
1.378     raeburn  15713: sub course_type {
                   15714:     my ($cid) = @_;
                   15715:     if (!defined($cid)) {
                   15716:         $cid = $env{'request.course.id'};
                   15717:     }
1.404     albertel 15718:     if (defined($env{'course.'.$cid.'.type'})) {
                   15719:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15720:     } else {
                   15721:         return 'Course';
1.377     raeburn  15722:     }
                   15723: }
1.156     albertel 15724: 
1.406     raeburn  15725: sub group_term {
                   15726:     my $crstype = &course_type();
                   15727:     my %names = (
                   15728:                   'Course' => 'group',
1.865     raeburn  15729:                   'Community' => 'group',
1.406     raeburn  15730:                 );
                   15731:     return $names{$crstype};
                   15732: }
                   15733: 
1.902     raeburn  15734: sub course_types {
1.1075.2.59  raeburn  15735:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15736:     my %typename = (
                   15737:                          official   => 'Official course',
                   15738:                          unofficial => 'Unofficial course',
                   15739:                          community  => 'Community',
1.1075.2.59  raeburn  15740:                          textbook   => 'Textbook course',
1.902     raeburn  15741:                    );
                   15742:     return (\@types,\%typename);
                   15743: }
                   15744: 
1.156     albertel 15745: sub icon {
                   15746:     my ($file)=@_;
1.505     albertel 15747:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15748:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15749:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15750:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15751: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15752: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15753: 	            $curfext.".gif") {
                   15754: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15755: 		$curfext.".gif";
                   15756: 	}
                   15757:     }
1.249     albertel 15758:     return &lonhttpdurl($iconname);
1.154     albertel 15759: } 
1.84      albertel 15760: 
1.575     albertel 15761: sub lonhttpdurl {
1.692     www      15762: #
                   15763: # Had been used for "small fry" static images on separate port 8080.
                   15764: # Modify here if lightweight http functionality desired again.
                   15765: # Currently eliminated due to increasing firewall issues.
                   15766: #
1.575     albertel 15767:     my ($url)=@_;
1.692     www      15768:     return $url;
1.215     albertel 15769: }
                   15770: 
1.213     albertel 15771: sub connection_aborted {
                   15772:     my ($r)=@_;
                   15773:     $r->print(" ");$r->rflush();
                   15774:     my $c = $r->connection;
                   15775:     return $c->aborted();
                   15776: }
                   15777: 
1.221     foxr     15778: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15779: #    strings as 'strings'.
                   15780: sub escape_single {
1.221     foxr     15781:     my ($input) = @_;
1.223     albertel 15782:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15783:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15784:     return $input;
                   15785: }
1.223     albertel 15786: 
1.222     foxr     15787: #  Same as escape_single, but escape's "'s  This 
                   15788: #  can be used for  "strings"
                   15789: sub escape_double {
                   15790:     my ($input) = @_;
                   15791:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15792:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15793:     return $input;
                   15794: }
1.223     albertel 15795:  
1.222     foxr     15796: #   Escapes the last element of a full URL.
                   15797: sub escape_url {
                   15798:     my ($url)   = @_;
1.238     raeburn  15799:     my @urlslices = split(/\//, $url,-1);
1.369     www      15800:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15801:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15802: }
1.462     albertel 15803: 
1.820     raeburn  15804: sub compare_arrays {
                   15805:     my ($arrayref1,$arrayref2) = @_;
                   15806:     my (@difference,%count);
                   15807:     @difference = ();
                   15808:     %count = ();
                   15809:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15810:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15811:         foreach my $element (keys(%count)) {
                   15812:             if ($count{$element} == 1) {
                   15813:                 push(@difference,$element);
                   15814:             }
                   15815:         }
                   15816:     }
                   15817:     return @difference;
                   15818: }
                   15819: 
1.817     bisitz   15820: # -------------------------------------------------------- Initialize user login
1.462     albertel 15821: sub init_user_environment {
1.463     albertel 15822:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15823:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15824: 
                   15825:     my $public=($username eq 'public' && $domain eq 'public');
                   15826: 
                   15827: # See if old ID present, if so, remove
                   15828: 
1.1062    raeburn  15829:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15830:     my $now=time;
                   15831: 
                   15832:     if ($public) {
                   15833: 	my $max_public=100;
                   15834: 	my $oldest;
                   15835: 	my $oldest_time=0;
                   15836: 	for(my $next=1;$next<=$max_public;$next++) {
                   15837: 	    if (-e $lonids."/publicuser_$next.id") {
                   15838: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15839: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15840: 		    $oldest_time=$mtime;
                   15841: 		    $oldest=$next;
                   15842: 		}
                   15843: 	    } else {
                   15844: 		$cookie="publicuser_$next";
                   15845: 		last;
                   15846: 	    }
                   15847: 	}
                   15848: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15849:     } else {
1.463     albertel 15850: 	# if this isn't a robot, kill any existing non-robot sessions
                   15851: 	if (!$args->{'robot'}) {
                   15852: 	    opendir(DIR,$lonids);
                   15853: 	    while ($filename=readdir(DIR)) {
                   15854: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15855:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15856:                             &GDBM_READER(),0640)) {
                   15857:                         my $linkedfile;
                   15858:                         if (exists($oldenv{'user.linkedenv'})) {
                   15859:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15860:                         }
                   15861:                         untie(%oldenv);
                   15862:                         if (unlink("$lonids/$filename")) {
                   15863:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15864:                                 if (-l "$lonids/$linkedfile.id") {
                   15865:                                     unlink("$lonids/$linkedfile.id");
                   15866:                                 }
                   15867:                             }
                   15868:                         }
                   15869:                     } else {
                   15870:                         unlink($lonids.'/'.$filename);
                   15871:                     }
1.463     albertel 15872: 		}
1.462     albertel 15873: 	    }
1.463     albertel 15874: 	    closedir(DIR);
1.1075.2.84  raeburn  15875: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15876:             my $namespace = 'nohist_courseeditor';
                   15877:             my $lockingkey = 'paste'."\0".'locked_num';
                   15878:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15879:                                                 $domain,$username);
                   15880:             if (exists($lockhash{$lockingkey})) {
                   15881:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15882:                 unless ($delresult eq 'ok') {
                   15883:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15884:                 }
                   15885:             }
1.462     albertel 15886: 	}
                   15887: # Give them a new cookie
1.463     albertel 15888: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15889: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15890: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15891:     
                   15892: # Initialize roles
                   15893: 
1.1062    raeburn  15894: 	($userroles,$firstaccenv,$timerintenv) = 
                   15895:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15896:     }
                   15897: # ------------------------------------ Check browser type and MathML capability
                   15898: 
1.1075.2.77  raeburn  15899:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15900:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15901: 
                   15902: # ------------------------------------------------------------- Get environment
                   15903: 
                   15904:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15905:     my ($tmp) = keys(%userenv);
                   15906:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15907:     } else {
                   15908: 	undef(%userenv);
                   15909:     }
                   15910:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15911: 	$form->{'interface'}=$userenv{'interface'};
                   15912:     }
                   15913:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15914: 
                   15915: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15916:     foreach my $option ('interface','localpath','localres') {
                   15917:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15918:     }
                   15919: # --------------------------------------------------------- Write first profile
                   15920: 
                   15921:     {
                   15922: 	my %initial_env = 
                   15923: 	    ("user.name"          => $username,
                   15924: 	     "user.domain"        => $domain,
                   15925: 	     "user.home"          => $authhost,
                   15926: 	     "browser.type"       => $clientbrowser,
                   15927: 	     "browser.version"    => $clientversion,
                   15928: 	     "browser.mathml"     => $clientmathml,
                   15929: 	     "browser.unicode"    => $clientunicode,
                   15930: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15931:              "browser.mobile"     => $clientmobile,
                   15932:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15933:              "browser.osversion"  => $clientosversion,
1.462     albertel 15934: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15935: 	     "request.course.fn"  => '',
                   15936: 	     "request.course.uri" => '',
                   15937: 	     "request.course.sec" => '',
                   15938: 	     "request.role"       => 'cm',
                   15939: 	     "request.role.adv"   => $env{'user.adv'},
                   15940: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15941: 
                   15942:         if ($form->{'localpath'}) {
                   15943: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15944: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15945:         }
                   15946: 	
                   15947: 	if ($form->{'interface'}) {
                   15948: 	    $form->{'interface'}=~s/\W//gs;
                   15949: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15950: 	    $env{'browser.interface'}=$form->{'interface'};
                   15951: 	}
                   15952: 
1.1075.2.54  raeburn  15953:         if ($form->{'iptoken'}) {
                   15954:             my $lonhost = $r->dir_config('lonHostID');
                   15955:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15956:             $env{'user.noloadbalance'} = $lonhost;
                   15957:         }
                   15958: 
1.1075.2.120  raeburn  15959:         if ($form->{'noloadbalance'}) {
                   15960:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15961:             my $hosthere = $form->{'noloadbalance'};
                   15962:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15963:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15964:                 $env{'user.noloadbalance'} = $hosthere;
                   15965:             }
                   15966:         }
                   15967: 
1.1016    raeburn  15968:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15969:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15970:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15971: 
1.1075.2.125  raeburn  15972:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15973:                 $userenv{'availabletools.'.$tool} = 
                   15974:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15975:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15976:             }
1.724     raeburn  15977: 
1.1075.2.125  raeburn  15978:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15979:                 $userenv{'canrequest.'.$crstype} =
                   15980:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15981:                                                       'reload','requestcourses',
                   15982:                                                       \%userenv,\%domdef,\%is_adv);
                   15983:             }
1.765     raeburn  15984: 
1.1075.2.125  raeburn  15985:             $userenv{'canrequest.author'} =
                   15986:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15987:                                                   'reload','requestauthor',
                   15988:                                                   \%userenv,\%domdef,\%is_adv);
                   15989:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15990:                                                  $domain,$username);
                   15991:             my $reqstatus = $reqauthor{'author_status'};
                   15992:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15993:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15994:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15995:                                                       $reqauthor{'author'}{'timestamp'};
                   15996:                 }
1.1075.2.14  raeburn  15997:             }
                   15998:         }
                   15999: 
1.462     albertel 16000: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16001: 
1.462     albertel 16002: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16003: 		 &GDBM_WRCREAT(),0640)) {
                   16004: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16005: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16006: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16007:             if (ref($firstaccenv) eq 'HASH') {
                   16008:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16009:             }
                   16010:             if (ref($timerintenv) eq 'HASH') {
                   16011:                 &_add_to_env(\%disk_env,$timerintenv);
                   16012:             }
1.463     albertel 16013: 	    if (ref($args->{'extra_env'})) {
                   16014: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16015: 	    }
1.462     albertel 16016: 	    untie(%disk_env);
                   16017: 	} else {
1.705     tempelho 16018: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16019: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16020: 	    return 'error: '.$!;
                   16021: 	}
                   16022:     }
                   16023:     $env{'request.role'}='cm';
                   16024:     $env{'request.role.adv'}=$env{'user.adv'};
                   16025:     $env{'browser.type'}=$clientbrowser;
                   16026: 
                   16027:     return $cookie;
                   16028: 
                   16029: }
                   16030: 
                   16031: sub _add_to_env {
                   16032:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16033:     if (ref($env_data) eq 'HASH') {
                   16034:         while (my ($key,$value) = each(%$env_data)) {
                   16035: 	    $idf->{$prefix.$key} = $value;
                   16036: 	    $env{$prefix.$key}   = $value;
                   16037:         }
1.462     albertel 16038:     }
                   16039: }
                   16040: 
1.685     tempelho 16041: # --- Get the symbolic name of a problem and the url
                   16042: sub get_symb {
                   16043:     my ($request,$silent) = @_;
1.726     raeburn  16044:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16045:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16046:     if ($symb eq '') {
                   16047:         if (!$silent) {
1.1071    raeburn  16048:             if (ref($request)) { 
                   16049:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16050:             }
1.685     tempelho 16051:             return ();
                   16052:         }
                   16053:     }
                   16054:     &Apache::lonenc::check_decrypt(\$symb);
                   16055:     return ($symb);
                   16056: }
                   16057: 
                   16058: # --------------------------------------------------------------Get annotation
                   16059: 
                   16060: sub get_annotation {
                   16061:     my ($symb,$enc) = @_;
                   16062: 
                   16063:     my $key = $symb;
                   16064:     if (!$enc) {
                   16065:         $key =
                   16066:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16067:     }
                   16068:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16069:     return $annotation{$key};
                   16070: }
                   16071: 
                   16072: sub clean_symb {
1.731     raeburn  16073:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16074: 
                   16075:     &Apache::lonenc::check_decrypt(\$symb);
                   16076:     my $enc = $env{'request.enc'};
1.731     raeburn  16077:     if ($delete_enc) {
1.730     raeburn  16078:         delete($env{'request.enc'});
                   16079:     }
1.685     tempelho 16080: 
                   16081:     return ($symb,$enc);
                   16082: }
1.462     albertel 16083: 
1.1075.2.69  raeburn  16084: ############################################################
                   16085: ############################################################
                   16086: 
                   16087: =pod
                   16088: 
                   16089: =head1 Routines for building display used to search for courses
                   16090: 
                   16091: 
                   16092: =over 4
                   16093: 
                   16094: =item * &build_filters()
                   16095: 
                   16096: Create markup for a table used to set filters to use when selecting
                   16097: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16098: and quotacheck.pl
                   16099: 
                   16100: 
                   16101: Inputs:
                   16102: 
                   16103: filterlist - anonymous array of fields to include as potential filters
                   16104: 
                   16105: crstype - course type
                   16106: 
                   16107: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16108:               to pop-open a course selector (will contain "extra element").
                   16109: 
                   16110: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16111: 
                   16112: filter - anonymous hash of criteria and their values
                   16113: 
                   16114: action - form action
                   16115: 
                   16116: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16117: 
                   16118: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16119: 
                   16120: cloneruname - username of owner of new course who wants to clone
                   16121: 
                   16122: clonerudom - domain of owner of new course who wants to clone
                   16123: 
                   16124: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16125: 
                   16126: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16127: 
                   16128: codedom - domain
                   16129: 
                   16130: formname - value of form element named "form".
                   16131: 
                   16132: fixeddom - domain, if fixed.
                   16133: 
                   16134: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16135: 
                   16136: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16137: 
                   16138: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16139: 
                   16140: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16141: 
                   16142: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16143: 
                   16144: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16145: 
                   16146: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16147: 
                   16148: 
                   16149: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16150: 
                   16151: 
                   16152: Side Effects: None
                   16153: 
                   16154: =cut
                   16155: 
                   16156: # ---------------------------------------------- search for courses based on last activity etc.
                   16157: 
                   16158: sub build_filters {
                   16159:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16160:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16161:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16162:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16163:         $clonetext,$clonewarning) = @_;
                   16164:     my ($list,$jscript);
                   16165:     my $onchange = 'javascript:updateFilters(this)';
                   16166:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16167:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16168:         $typeselectform,$instcodetitle);
                   16169:     if ($formname eq '') {
                   16170:         $formname = $caller;
                   16171:     }
                   16172:     foreach my $item (@{$filterlist}) {
                   16173:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16174:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16175:             if ($item eq 'domainfilter') {
                   16176:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16177:             } elsif ($item eq 'coursefilter') {
                   16178:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16179:             } elsif ($item eq 'ownerfilter') {
                   16180:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16181:             } elsif ($item eq 'ownerdomfilter') {
                   16182:                 $filter->{'ownerdomfilter'} =
                   16183:                     &LONCAPA::clean_domain($filter->{$item});
                   16184:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16185:                                                        'ownerdomfilter',1);
                   16186:             } elsif ($item eq 'personfilter') {
                   16187:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16188:             } elsif ($item eq 'persondomfilter') {
                   16189:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16190:                                                         'persondomfilter',1);
                   16191:             } else {
                   16192:                 $filter->{$item} =~ s/\W//g;
                   16193:             }
                   16194:             if (!$filter->{$item}) {
                   16195:                 $filter->{$item} = '';
                   16196:             }
                   16197:         }
                   16198:         if ($item eq 'domainfilter') {
                   16199:             my $allow_blank = 1;
                   16200:             if ($formname eq 'portform') {
                   16201:                 $allow_blank=0;
                   16202:             } elsif ($formname eq 'studentform') {
                   16203:                 $allow_blank=0;
                   16204:             }
                   16205:             if ($fixeddom) {
                   16206:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16207:                                     ' value="'.$codedom.'" />'.
                   16208:                                     &Apache::lonnet::domain($codedom,'description');
                   16209:             } else {
                   16210:                 $domainselectform = &select_dom_form($filter->{$item},
                   16211:                                                      'domainfilter',
                   16212:                                                       $allow_blank,'',$onchange);
                   16213:             }
                   16214:         } else {
                   16215:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16216:         }
                   16217:     }
                   16218: 
                   16219:     # last course activity filter and selection
                   16220:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16221: 
                   16222:     # course created filter and selection
                   16223:     if (exists($filter->{'createdfilter'})) {
                   16224:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16225:     }
                   16226: 
                   16227:     my %lt = &Apache::lonlocal::texthash(
                   16228:                 'cac' => "$crstype Activity",
                   16229:                 'ccr' => "$crstype Created",
                   16230:                 'cde' => "$crstype Title",
                   16231:                 'cdo' => "$crstype Domain",
                   16232:                 'ins' => 'Institutional Code',
                   16233:                 'inc' => 'Institutional Categorization',
                   16234:                 'cow' => "$crstype Owner/Co-owner",
                   16235:                 'cop' => "$crstype Personnel Includes",
                   16236:                 'cog' => 'Type',
                   16237:              );
                   16238: 
                   16239:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16240:         my $typeval = 'Course';
                   16241:         if ($crstype eq 'Community') {
                   16242:             $typeval = 'Community';
                   16243:         }
                   16244:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16245:     } else {
                   16246:         $typeselectform =  '<select name="type" size="1"';
                   16247:         if ($onchange) {
                   16248:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16249:         }
                   16250:         $typeselectform .= '>'."\n";
                   16251:         foreach my $posstype ('Course','Community') {
                   16252:             $typeselectform.='<option value="'.$posstype.'"'.
                   16253:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16254:         }
                   16255:         $typeselectform.="</select>";
                   16256:     }
                   16257: 
                   16258:     my ($cloneableonlyform,$cloneabletitle);
                   16259:     if (exists($filter->{'cloneableonly'})) {
                   16260:         my $cloneableon = '';
                   16261:         my $cloneableoff = ' checked="checked"';
                   16262:         if ($filter->{'cloneableonly'}) {
                   16263:             $cloneableon = $cloneableoff;
                   16264:             $cloneableoff = '';
                   16265:         }
                   16266:         $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>';
                   16267:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16268:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16269:         } else {
                   16270:             $cloneabletitle = &mt('Cloneable by you');
                   16271:         }
                   16272:     }
                   16273:     my $officialjs;
                   16274:     if ($crstype eq 'Course') {
                   16275:         if (exists($filter->{'instcodefilter'})) {
                   16276: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16277: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16278:             if ($codedom) {
                   16279:                 $officialjs = 1;
                   16280:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16281:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16282:                                                                   $officialjs,$codetitlesref);
                   16283:                 if ($jscript) {
                   16284:                     $jscript = '<script type="text/javascript">'."\n".
                   16285:                                '// <![CDATA['."\n".
                   16286:                                $jscript."\n".
                   16287:                                '// ]]>'."\n".
                   16288:                                '</script>'."\n";
                   16289:                 }
                   16290:             }
                   16291:             if ($instcodeform eq '') {
                   16292:                 $instcodeform =
                   16293:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16294:                     $list->{'instcodefilter'}.'" />';
                   16295:                 $instcodetitle = $lt{'ins'};
                   16296:             } else {
                   16297:                 $instcodetitle = $lt{'inc'};
                   16298:             }
                   16299:             if ($fixeddom) {
                   16300:                 $instcodetitle .= '<br />('.$codedom.')';
                   16301:             }
                   16302:         }
                   16303:     }
                   16304:     my $output = qq|
                   16305: <form method="post" name="filterpicker" action="$action">
                   16306: <input type="hidden" name="form" value="$formname" />
                   16307: |;
                   16308:     if ($formname eq 'modifycourse') {
                   16309:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16310:                    '<input type="hidden" name="prevphase" value="'.
                   16311:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16312:     } elsif ($formname eq 'quotacheck') {
                   16313:         $output .= qq|
                   16314: <input type="hidden" name="sortby" value="" />
                   16315: <input type="hidden" name="sortorder" value="" />
                   16316: |;
                   16317:     } else {
1.1075.2.69  raeburn  16318:         my $name_input;
                   16319:         if ($cnameelement ne '') {
                   16320:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16321:                           $cnameelement.'" />';
                   16322:         }
                   16323:         $output .= qq|
                   16324: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16325: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16326: $name_input
                   16327: $roleelement
                   16328: $multelement
                   16329: $typeelement
                   16330: |;
                   16331:         if ($formname eq 'portform') {
                   16332:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16333:         }
                   16334:     }
                   16335:     if ($fixeddom) {
                   16336:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16337:     }
                   16338:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16339:     if ($sincefilterform) {
                   16340:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16341:                   .$sincefilterform
                   16342:                   .&Apache::lonhtmlcommon::row_closure();
                   16343:     }
                   16344:     if ($createdfilterform) {
                   16345:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16346:                   .$createdfilterform
                   16347:                   .&Apache::lonhtmlcommon::row_closure();
                   16348:     }
                   16349:     if ($domainselectform) {
                   16350:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16351:                   .$domainselectform
                   16352:                   .&Apache::lonhtmlcommon::row_closure();
                   16353:     }
                   16354:     if ($typeselectform) {
                   16355:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16356:             $output .= $typeselectform;
                   16357:         } else {
                   16358:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16359:                       .$typeselectform
                   16360:                       .&Apache::lonhtmlcommon::row_closure();
                   16361:         }
                   16362:     }
                   16363:     if ($instcodeform) {
                   16364:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16365:                   .$instcodeform
                   16366:                   .&Apache::lonhtmlcommon::row_closure();
                   16367:     }
                   16368:     if (exists($filter->{'ownerfilter'})) {
                   16369:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16370:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16371:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16372:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16373:                    $ownerdomselectform.'</td></tr></table>'.
                   16374:                    &Apache::lonhtmlcommon::row_closure();
                   16375:     }
                   16376:     if (exists($filter->{'personfilter'})) {
                   16377:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16378:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16379:                    '<input type="text" name="personfilter" size="20" value="'.
                   16380:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16381:                    $persondomselectform.'</td></tr></table>'.
                   16382:                    &Apache::lonhtmlcommon::row_closure();
                   16383:     }
                   16384:     if (exists($filter->{'coursefilter'})) {
                   16385:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16386:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16387:                   .$list->{'coursefilter'}.'" />'
                   16388:                   .&Apache::lonhtmlcommon::row_closure();
                   16389:     }
                   16390:     if ($cloneableonlyform) {
                   16391:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16392:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16393:     }
                   16394:     if (exists($filter->{'descriptfilter'})) {
                   16395:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16396:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16397:                   .$list->{'descriptfilter'}.'" />'
                   16398:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16399:     }
                   16400:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16401:                '<input type="hidden" name="updater" value="" />'."\n".
                   16402:                '<input type="submit" name="gosearch" value="'.
                   16403:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16404:     return $jscript.$clonewarning.$output;
                   16405: }
                   16406: 
                   16407: =pod
                   16408: 
                   16409: =item * &timebased_select_form()
                   16410: 
                   16411: Create markup for a dropdown list used to select a time-based
                   16412: filter e.g., Course Activity, Course Created, when searching for courses
                   16413: or communities
                   16414: 
                   16415: Inputs:
                   16416: 
                   16417: item - name of form element (sincefilter or createdfilter)
                   16418: 
                   16419: filter - anonymous hash of criteria and their values
                   16420: 
                   16421: Returns: HTML for a select box contained a blank, then six time selections,
                   16422:          with value set in incoming form variables currently selected.
                   16423: 
                   16424: Side Effects: None
                   16425: 
                   16426: =cut
                   16427: 
                   16428: sub timebased_select_form {
                   16429:     my ($item,$filter) = @_;
                   16430:     if (ref($filter) eq 'HASH') {
                   16431:         $filter->{$item} =~ s/[^\d-]//g;
                   16432:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16433:         return &select_form(
                   16434:                             $filter->{$item},
                   16435:                             $item,
                   16436:                             {      '-1' => '',
                   16437:                                 '86400' => &mt('today'),
                   16438:                                '604800' => &mt('last week'),
                   16439:                               '2592000' => &mt('last month'),
                   16440:                               '7776000' => &mt('last three months'),
                   16441:                              '15552000' => &mt('last six months'),
                   16442:                              '31104000' => &mt('last year'),
                   16443:                     'select_form_order' =>
                   16444:                            ['-1','86400','604800','2592000','7776000',
                   16445:                             '15552000','31104000']});
                   16446:     }
                   16447: }
                   16448: 
                   16449: =pod
                   16450: 
                   16451: =item * &js_changer()
                   16452: 
                   16453: Create script tag containing Javascript used to submit course search form
                   16454: when course type or domain is changed, and also to hide 'Searching ...' on
                   16455: page load completion for page showing search result.
                   16456: 
                   16457: Inputs: None
                   16458: 
                   16459: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16460: 
                   16461: Side Effects: None
                   16462: 
                   16463: =cut
                   16464: 
                   16465: sub js_changer {
                   16466:     return <<ENDJS;
                   16467: <script type="text/javascript">
                   16468: // <![CDATA[
                   16469: function updateFilters(caller) {
                   16470:     if (typeof(caller) != "undefined") {
                   16471:         document.filterpicker.updater.value = caller.name;
                   16472:     }
                   16473:     document.filterpicker.submit();
                   16474: }
                   16475: 
                   16476: function hideSearching() {
                   16477:     if (document.getElementById('searching')) {
                   16478:         document.getElementById('searching').style.display = 'none';
                   16479:     }
                   16480:     return;
                   16481: }
                   16482: 
                   16483: // ]]>
                   16484: </script>
                   16485: 
                   16486: ENDJS
                   16487: }
                   16488: 
                   16489: =pod
                   16490: 
                   16491: =item * &search_courses()
                   16492: 
                   16493: Process selected filters form course search form and pass to lonnet::courseiddump
                   16494: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16495: 
                   16496: Inputs:
                   16497: 
                   16498: dom - domain being searched
                   16499: 
                   16500: type - course type ('Course' or 'Community' or '.' if any).
                   16501: 
                   16502: filter - anonymous hash of criteria and their values
                   16503: 
                   16504: numtitles - for institutional codes - number of categories
                   16505: 
                   16506: cloneruname - optional username of new course owner
                   16507: 
                   16508: clonerudom - optional domain of new course owner
                   16509: 
1.1075.2.95  raeburn  16510: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16511:             (used when DC is using course creation form)
                   16512: 
                   16513: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16514: 
1.1075.2.95  raeburn  16515: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16516:            (and so can clone automatically)
                   16517: 
                   16518: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16519: 
                   16520: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16521:               courses to clone
1.1075.2.69  raeburn  16522: 
                   16523: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16524: 
                   16525: 
                   16526: Side Effects: None
                   16527: 
                   16528: =cut
                   16529: 
                   16530: 
                   16531: sub search_courses {
1.1075.2.95  raeburn  16532:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16533:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16534:     my (%courses,%showcourses,$cloner);
                   16535:     if (($filter->{'ownerfilter'} ne '') ||
                   16536:         ($filter->{'ownerdomfilter'} ne '')) {
                   16537:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16538:                                        $filter->{'ownerdomfilter'};
                   16539:     }
                   16540:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16541:         if (!$filter->{$item}) {
                   16542:             $filter->{$item}='.';
                   16543:         }
                   16544:     }
                   16545:     my $now = time;
                   16546:     my $timefilter =
                   16547:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16548:     my ($createdbefore,$createdafter);
                   16549:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16550:         $createdbefore = $now;
                   16551:         $createdafter = $now-$filter->{'createdfilter'};
                   16552:     }
                   16553:     my ($instcodefilter,$regexpok);
                   16554:     if ($numtitles) {
                   16555:         if ($env{'form.official'} eq 'on') {
                   16556:             $instcodefilter =
                   16557:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16558:             $regexpok = 1;
                   16559:         } elsif ($env{'form.official'} eq 'off') {
                   16560:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16561:             unless ($instcodefilter eq '') {
                   16562:                 $regexpok = -1;
                   16563:             }
                   16564:         }
                   16565:     } else {
                   16566:         $instcodefilter = $filter->{'instcodefilter'};
                   16567:     }
                   16568:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16569:     if ($type eq '') { $type = '.'; }
                   16570: 
                   16571:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16572:         $cloner = $cloneruname.':'.$clonerudom;
                   16573:     }
                   16574:     %courses = &Apache::lonnet::courseiddump($dom,
                   16575:                                              $filter->{'descriptfilter'},
                   16576:                                              $timefilter,
                   16577:                                              $instcodefilter,
                   16578:                                              $filter->{'combownerfilter'},
                   16579:                                              $filter->{'coursefilter'},
                   16580:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16581:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16582:                                              $filter->{'cloneableonly'},
                   16583:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16584:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16585:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16586:         my $ccrole;
                   16587:         if ($type eq 'Community') {
                   16588:             $ccrole = 'co';
                   16589:         } else {
                   16590:             $ccrole = 'cc';
                   16591:         }
                   16592:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16593:                                                      $filter->{'persondomfilter'},
                   16594:                                                      'userroles',undef,
                   16595:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16596:                                                      $dom);
                   16597:         foreach my $role (keys(%rolehash)) {
                   16598:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16599:             my $cid = $cdom.'_'.$cnum;
                   16600:             if (exists($courses{$cid})) {
                   16601:                 if (ref($courses{$cid}) eq 'HASH') {
                   16602:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16603:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16604:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16605:                         }
                   16606:                     } else {
                   16607:                         $courses{$cid}{roles} = [$courserole];
                   16608:                     }
                   16609:                     $showcourses{$cid} = $courses{$cid};
                   16610:                 }
                   16611:             }
                   16612:         }
                   16613:         %courses = %showcourses;
                   16614:     }
                   16615:     return %courses;
                   16616: }
                   16617: 
                   16618: =pod
                   16619: 
                   16620: =back
                   16621: 
1.1075.2.88  raeburn  16622: =head1 Routines for version requirements for current course.
                   16623: 
                   16624: =over 4
                   16625: 
                   16626: =item * &check_release_required()
                   16627: 
                   16628: Compares required LON-CAPA version with version on server, and
                   16629: if required version is newer looks for a server with the required version.
                   16630: 
                   16631: Looks first at servers in user's owen domain; if none suitable, looks at
                   16632: servers in course's domain are permitted to host sessions for user's domain.
                   16633: 
                   16634: Inputs:
                   16635: 
                   16636: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16637: 
                   16638: $courseid - Course ID of current course
                   16639: 
                   16640: $rolecode - User's current role in course (for switchserver query string).
                   16641: 
                   16642: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16643: 
                   16644: 
                   16645: Returns:
                   16646: 
                   16647: $switchserver - query string tp append to /adm/switchserver call (if
                   16648:                 current server's LON-CAPA version is too old.
                   16649: 
                   16650: $warning - Message is displayed if no suitable server could be found.
                   16651: 
                   16652: =cut
                   16653: 
                   16654: sub check_release_required {
                   16655:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16656:     my ($switchserver,$warning);
                   16657:     if ($required ne '') {
                   16658:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16659:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16660:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16661:             my $otherserver;
                   16662:             if (($major eq '' && $minor eq '') ||
                   16663:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16664:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16665:                 my $switchlcrev =
                   16666:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16667:                                                            $userdomserver);
                   16668:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16669:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16670:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16671:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16672:                     if ($cdom ne $env{'user.domain'}) {
                   16673:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16674:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16675:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16676:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16677:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16678:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16679:                         my $canhost =
                   16680:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16681:                                                               $coursedomserver,
                   16682:                                                               $remoterev,
                   16683:                                                               $udomdefaults{'remotesessions'},
                   16684:                                                               $defdomdefaults{'hostedsessions'});
                   16685: 
                   16686:                         if ($canhost) {
                   16687:                             $otherserver = $coursedomserver;
                   16688:                         } else {
                   16689:                             $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.");
                   16690:                         }
                   16691:                     } else {
                   16692:                         $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).");
                   16693:                     }
                   16694:                 } else {
                   16695:                     $otherserver = $userdomserver;
                   16696:                 }
                   16697:             }
                   16698:             if ($otherserver ne '') {
                   16699:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16700:             }
                   16701:         }
                   16702:     }
                   16703:     return ($switchserver,$warning);
                   16704: }
                   16705: 
                   16706: =pod
                   16707: 
                   16708: =item * &check_release_result()
                   16709: 
                   16710: Inputs:
                   16711: 
                   16712: $switchwarning - Warning message if no suitable server found to host session.
                   16713: 
                   16714: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16715:                 and current role.
                   16716: 
                   16717: Returns: HTML to display with information about requirement to switch server.
                   16718:          Either displaying warning with link to Roles/Courses screen or
                   16719:          display link to switchserver.
                   16720: 
1.1075.2.69  raeburn  16721: =cut
                   16722: 
1.1075.2.88  raeburn  16723: sub check_release_result {
                   16724:     my ($switchwarning,$switchserver) = @_;
                   16725:     my $output = &start_page('Selected course unavailable on this server').
                   16726:                  '<p class="LC_warning">';
                   16727:     if ($switchwarning) {
                   16728:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16729:         if (&show_course()) {
                   16730:             $output .= &mt('Display courses');
                   16731:         } else {
                   16732:             $output .= &mt('Display roles');
                   16733:         }
                   16734:         $output .= '</a>';
                   16735:     } elsif ($switchserver) {
                   16736:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16737:                    '<br />'.
                   16738:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16739:                    &mt('Switch Server').
                   16740:                    '</a>';
                   16741:     }
                   16742:     $output .= '</p>'.&end_page();
                   16743:     return $output;
                   16744: }
                   16745: 
                   16746: =pod
                   16747: 
                   16748: =item * &needs_coursereinit()
                   16749: 
                   16750: Determine if course contents stored for user's session needs to be
                   16751: refreshed, because content has changed since "Big Hash" last tied.
                   16752: 
                   16753: Check for change is made if time last checked is more than 10 minutes ago
                   16754: (by default).
                   16755: 
                   16756: Inputs:
                   16757: 
                   16758: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16759: 
                   16760: $interval (optional) - Time which may elapse (in s) between last check for content
                   16761:                        change in current course. (default: 600 s).
                   16762: 
                   16763: Returns: an array; first element is:
                   16764: 
                   16765: =over 4
                   16766: 
                   16767: 'switch' - if content updates mean user's session
                   16768:            needs to be switched to a server running a newer LON-CAPA version
                   16769: 
                   16770: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16771:            on current server hosting user's session
                   16772: 
                   16773: ''       - if no action required.
                   16774: 
                   16775: =back
                   16776: 
                   16777: If first item element is 'switch':
                   16778: 
                   16779: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16780: 
                   16781: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16782:                               and current role.
                   16783: 
                   16784: otherwise: no other elements returned.
                   16785: 
                   16786: =back
                   16787: 
                   16788: =cut
                   16789: 
                   16790: sub needs_coursereinit {
                   16791:     my ($loncaparev,$interval) = @_;
                   16792:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16793:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16794:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16795:     my $now = time;
                   16796:     if ($interval eq '') {
                   16797:         $interval = 600;
                   16798:     }
                   16799:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16800:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.141.  .6(raebu 16801:20):         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
                   16802:20):         if ($blocked) {
                   16803:20):             return ();
                   16804:20):         }
                   16805:20):         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
1.1075.2.88  raeburn  16806:         if ($lastchange > $env{'request.course.tied'}) {
                   16807:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16808:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16809:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16810:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16811:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16812:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16813:                     my ($switchserver,$switchwarning) =
                   16814:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16815:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16816:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16817:                         return ('switch',$switchwarning,$switchserver);
                   16818:                     }
                   16819:                 }
                   16820:             }
                   16821:             return ('update');
                   16822:         }
                   16823:     }
                   16824:     return ();
                   16825: }
1.1075.2.69  raeburn  16826: 
1.1075.2.11  raeburn  16827: sub update_content_constraints {
                   16828:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16829:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16830:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16831:     my %checkresponsetypes;
                   16832:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16833:         my ($item,$name,$value) = split(/:/,$key);
                   16834:         if ($item eq 'resourcetag') {
                   16835:             if ($name eq 'responsetype') {
                   16836:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16837:             }
                   16838:         }
                   16839:     }
                   16840:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16841:     if (defined($navmap)) {
                   16842:         my %allresponses;
                   16843:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16844:             my %responses = $res->responseTypes();
                   16845:             foreach my $key (keys(%responses)) {
                   16846:                 next unless(exists($checkresponsetypes{$key}));
                   16847:                 $allresponses{$key} += $responses{$key};
                   16848:             }
                   16849:         }
                   16850:         foreach my $key (keys(%allresponses)) {
                   16851:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16852:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16853:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16854:             }
                   16855:         }
                   16856:         undef($navmap);
                   16857:     }
                   16858:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16859:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16860:     }
                   16861:     return;
                   16862: }
                   16863: 
1.1075.2.27  raeburn  16864: sub allmaps_incourse {
                   16865:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16866:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16867:         $cid = $env{'request.course.id'};
                   16868:         $cdom = $env{'course.'.$cid.'.domain'};
                   16869:         $cnum = $env{'course.'.$cid.'.num'};
                   16870:         $chome = $env{'course.'.$cid.'.home'};
                   16871:     }
                   16872:     my %allmaps = ();
                   16873:     my $lastchange =
                   16874:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16875:     if ($lastchange > $env{'request.course.tied'}) {
                   16876:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16877:         unless ($ferr) {
                   16878:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16879:         }
                   16880:     }
                   16881:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16882:     if (defined($navmap)) {
                   16883:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16884:             $allmaps{$res->src()} = 1;
                   16885:         }
                   16886:     }
                   16887:     return \%allmaps;
                   16888: }
                   16889: 
1.1075.2.11  raeburn  16890: sub parse_supplemental_title {
                   16891:     my ($title) = @_;
                   16892: 
                   16893:     my ($foldertitle,$renametitle);
                   16894:     if ($title =~ /&amp;&amp;&amp;/) {
                   16895:         $title = &HTML::Entites::decode($title);
                   16896:     }
                   16897:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16898:         $renametitle=$4;
                   16899:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16900:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16901:         my $name =  &plainname($uname,$udom);
                   16902:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16903:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16904:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16905:             $name.': <br />'.$foldertitle;
                   16906:     }
                   16907:     if (wantarray) {
                   16908:         return ($title,$foldertitle,$renametitle);
                   16909:     }
                   16910:     return $title;
                   16911: }
                   16912: 
1.1075.2.43  raeburn  16913: sub recurse_supplemental {
                   16914:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16915:     if ($suppmap) {
                   16916:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16917:         if ($fatal) {
                   16918:             $errors ++;
                   16919:         } else {
                   16920:             if ($#LONCAPA::map::resources > 0) {
                   16921:                 foreach my $res (@LONCAPA::map::resources) {
                   16922:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16923:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16924:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16925:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16926:                         } else {
                   16927:                             $numfiles ++;
                   16928:                         }
                   16929:                     }
                   16930:                 }
                   16931:             }
                   16932:         }
                   16933:     }
                   16934:     return ($numfiles,$errors);
                   16935: }
                   16936: 
1.1075.2.18  raeburn  16937: sub symb_to_docspath {
1.1075.2.119  raeburn  16938:     my ($symb,$navmapref) = @_;
                   16939:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16940:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16941:     if ($resurl=~/\.(sequence|page)$/) {
                   16942:         $mapurl=$resurl;
                   16943:     } elsif ($resurl eq 'adm/navmaps') {
                   16944:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16945:     }
                   16946:     my $mapresobj;
1.1075.2.119  raeburn  16947:     unless (ref($$navmapref)) {
                   16948:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16949:     }
                   16950:     if (ref($$navmapref)) {
                   16951:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16952:     }
                   16953:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16954:     my $type=$2;
                   16955:     my $path;
                   16956:     if (ref($mapresobj)) {
                   16957:         my $pcslist = $mapresobj->map_hierarchy();
                   16958:         if ($pcslist ne '') {
                   16959:             foreach my $pc (split(/,/,$pcslist)) {
                   16960:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16961:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16962:                 if (ref($res)) {
                   16963:                     my $thisurl = $res->src();
                   16964:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16965:                     my $thistitle = $res->title();
                   16966:                     $path .= '&'.
                   16967:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16968:                              &escape($thistitle).
1.1075.2.18  raeburn  16969:                              ':'.$res->randompick().
                   16970:                              ':'.$res->randomout().
                   16971:                              ':'.$res->encrypted().
                   16972:                              ':'.$res->randomorder().
                   16973:                              ':'.$res->is_page();
                   16974:                 }
                   16975:             }
                   16976:         }
                   16977:         $path =~ s/^\&//;
                   16978:         my $maptitle = $mapresobj->title();
                   16979:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16980:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16981:         }
                   16982:         $path .= (($path ne '')? '&' : '').
                   16983:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16984:                  &escape($maptitle).
1.1075.2.18  raeburn  16985:                  ':'.$mapresobj->randompick().
                   16986:                  ':'.$mapresobj->randomout().
                   16987:                  ':'.$mapresobj->encrypted().
                   16988:                  ':'.$mapresobj->randomorder().
                   16989:                  ':'.$mapresobj->is_page();
                   16990:     } else {
                   16991:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16992:         my $ispage = (($type eq 'page')? 1 : '');
                   16993:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16994:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16995:         }
                   16996:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16997:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16998:     }
                   16999:     unless ($mapurl eq 'default') {
                   17000:         $path = 'default&'.
1.1075.2.46  raeburn  17001:                 &escape('Main Content').
1.1075.2.18  raeburn  17002:                 ':::::&'.$path;
                   17003:     }
                   17004:     return $path;
                   17005: }
                   17006: 
1.1075.2.14  raeburn  17007: sub captcha_display {
1.1075.2.137  raeburn  17008:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17009:     my ($output,$error);
1.1075.2.107  raeburn  17010:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17011:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17012:     if ($captcha eq 'original') {
                   17013:         $output = &create_captcha();
                   17014:         unless ($output) {
                   17015:             $error = 'captcha';
                   17016:         }
                   17017:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17018:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17019:         unless ($output) {
                   17020:             $error = 'recaptcha';
                   17021:         }
                   17022:     }
1.1075.2.107  raeburn  17023:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17024: }
                   17025: 
                   17026: sub captcha_response {
1.1075.2.137  raeburn  17027:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17028:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17029:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17030:     if ($captcha eq 'original') {
                   17031:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17032:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17033:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17034:     } else {
                   17035:         $captcha_chk = 1;
                   17036:     }
                   17037:     return ($captcha_chk,$captcha_error);
                   17038: }
                   17039: 
                   17040: sub get_captcha_config {
1.1075.2.137  raeburn  17041:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17042:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17043:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17044:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17045:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17046:     if ($context eq 'usercreation') {
                   17047:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17048:         if (ref($domconfig{$context}) eq 'HASH') {
                   17049:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17050:             if (ref($hashtocheck) eq 'HASH') {
                   17051:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17052:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17053:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17054:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17055:                     }
                   17056:                     if ($privkey && $pubkey) {
                   17057:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17058:                         $version = $hashtocheck->{'recaptchaversion'};
                   17059:                         if ($version ne '2') {
                   17060:                             $version = 1;
                   17061:                         }
1.1075.2.14  raeburn  17062:                     } else {
                   17063:                         $captcha = 'original';
                   17064:                     }
                   17065:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17066:                     $captcha = 'original';
                   17067:                 }
                   17068:             }
                   17069:         } else {
                   17070:             $captcha = 'captcha';
                   17071:         }
                   17072:     } elsif ($context eq 'login') {
                   17073:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17074:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17075:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17076:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17077:             if ($privkey && $pubkey) {
                   17078:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17079:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17080:                 if ($version ne '2') {
                   17081:                     $version = 1;
                   17082:                 }
1.1075.2.14  raeburn  17083:             } else {
                   17084:                 $captcha = 'original';
                   17085:             }
                   17086:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17087:             $captcha = 'original';
                   17088:         }
1.1075.2.137  raeburn  17089:     } elsif ($context eq 'passwords') {
                   17090:         if ($dom_in_effect) {
                   17091:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17092:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17093:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17094:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17095:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17096:                 }
                   17097:                 if ($privkey && $pubkey) {
                   17098:                     $captcha = 'recaptcha';
                   17099:                     $version = $passwdconf{'recaptchaversion'};
                   17100:                     if ($version ne '2') {
                   17101:                         $version = 1;
                   17102:                     }
                   17103:                 } else {
                   17104:                     $captcha = 'original';
                   17105:                 }
                   17106:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17107:                 $captcha = 'original';
                   17108:             }
                   17109:         }
1.1075.2.14  raeburn  17110:     }
1.1075.2.107  raeburn  17111:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17112: }
                   17113: 
                   17114: sub create_captcha {
                   17115:     my %captcha_params = &captcha_settings();
                   17116:     my ($output,$maxtries,$tries) = ('',10,0);
                   17117:     while ($tries < $maxtries) {
                   17118:         $tries ++;
                   17119:         my $captcha = Authen::Captcha->new (
                   17120:                                            output_folder => $captcha_params{'output_dir'},
                   17121:                                            data_folder   => $captcha_params{'db_dir'},
                   17122:                                           );
                   17123:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17124: 
                   17125:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17126:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17127:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17128:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17129:                       '<br />'.
                   17130:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17131:             last;
                   17132:         }
                   17133:     }
                   17134:     return $output;
                   17135: }
                   17136: 
                   17137: sub captcha_settings {
                   17138:     my %captcha_params = (
                   17139:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17140:                            www_output_dir => "/captchaspool",
                   17141:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17142:                            numchars       => '5',
                   17143:                          );
                   17144:     return %captcha_params;
                   17145: }
                   17146: 
                   17147: sub check_captcha {
                   17148:     my ($captcha_chk,$captcha_error);
                   17149:     my $code = $env{'form.code'};
                   17150:     my $md5sum = $env{'form.crypt'};
                   17151:     my %captcha_params = &captcha_settings();
                   17152:     my $captcha = Authen::Captcha->new(
                   17153:                       output_folder => $captcha_params{'output_dir'},
                   17154:                       data_folder   => $captcha_params{'db_dir'},
                   17155:                   );
1.1075.2.26  raeburn  17156:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17157:     my %captcha_hash = (
                   17158:                         0       => 'Code not checked (file error)',
                   17159:                        -1      => 'Failed: code expired',
                   17160:                        -2      => 'Failed: invalid code (not in database)',
                   17161:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17162:     );
                   17163:     if ($captcha_chk != 1) {
                   17164:         $captcha_error = $captcha_hash{$captcha_chk}
                   17165:     }
                   17166:     return ($captcha_chk,$captcha_error);
                   17167: }
                   17168: 
                   17169: sub create_recaptcha {
1.1075.2.107  raeburn  17170:     my ($pubkey,$version) = @_;
                   17171:     if ($version >= 2) {
                   17172:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17173:     } else {
                   17174:         my $use_ssl;
                   17175:         if ($ENV{'SERVER_PORT'} == 443) {
                   17176:             $use_ssl = 1;
                   17177:         }
                   17178:         my $captcha = Captcha::reCAPTCHA->new;
                   17179:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17180:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17181:                &mt('If the text is hard to read, [_1] will replace them.',
                   17182:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17183:                '<br /><br />';
                   17184:      }
1.1075.2.14  raeburn  17185: }
                   17186: 
                   17187: sub check_recaptcha {
1.1075.2.107  raeburn  17188:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17189:     my $captcha_chk;
1.1075.2.107  raeburn  17190:     if ($version >= 2) {
                   17191:         my $ua = LWP::UserAgent->new;
                   17192:         $ua->timeout(10);
                   17193:         my %info = (
                   17194:                      secret   => $privkey,
                   17195:                      response => $env{'form.g-recaptcha-response'},
                   17196:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17197:                    );
                   17198:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17199:         if ($response->is_success)  {
                   17200:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17201:             if (ref($data) eq 'HASH') {
                   17202:                 if ($data->{'success'}) {
                   17203:                     $captcha_chk = 1;
                   17204:                 }
                   17205:             }
                   17206:         }
                   17207:     } else {
                   17208:         my $captcha = Captcha::reCAPTCHA->new;
                   17209:         my $captcha_result =
                   17210:             $captcha->check_answer(
                   17211:                                     $privkey,
                   17212:                                     $ENV{'REMOTE_ADDR'},
                   17213:                                     $env{'form.recaptcha_challenge_field'},
                   17214:                                     $env{'form.recaptcha_response_field'},
                   17215:                                   );
                   17216:         if ($captcha_result->{is_valid}) {
                   17217:             $captcha_chk = 1;
                   17218:         }
1.1075.2.14  raeburn  17219:     }
                   17220:     return $captcha_chk;
                   17221: }
                   17222: 
1.1075.2.64  raeburn  17223: sub emailusername_info {
1.1075.2.103  raeburn  17224:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17225:     my %titles = &Apache::lonlocal::texthash (
                   17226:                      lastname      => 'Last Name',
                   17227:                      firstname     => 'First Name',
                   17228:                      institution   => 'School/college/university',
                   17229:                      location      => "School's city, state/province, country",
                   17230:                      web           => "School's web address",
                   17231:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17232:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17233:                  );
                   17234:     return (\@fields,\%titles);
                   17235: }
                   17236: 
1.1075.2.56  raeburn  17237: sub cleanup_html {
                   17238:     my ($incoming) = @_;
                   17239:     my $outgoing;
                   17240:     if ($incoming ne '') {
                   17241:         $outgoing = $incoming;
                   17242:         $outgoing =~ s/;/&#059;/g;
                   17243:         $outgoing =~ s/\#/&#035;/g;
                   17244:         $outgoing =~ s/\&/&#038;/g;
                   17245:         $outgoing =~ s/</&#060;/g;
                   17246:         $outgoing =~ s/>/&#062;/g;
                   17247:         $outgoing =~ s/\(/&#040/g;
                   17248:         $outgoing =~ s/\)/&#041;/g;
                   17249:         $outgoing =~ s/"/&#034;/g;
                   17250:         $outgoing =~ s/'/&#039;/g;
                   17251:         $outgoing =~ s/\$/&#036;/g;
                   17252:         $outgoing =~ s{/}{&#047;}g;
                   17253:         $outgoing =~ s/=/&#061;/g;
                   17254:         $outgoing =~ s/\\/&#092;/g
                   17255:     }
                   17256:     return $outgoing;
                   17257: }
                   17258: 
1.1075.2.74  raeburn  17259: # Checks for critical messages and returns a redirect url if one exists.
                   17260: # $interval indicates how often to check for messages.
1.1075.2.141.  .6(raebu 17261:20): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  17262: sub critical_redirect {
1.1075.2.141.  .6(raebu 17263:20):     my ($interval,$context) = @_;
1.1075.2.74  raeburn  17264:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.141.  .6(raebu 17265:20):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17266:20):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17267:20):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17268:20):             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17269:20):             if ($blocked) {
                   17270:20):                 my $checkrole = "cm./$cdom/$cnum";
                   17271:20):                 if ($env{'request.course.sec'} ne '') {
                   17272:20):                     $checkrole .= "/$env{'request.course.sec'}";
                   17273:20):                 }
                   17274:20):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17275:20):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17276:20):                     return;
                   17277:20):                 }
                   17278:20):             }
                   17279:20):         }
1.1075.2.74  raeburn  17280:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17281:                                         $env{'user.name'});
                   17282:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17283:         my $redirecturl;
                   17284:         if ($what[0]) {
                   17285:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17286:                 $redirecturl='/adm/email?critical=display';
                   17287:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17288:                 return (1, $url);
                   17289:             }
                   17290:         }
                   17291:     }
                   17292:     return ();
                   17293: }
                   17294: 
1.1075.2.64  raeburn  17295: # Use:
                   17296: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17297: #
                   17298: ##################################################
                   17299: #          password associated functions         #
                   17300: ##################################################
                   17301: sub des_keys {
                   17302:     # Make a new key for DES encryption.
                   17303:     # Each key has two parts which are returned separately.
                   17304:     # Please note:  Each key must be passed through the &hex function
                   17305:     # before it is output to the web browser.  The hex versions cannot
                   17306:     # be used to decrypt.
                   17307:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17308:                 '8','9','a','b','c','d','e','f');
                   17309:     my $lkey='';
                   17310:     for (0..7) {
                   17311:         $lkey.=$hexstr[rand(15)];
                   17312:     }
                   17313:     my $ukey='';
                   17314:     for (0..7) {
                   17315:         $ukey.=$hexstr[rand(15)];
                   17316:     }
                   17317:     return ($lkey,$ukey);
                   17318: }
                   17319: 
                   17320: sub des_decrypt {
                   17321:     my ($key,$cyphertext) = @_;
                   17322:     my $keybin=pack("H16",$key);
                   17323:     my $cypher;
                   17324:     if ($Crypt::DES::VERSION>=2.03) {
                   17325:         $cypher=new Crypt::DES $keybin;
                   17326:     } else {
                   17327:         $cypher=new DES $keybin;
                   17328:     }
1.1075.2.106  raeburn  17329:     my $plaintext='';
                   17330:     my $cypherlength = length($cyphertext);
                   17331:     my $numchunks = int($cypherlength/32);
                   17332:     for (my $j=0; $j<$numchunks; $j++) {
                   17333:         my $start = $j*32;
                   17334:         my $cypherblock = substr($cyphertext,$start,32);
                   17335:         my $chunk =
                   17336:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17337:         $chunk .=
                   17338:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17339:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17340:         $plaintext .= $chunk;
                   17341:     }
1.1075.2.64  raeburn  17342:     return $plaintext;
                   17343: }
                   17344: 
1.1075.2.141.  .5(raebu 17345:20): sub get_requested_shorturls {
          .1(raebu 17346:20):     my ($cdom,$cnum,$navmap) = @_;
                   17347:20):     return unless (ref($navmap));
          .5(raebu 17348:20):     my ($numnew,$errors);
          .1(raebu 17349:20):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17350:20):     if (@toshorten) {
                   17351:20):         my (%maps,%resources,%titles);
                   17352:20):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17353:20):                                                                'shorturls',$cdom,$cnum);
                   17354:20):         if (keys(%resources)) {
          .5(raebu 17355:20):             my %tocreate;
          .1(raebu 17356:20):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17357:20):                 my $symb = $resources{$item};
                   17358:20):                 if ($symb) {
                   17359:20):                     $tocreate{$cnum.'&'.$symb} = 1;
                   17360:20):                 }
                   17361:20):             }
          .5(raebu 17362:20):             if (keys(%tocreate)) {
                   17363:20):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   17364:20):                                                       \%tocreate);
                   17365:20):             }
          .1(raebu 17366:20):         }
          .5(raebu 17367:20):     }
                   17368:20):     return ($numnew,$errors);
                   17369:20): }
                   17370:20): 
                   17371:20): sub make_short_symbs {
                   17372:20):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   17373:20):     my ($numnew,@errors);
                   17374:20):     if (ref($tocreateref) eq 'HASH') {
                   17375:20):         my %tocreate = %{$tocreateref};
          .1(raebu 17376:20):         if (keys(%tocreate)) {
                   17377:20):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17378:20):             my $su = Short::URL->new(no_vowels => 1);
                   17379:20):             my $init = '';
                   17380:20):             my (%newunique,%addcourse,%courseonly,%failed);
                   17381:20):             # get lock on tiny db
                   17382:20):             my $now = time;
          .5(raebu 17383:20):             if ($lockuser eq '') {
                   17384:20):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   17385:20):             }
          .1(raebu 17386:20):             my $lockhash = {
          .5(raebu 17387:20):                                 "lock\0$now" => $lockuser,
          .1(raebu 17388:20):                             };
                   17389:20):             my $tries = 0;
                   17390:20):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17391:20):             my ($code,$error);
                   17392:20):             while (($gotlock ne 'ok') && ($tries<3)) {
                   17393:20):                 $tries ++;
                   17394:20):                 sleep 1;
                   17395:20):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17396:20):             }
                   17397:20):             if ($gotlock eq 'ok') {
                   17398:20):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17399:20):                                        \%addcourse,\%courseonly,\%failed);
                   17400:20):                 if (keys(%failed)) {
                   17401:20):                     my $numfailed = scalar(keys(%failed));
                   17402:20):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17403:20):                 }
                   17404:20):                 if (keys(%newunique)) {
                   17405:20):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17406:20):                     if ($putres eq 'ok') {
                   17407:20):                         $numnew = scalar(keys(%newunique));
                   17408:20):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17409:20):                         unless ($newputres eq 'ok') {
                   17410:20):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17411:20):                         }
                   17412:20):                     } else {
                   17413:20):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   17414:20):                     }
                   17415:20):                 }
                   17416:20):             }
                   17417:20):         }
                   17418:20):     }
                   17419:20):     return ($numnew,\@errors);
                   17420:20): }
                   17421:20): 
                   17422:20): sub shorten_symbs {
                   17423:20):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   17424:20):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   17425:20):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   17426:20):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   17427:20):     my (%possibles,%collisions);
                   17428:20):     foreach my $key (keys(%{$tocreate})) {
                   17429:20):         my $num = String::CRC32::crc32($key);
                   17430:20):         my $tiny = $su->encode($num,$init);
                   17431:20):         if ($tiny) {
                   17432:20):             $possibles{$tiny} = $key;
                   17433:20):         }
                   17434:20):     }
                   17435:20):     if (!$init) {
                   17436:20):         $init = 1;
                   17437:20):     } else {
                   17438:20):         $init ++;
                   17439:20):     }
                   17440:20):     if (keys(%possibles)) {
                   17441:20):         my @posstiny = keys(%possibles);
                   17442:20):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   17443:20):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   17444:20):         if (keys(%currtiny)) {
                   17445:20):             foreach my $key (keys(%currtiny)) {
                   17446:20):                 next if ($currtiny{$key} eq '');
                   17447:20):                 if ($currtiny{$key} eq $possibles{$key}) {
                   17448:20):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   17449:20):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17450:20):                         $courseonly->{$tsymb} = $key;
                   17451:20):                     }
                   17452:20):                 } else {
                   17453:20):                     $collisions{$possibles{$key}} = 1;
                   17454:20):                 }
                   17455:20):                 delete($possibles{$key});
                   17456:20):             }
                   17457:20):         }
                   17458:20):         foreach my $key (keys(%possibles)) {
                   17459:20):             $newunique->{$key} = $possibles{$key};
                   17460:20):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   17461:20):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17462:20):                 $addcourse->{$tsymb} = $key;
                   17463:20):             }
                   17464:20):         }
                   17465:20):     }
                   17466:20):     if (keys(%collisions)) {
                   17467:20):         if ($init <5) {
                   17468:20):             if (!$init) {
                   17469:20):                 $init = 1;
                   17470:20):             } else {
                   17471:20):                 $init ++;
                   17472:20):             }
                   17473:20):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   17474:20):                                    $newunique,$addcourse,$courseonly,$failed);
                   17475:20):         } else {
                   17476:20):             foreach my $key (keys(%collisions)) {
                   17477:20):                 $failed->{$key} = 1;
                   17478:20):                 $failed->{$key} = 1;
                   17479:20):             }
                   17480:20):         }
                   17481:20):     }
                   17482:20):     return $init;
                   17483:20): }
                   17484:20): 
1.1075.2.135  raeburn  17485: sub is_nonframeable {
                   17486:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17487:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17488:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17489: 
                   17490:     $remprotocol = lc($remprotocol);
                   17491:     $remhost = lc($remhost);
                   17492:     my $remport = 80;
                   17493:     if ($remprotocol eq 'https') {
                   17494:         $remport = 443;
                   17495:     }
                   17496:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17497:     if ($cached) {
                   17498:         unless ($nocache) {
                   17499:             if ($result) {
                   17500:                 return 1;
                   17501:             } else {
                   17502:                 return 0;
                   17503:             }
                   17504:         }
                   17505:     }
                   17506:     my $uselink;
                   17507:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.141.  .2(raebu 17508:20):     my $ua = LWP::UserAgent->new;
                   17509:20):     $ua->timeout(5);
                   17510:20):     my $response=$ua->request($request);
1.1075.2.135  raeburn  17511:     if ($response->is_success()) {
                   17512:         my $secpolicy = lc($response->header('content-security-policy'));
                   17513:         my $xframeop = lc($response->header('x-frame-options'));
                   17514:         $secpolicy =~ s/^\s+|\s+$//g;
                   17515:         $xframeop =~ s/^\s+|\s+$//g;
                   17516:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17517:             my $remotehost = $remprotocol.'://'.$remhost;
                   17518:             my ($origin,$protocol,$port);
                   17519:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17520:                 $port = $ENV{'SERVER_PORT'};
                   17521:             } else {
                   17522:                 $port = 80;
                   17523:             }
                   17524:             if ($absolute eq '') {
                   17525:                 $protocol = 'http:';
                   17526:                 if ($port == 443) {
                   17527:                     $protocol = 'https:';
                   17528:                 }
                   17529:                 $origin = $protocol.'//'.lc($hostname);
                   17530:             } else {
                   17531:                 $origin = lc($absolute);
                   17532:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17533:             }
                   17534:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17535:                 my $framepolicy = $1;
                   17536:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17537:                 my @policies = split(/\s+/,$framepolicy);
                   17538:                 if (@policies) {
                   17539:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17540:                         $uselink = 1;
                   17541:                     } else {
                   17542:                         $uselink = 1;
                   17543:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17544:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17545:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17546:                             undef($uselink);
                   17547:                         }
                   17548:                         if ($uselink) {
                   17549:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17550:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17551:                                     undef($uselink);
                   17552:                                 }
                   17553:                             }
                   17554:                         }
                   17555:                         if ($uselink) {
                   17556:                             my @possok;
                   17557:                             if ($ip ne '') {
                   17558:                                 push(@possok,$ip);
                   17559:                             }
                   17560:                             my $hoststr = '';
                   17561:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17562:                                 if ($hoststr eq '') {
                   17563:                                     $hoststr = $part;
                   17564:                                 } else {
                   17565:                                     $hoststr = "$part.$hoststr";
                   17566:                                 }
                   17567:                                 if ($hoststr eq $hostname) {
                   17568:                                     push(@possok,$hostname);
                   17569:                                 } else {
                   17570:                                     push(@possok,"*.$hoststr");
                   17571:                                 }
                   17572:                             }
                   17573:                             if (@possok) {
                   17574:                                 foreach my $poss (@possok) {
                   17575:                                     last if (!$uselink);
                   17576:                                     foreach my $policy (@policies) {
                   17577:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17578:                                             undef($uselink);
                   17579:                                             last;
                   17580:                                         }
                   17581:                                     }
                   17582:                                 }
                   17583:                             }
                   17584:                         }
                   17585:                     }
                   17586:                 }
                   17587:             } elsif ($xframeop ne '') {
                   17588:                 $uselink = 1;
                   17589:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17590:                 if (@policies) {
                   17591:                     unless (grep(/^deny$/,@policies)) {
                   17592:                         if ($origin ne '') {
                   17593:                             if (grep(/^sameorigin$/,@policies)) {
                   17594:                                 if ($remotehost eq $origin) {
                   17595:                                     undef($uselink);
                   17596:                                 }
                   17597:                             }
                   17598:                             if ($uselink) {
                   17599:                                 foreach my $policy (@policies) {
                   17600:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17601:                                         my $allowfrom = $1;
                   17602:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17603:                                             undef($uselink);
                   17604:                                             last;
                   17605:                                         }
                   17606:                                     }
                   17607:                                 }
                   17608:                             }
                   17609:                         }
                   17610:                     }
                   17611:                 }
                   17612:             }
                   17613:         }
                   17614:     }
                   17615:     if ($nocache) {
                   17616:         if ($cached) {
                   17617:             my $devalidate;
                   17618:             if ($uselink && !$result) {
                   17619:                 $devalidate = 1;
                   17620:             } elsif (!$uselink && $result) {
                   17621:                 $devalidate = 1;
                   17622:             }
                   17623:             if ($devalidate) {
                   17624:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17625:             }
                   17626:         }
                   17627:     } else {
                   17628:         if ($uselink) {
                   17629:             $result = 1;
                   17630:         } else {
                   17631:             $result = 0;
                   17632:         }
                   17633:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17634:     }
                   17635:     return $uselink;
                   17636: }
                   17637: 
1.112     bowersj2 17638: 1;
                   17639: __END__;
1.41      ng       17640: 

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