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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.161.  .27(raeb    4:-24): # $Id: loncommon.pm,v 1.1075.2.161.2.26 2024/08/22 17:05:49 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.1075.2.161.  .7(raebu   64:22): use Apache::lonnavmaps();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.161.  .13(raeb   74:-23): use LONCAPA::map();
1.1075.2.135  raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1075.2.102  raeburn    77: use DateTime::Locale;
1.1075.2.94  raeburn    78: use Encode();
1.1075.2.14  raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1075.2.64  raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    85: use File::Copy();
                     86: use File::Path();
1.1075.2.161.  .1(raebu   87:21): use String::CRC32();
                     88:21): use Short::URL();
1.117     www        89: 
1.517     raeburn    90: # ---------------------------------------------- Designs
                     91: use vars qw(%defaultdesign);
                     92: 
1.22      www        93: my $readit;
                     94: 
1.517     raeburn    95: 
1.157     matthew    96: ##
                     97: ## Global Variables
                     98: ##
1.46      matthew    99: 
1.643     foxr      100: 
                    101: # ----------------------------------------------- SSI with retries:
                    102: #
                    103: 
                    104: =pod
                    105: 
1.648     raeburn   106: =head1 Server Side include with retries:
1.643     foxr      107: 
                    108: =over 4
                    109: 
1.648     raeburn   110: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      111: 
                    112: Performs an ssi with some number of retries.  Retries continue either
                    113: until the result is ok or until the retry count supplied by the
                    114: caller is exhausted.  
                    115: 
                    116: Inputs:
1.648     raeburn   117: 
                    118: =over 4
                    119: 
1.643     foxr      120: resource   - Identifies the resource to insert.
1.648     raeburn   121: 
1.643     foxr      122: retries    - Count of the number of retries allowed.
1.648     raeburn   123: 
1.643     foxr      124: form       - Hash that identifies the rendering options.
                    125: 
1.648     raeburn   126: =back
                    127: 
                    128: Returns:
                    129: 
                    130: =over 4
                    131: 
1.643     foxr      132: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   133: 
1.643     foxr      134: response   - The response from the last attempt (which may or may not have been successful.
                    135: 
1.648     raeburn   136: =back
                    137: 
                    138: =back
                    139: 
1.643     foxr      140: =cut
                    141: 
                    142: sub ssi_with_retries {
                    143:     my ($resource, $retries, %form) = @_;
                    144: 
                    145: 
                    146:     my $ok = 0;			# True if we got a good response.
                    147:     my $content;
                    148:     my $response;
                    149: 
                    150:     # Try to get the ssi done. within the retries count:
                    151: 
                    152:     do {
                    153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    154: 	$ok      = $response->is_success;
1.650     www       155:         if (!$ok) {
                    156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    157:         }
1.643     foxr      158: 	$retries--;
                    159:     } while (!$ok && ($retries > 0));
                    160: 
                    161:     if (!$ok) {
                    162: 	$content = '';		# On error return an empty content.
                    163:     }
                    164:     return ($content, $response);
                    165: 
                    166: }
                    167: 
                    168: 
                    169: 
1.20      www       170: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  171: my %language;
1.124     www       172: my %supported_language;
1.1048    foxr      173: my %latex_language;		# For choosing hyphenation in <transl..>
                    174: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  175: my %cprtag;
1.192     taceyjo1  176: my %scprtag;
1.351     www       177: my %fe; my %fd; my %fm;
1.41      ng        178: my %category_extensions;
1.12      harris41  179: 
1.46      matthew   180: # ---------------------------------------------- Thesaurus variables
1.144     matthew   181: #
                    182: # %Keywords:
                    183: #      A hash used by &keyword to determine if a word is considered a keyword.
                    184: # $thesaurus_db_file 
                    185: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   186: 
                    187: my %Keywords;
                    188: my $thesaurus_db_file;
                    189: 
1.144     matthew   190: #
                    191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    192: # thesaurus.tab, and filecategories.tab.
                    193: #
1.18      www       194: BEGIN {
1.46      matthew   195:     # Variable initialization
                    196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    197:     #
1.22      www       198:     unless ($readit) {
1.12      harris41  199: # ------------------------------------------------------------------- languages
                    200:     {
1.158     raeburn   201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    202:                                    '/language.tab';
1.1075.2.128  raeburn   203:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  204:             while (my $line = <$fh>) {
                    205:                 next if ($line=~/^\#/);
                    206:                 chomp($line);
1.1048    foxr      207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   208:                 $language{$key}=$val.' - '.$enc;
                    209:                 if ($sup) {
                    210:                     $supported_language{$key}=$sup;
                    211:                 }
1.1048    foxr      212: 		if ($latex) {
                    213: 		    $latex_language_bykey{$key} = $latex;
                    214: 		    $latex_language{$two} = $latex;
                    215: 		}
1.158     raeburn   216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
                    220: # ------------------------------------------------------------------ copyrights
                    221:     {
1.158     raeburn   222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/copyright.tab';
1.1075.2.128  raeburn   224:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line=~/^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   229:                 $cprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
1.12      harris41  233:     }
1.351     www       234: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  235:     {
                    236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    237:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  239:             while (my $line = <$fh>) {
                    240:                 next if ($line =~ /^\#/);
                    241:                 chomp($line);
                    242:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  243:                 $scprtag{$key}=$val;
                    244:             }
                    245:             close($fh);
                    246:         }
                    247:     }
1.63      www       248: 
1.517     raeburn   249: # -------------------------------------------------------------- default domain designs
1.63      www       250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   251:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   252:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   253:         while (my $line = <$fh>) {
                    254:             next if ($line =~ /^\#/);
                    255:             chomp($line);
                    256:             my ($key,$val)=(split(/\=/,$line));
                    257:             if ($val) { $defaultdesign{$key}=$val; }
                    258:         }
                    259:         close($fh);
1.63      www       260:     }
                    261: 
1.15      harris41  262: # ------------------------------------------------------------- file categories
                    263:     {
1.158     raeburn   264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    265:                                   '/filecategories.tab';
1.1075.2.128  raeburn   266:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  267: 	    while (my $line = <$fh>) {
                    268: 		next if ($line =~ /^\#/);
                    269: 		chomp($line);
                    270:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   271:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   272:             }
                    273:             close($fh);
                    274:         }
                    275: 
1.15      harris41  276:     }
1.12      harris41  277: # ------------------------------------------------------------------ file types
                    278:     {
1.158     raeburn   279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    280:                '/filetypes.tab';
1.1075.2.128  raeburn   281:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  282:             while (my $line = <$fh>) {
                    283: 		next if ($line =~ /^\#/);
                    284: 		chomp($line);
                    285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   286:                 if ($descr ne '') {
                    287:                     $fe{$ending}=lc($emb);
                    288:                     $fd{$ending}=$descr;
1.351     www       289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   290:                 }
                    291:             }
                    292:             close($fh);
                    293:         }
1.12      harris41  294:     }
1.22      www       295:     &Apache::lonnet::logthis(
1.705     tempelho  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       297:     $readit=1;
1.46      matthew   298:     }  # end of unless($readit) 
1.32      matthew   299:     
                    300: }
1.112     bowersj2  301: 
1.42      matthew   302: ###############################################################
                    303: ##           HTML and Javascript Helper Functions            ##
                    304: ###############################################################
                    305: 
                    306: =pod 
                    307: 
1.112     bowersj2  308: =head1 HTML and Javascript Functions
1.42      matthew   309: 
1.112     bowersj2  310: =over 4
                    311: 
1.648     raeburn   312: =item * &browser_and_searcher_javascript()
1.112     bowersj2  313: 
                    314: X<browsing, javascript>X<searching, javascript>Returns a string
                    315: containing javascript with two functions, C<openbrowser> and
                    316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    317: tags.
1.42      matthew   318: 
1.648     raeburn   319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   320: 
                    321: inputs: formname, elementname, only, omit
                    322: 
                    323: formname and elementname indicate the name of the html form and name of
                    324: the element that the results of the browsing selection are to be placed in. 
                    325: 
                    326: Specifying 'only' will restrict the browser to displaying only files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
                    329: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       330: with the given extension.  Can be a comma separated list.
1.42      matthew   331: 
1.648     raeburn   332: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   333: 
                    334: Inputs: formname, elementname
                    335: 
                    336: formname and elementname specify the name of the html form and the name
                    337: of the element the selection from the search results will be placed in.
1.542     raeburn   338: 
1.42      matthew   339: =cut
                    340: 
                    341: sub browser_and_searcher_javascript {
1.199     albertel  342:     my ($mode)=@_;
                    343:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  344:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   345:     return <<END;
1.219     albertel  346: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   347:     var editbrowser = null;
1.135     albertel  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       349:         var url = '$resurl/?';
1.42      matthew   350:         if (editbrowser == null) {
                    351:             url += 'launch=1&';
                    352:         }
                    353:         url += 'catalogmode=interactive&';
1.199     albertel  354:         url += 'mode=$mode&';
1.611     albertel  355:         url += 'inhibitmenu=yes&';
1.42      matthew   356:         url += 'form=' + formname + '&';
                    357:         if (only != null) {
                    358:             url += 'only=' + only + '&';
1.217     albertel  359:         } else {
                    360:             url += 'only=&';
                    361: 	}
1.42      matthew   362:         if (omit != null) {
                    363:             url += 'omit=' + omit + '&';
1.217     albertel  364:         } else {
                    365:             url += 'omit=&';
                    366: 	}
1.135     albertel  367:         if (titleelement != null) {
                    368:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  369:         } else {
                    370: 	    url += 'titleelement=&';
                    371: 	}
1.42      matthew   372:         url += 'element=' + elementname + '';
                    373:         var title = 'Browser';
1.435     albertel  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   375:         options += ',width=700,height=600';
                    376:         editbrowser = open(url,title,options,'1');
                    377:         editbrowser.focus();
                    378:     }
                    379:     var editsearcher;
1.135     albertel  380:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   381:         var url = '/adm/searchcat?';
                    382:         if (editsearcher == null) {
                    383:             url += 'launch=1&';
                    384:         }
                    385:         url += 'catalogmode=interactive&';
1.199     albertel  386:         url += 'mode=$mode&';
1.42      matthew   387:         url += 'form=' + formname + '&';
1.135     albertel  388:         if (titleelement != null) {
                    389:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  390:         } else {
                    391: 	    url += 'titleelement=&';
                    392: 	}
1.42      matthew   393:         url += 'element=' + elementname + '';
                    394:         var title = 'Search';
1.435     albertel  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   396:         options += ',width=700,height=600';
                    397:         editsearcher = open(url,title,options,'1');
                    398:         editsearcher.focus();
                    399:     }
1.219     albertel  400: // END LON-CAPA Internal -->
1.42      matthew   401: END
1.170     www       402: }
                    403: 
                    404: sub lastresurl {
1.258     albertel  405:     if ($env{'environment.lastresurl'}) {
                    406: 	return $env{'environment.lastresurl'}
1.170     www       407:     } else {
                    408: 	return '/res';
                    409:     }
                    410: }
                    411: 
                    412: sub storeresurl {
                    413:     my $resurl=&Apache::lonnet::clutter(shift);
                    414:     unless ($resurl=~/^\/res/) { return 0; }
                    415:     $resurl=~s/\/$//;
                    416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       418:     return 1;
1.42      matthew   419: }
                    420: 
1.74      www       421: sub studentbrowser_javascript {
1.111     www       422:    unless (
1.258     albertel  423:             (($env{'request.course.id'}) && 
1.302     albertel  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    426: 					  '/'.$env{'request.course.sec'})
                    427: 	      ))
1.258     albertel  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       429:           ) { return ''; }  
1.74      www       430:    return (<<'ENDSTDBRW');
1.776     bisitz    431: <script type="text/javascript" language="Javascript">
1.824     bisitz    432: // <![CDATA[
1.74      www       433:     var stdeditbrowser;
1.1075.2.161.  .20(raeb  434:-23):     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       435:         var url = '/adm/pickstudent?';
                    436:         var filter;
1.558     albertel  437: 	if (!ignorefilter) {
                    438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    439: 	}
1.74      www       440:         if (filter != null) {
                    441:            if (filter != '') {
                    442:                url += 'filter='+filter+'&';
                    443: 	   }
                    444:         }
                    445:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       446:                                     '&udomelement='+udom+
                    447:                                     '&clicker='+clicker;
1.111     www       448: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   449:         if (courseadv == 'condition') {
                    450:             if (document.getElementById('courseadv')) {
                    451:                 courseadv = document.getElementById('courseadv').value;
                    452:             }
                    453:         }
                    454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1075.2.161.  .20(raeb  455:-23):         if (uident !== '') { url+="&identelement="+uident; }
1.102     www       456:         var title = 'Student_Browser';
1.74      www       457:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    458:         options += ',width=700,height=600';
                    459:         stdeditbrowser = open(url,title,options,'1');
                    460:         stdeditbrowser.focus();
                    461:     }
1.824     bisitz    462: // ]]>
1.74      www       463: </script>
                    464: ENDSTDBRW
                    465: }
1.42      matthew   466: 
1.1003    www       467: sub resourcebrowser_javascript {
                    468:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       469:    return (<<'ENDRESBRW');
1.1003    www       470: <script type="text/javascript" language="Javascript">
                    471: // <![CDATA[
                    472:     var reseditbrowser;
1.1004    www       473:     function openresbrowser(formname,reslink) {
1.1005    www       474:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       475:         var title = 'Resource_Browser';
                    476:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       477:         options += ',width=700,height=500';
1.1004    www       478:         reseditbrowser = open(url,title,options,'1');
                    479:         reseditbrowser.focus();
1.1003    www       480:     }
                    481: // ]]>
                    482: </script>
1.1004    www       483: ENDRESBRW
1.1003    www       484: }
                    485: 
1.74      www       486: sub selectstudent_link {
1.1075.2.161.  .20(raeb  487:-23):    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       488:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    490:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  491:    if ($env{'request.course.id'}) {  
1.302     albertel  492:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    493: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    494: 					'/'.$env{'request.course.sec'})) {
1.111     www       495: 	   return '';
                    496:        }
1.999     www       497:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   498:        if ($courseadv eq 'only') {
                    499:            $callargs .= ",'',1,'$courseadv'";
                    500:        } elsif ($courseadv eq 'none') {
                    501:            $callargs .= ",'','','$courseadv'";
                    502:        } elsif ($courseadv eq 'condition') {
                    503:            $callargs .= ",'','','$courseadv'";
1.1075.2.161.  .20(raeb  504:-23):        } elsif ($identelem ne '') {
                    505:-23):            $callargs .= ",'','',''";
                    506:-23):        }
                    507:-23):        if ($identelem ne '') {
                    508:-23):            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   509:        }
                    510:        return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    512:               &mt('Select User').'</a></span>';
1.74      www       513:    }
1.258     albertel  514:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       515:        $callargs .= ",'',1"; 
1.793     raeburn   516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.111     www       519:    }
                    520:    return '';
1.91      www       521: }
                    522: 
1.1004    www       523: sub selectresource_link {
                    524:    my ($form,$reslink,$arg)=@_;
                    525:    
                    526:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    527:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    528:    unless ($env{'request.course.id'}) { return $arg; }
                    529:    return '<span class="LC_nobreak">'.
                    530:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    531:               $arg.'</a></span>';
                    532: }
                    533: 
                    534: 
                    535: 
1.653     raeburn   536: sub authorbrowser_javascript {
                    537:     return <<"ENDAUTHORBRW";
1.776     bisitz    538: <script type="text/javascript" language="JavaScript">
1.824     bisitz    539: // <![CDATA[
1.653     raeburn   540: var stdeditbrowser;
                    541: 
                    542: function openauthorbrowser(formname,udom) {
                    543:     var url = '/adm/pickauthor?';
                    544:     url += 'form='+formname+'&roledom='+udom;
                    545:     var title = 'Author_Browser';
                    546:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    547:     options += ',width=700,height=600';
                    548:     stdeditbrowser = open(url,title,options,'1');
                    549:     stdeditbrowser.focus();
                    550: }
                    551: 
1.824     bisitz    552: // ]]>
1.653     raeburn   553: </script>
                    554: ENDAUTHORBRW
                    555: }
                    556: 
1.91      www       557: sub coursebrowser_javascript {
1.1075.2.31  raeburn   558:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   559:         $credits_element,$instcode) = @_;
1.932     raeburn   560:     my $wintitle = 'Course_Browser';
1.931     raeburn   561:     if ($crstype eq 'Community') {
1.932     raeburn   562:         $wintitle = 'Community_Browser';
1.909     raeburn   563:     }
1.876     raeburn   564:     my $id_functions = &javascript_index_functions();
                    565:     my $output = '
1.776     bisitz    566: <script type="text/javascript" language="JavaScript">
1.824     bisitz    567: // <![CDATA[
1.468     raeburn   568:     var stdeditbrowser;'."\n";
1.876     raeburn   569: 
                    570:     $output .= <<"ENDSTDBRW";
1.909     raeburn   571:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       572:         var url = '/adm/pickcourse?';
1.895     raeburn   573:         var formid = getFormIdByName(formname);
1.876     raeburn   574:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  575:         if (domainfilter != null) {
                    576:            if (domainfilter != '') {
                    577:                url += 'domainfilter='+domainfilter+'&';
                    578: 	   }
                    579:         }
1.91      www       580:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  581: 	                            '&cdomelement='+udom+
                    582:                                     '&cnameelement='+desc;
1.468     raeburn   583:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   584:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   585:                 url += '&roleelement='+extra_element;
                    586:                 if (domainfilter == null || domainfilter == '') {
                    587:                     url += '&domainfilter='+extra_element;
                    588:                 }
1.234     raeburn   589:             }
1.468     raeburn   590:             else {
                    591:                 if (formname == 'portform') {
                    592:                     url += '&setroles='+extra_element;
1.800     raeburn   593:                 } else {
                    594:                     if (formname == 'rules') {
                    595:                         url += '&fixeddom='+extra_element; 
                    596:                     }
1.468     raeburn   597:                 }
                    598:             }     
1.230     raeburn   599:         }
1.909     raeburn   600:         if (type != null && type != '') {
                    601:             url += '&type='+type;
                    602:         }
                    603:         if (type_elem != null && type_elem != '') {
                    604:             url += '&typeelement='+type_elem;
                    605:         }
1.872     raeburn   606:         if (formname == 'ccrs') {
                    607:             var ownername = document.forms[formid].ccuname.value;
                    608:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   609:             url += '&cloner='+ownername+':'+ownerdom;
                    610:             if (type == 'Course') {
                    611:                 url += '&crscode='+document.forms[formid].crscode.value;
                    612:             }
1.1075.2.95  raeburn   613:         }
                    614:         if (formname == 'requestcrs') {
                    615:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   616:         }
1.293     raeburn   617:         if (multflag !=null && multflag != '') {
                    618:             url += '&multiple='+multflag;
                    619:         }
1.909     raeburn   620:         var title = '$wintitle';
1.91      www       621:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    622:         options += ',width=700,height=600';
                    623:         stdeditbrowser = open(url,title,options,'1');
                    624:         stdeditbrowser.focus();
                    625:     }
1.876     raeburn   626: $id_functions
                    627: ENDSTDBRW
1.1075.2.31  raeburn   628:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    629:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    630:                                       $credits_element);
1.876     raeburn   631:     }
                    632:     $output .= '
                    633: // ]]>
                    634: </script>';
                    635:     return $output;
                    636: }
                    637: 
                    638: sub javascript_index_functions {
                    639:     return <<"ENDJS";
                    640: 
                    641: function getFormIdByName(formname) {
                    642:     for (var i=0;i<document.forms.length;i++) {
                    643:         if (document.forms[i].name == formname) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
                    649: 
                    650: function getIndexByName(formid,item) {
                    651:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    652:         if (document.forms[formid].elements[i].name == item) {
                    653:             return i;
                    654:         }
                    655:     }
                    656:     return -1;
                    657: }
1.468     raeburn   658: 
1.876     raeburn   659: function getDomainFromSelectbox(formname,udom) {
                    660:     var userdom;
                    661:     var formid = getFormIdByName(formname);
                    662:     if (formid > -1) {
                    663:         var domid = getIndexByName(formid,udom);
                    664:         if (domid > -1) {
                    665:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    666:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    667:             }
                    668:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    669:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   670:             }
                    671:         }
                    672:     }
1.876     raeburn   673:     return userdom;
                    674: }
                    675: 
                    676: ENDJS
1.468     raeburn   677: 
1.876     raeburn   678: }
                    679: 
1.1017    raeburn   680: sub javascript_array_indexof {
1.1018    raeburn   681:     return <<ENDJS;
1.1017    raeburn   682: <script type="text/javascript" language="JavaScript">
                    683: // <![CDATA[
                    684: 
                    685: if (!Array.prototype.indexOf) {
                    686:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    687:         "use strict";
                    688:         if (this === void 0 || this === null) {
                    689:             throw new TypeError();
                    690:         }
                    691:         var t = Object(this);
                    692:         var len = t.length >>> 0;
                    693:         if (len === 0) {
                    694:             return -1;
                    695:         }
                    696:         var n = 0;
                    697:         if (arguments.length > 0) {
                    698:             n = Number(arguments[1]);
                    699:             if (n !== n) { // shortcut for verifying if it's NaN
                    700:                 n = 0;
                    701:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    702:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    703:             }
                    704:         }
                    705:         if (n >= len) {
                    706:             return -1;
                    707:         }
                    708:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    709:         for (; k < len; k++) {
                    710:             if (k in t && t[k] === searchElement) {
                    711:                 return k;
                    712:             }
                    713:         }
                    714:         return -1;
                    715:     }
                    716: }
                    717: 
                    718: // ]]>
                    719: </script>
                    720: 
                    721: ENDJS
                    722: 
                    723: }
                    724: 
1.876     raeburn   725: sub userbrowser_javascript {
                    726:     my $id_functions = &javascript_index_functions();
                    727:     return <<"ENDUSERBRW";
                    728: 
1.888     raeburn   729: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   730:     var url = '/adm/pickuser?';
                    731:     var userdom = getDomainFromSelectbox(formname,udom);
                    732:     if (userdom != null) {
                    733:        if (userdom != '') {
                    734:            url += 'srchdom='+userdom+'&';
                    735:        }
                    736:     }
                    737:     url += 'form=' + formname + '&unameelement='+uname+
                    738:                                 '&udomelement='+udom+
                    739:                                 '&ulastelement='+ulast+
                    740:                                 '&ufirstelement='+ufirst+
                    741:                                 '&uemailelement='+uemail+
1.881     raeburn   742:                                 '&hideudomelement='+hideudom+
                    743:                                 '&coursedom='+crsdom;
1.888     raeburn   744:     if ((caller != null) && (caller != undefined)) {
                    745:         url += '&caller='+caller;
                    746:     }
1.876     raeburn   747:     var title = 'User_Browser';
                    748:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    749:     options += ',width=700,height=600';
                    750:     var stdeditbrowser = open(url,title,options,'1');
                    751:     stdeditbrowser.focus();
                    752: }
                    753: 
1.888     raeburn   754: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   755:     var formid = getFormIdByName(formname);
                    756:     if (formid > -1) {
1.888     raeburn   757:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   758:         var domid = getIndexByName(formid,udom);
                    759:         var hidedomid = getIndexByName(formid,origdom);
                    760:         if (hidedomid > -1) {
                    761:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   762:             var unameval = document.forms[formid].elements[unameid].value;
                    763:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    764:                 if (domid > -1) {
                    765:                     var slct = document.forms[formid].elements[domid];
                    766:                     if (slct.type == 'select-one') {
                    767:                         var i;
                    768:                         for (i=0;i<slct.length;i++) {
                    769:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    770:                         }
                    771:                     }
                    772:                     if (slct.type == 'hidden') {
                    773:                         slct.value = fixeddom;
1.876     raeburn   774:                     }
                    775:                 }
1.468     raeburn   776:             }
                    777:         }
                    778:     }
1.876     raeburn   779:     return;
                    780: }
                    781: 
                    782: $id_functions
                    783: ENDUSERBRW
1.468     raeburn   784: }
                    785: 
                    786: sub setsec_javascript {
1.1075.2.31  raeburn   787:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   788:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    789:         $communityrolestr);
                    790:     if ($role_element ne '') {
                    791:         my @allroles = ('st','ta','ep','in','ad');
                    792:         foreach my $crstype ('Course','Community') {
                    793:             if ($crstype eq 'Community') {
                    794:                 foreach my $role (@allroles) {
                    795:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    796:                 }
                    797:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    798:             } else {
                    799:                 foreach my $role (@allroles) {
                    800:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    801:                 }
                    802:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    803:             }
                    804:         }
                    805:         $rolestr = '"'.join('","',@allroles).'"';
                    806:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    807:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    808:     }
1.468     raeburn   809:     my $setsections = qq|
                    810: function setSect(sectionlist) {
1.629     raeburn   811:     var sectionsArray = new Array();
                    812:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    813:         sectionsArray = sectionlist.split(",");
                    814:     }
1.468     raeburn   815:     var numSections = sectionsArray.length;
                    816:     document.$formname.$sec_element.length = 0;
                    817:     if (numSections == 0) {
                    818:         document.$formname.$sec_element.multiple=false;
                    819:         document.$formname.$sec_element.size=1;
                    820:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    821:     } else {
                    822:         if (numSections == 1) {
                    823:             document.$formname.$sec_element.multiple=false;
                    824:             document.$formname.$sec_element.size=1;
                    825:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    826:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    827:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    828:         } else {
                    829:             for (var i=0; i<numSections; i++) {
                    830:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    831:             }
                    832:             document.$formname.$sec_element.multiple=true
                    833:             if (numSections < 3) {
                    834:                 document.$formname.$sec_element.size=numSections;
                    835:             } else {
                    836:                 document.$formname.$sec_element.size=3;
                    837:             }
                    838:             document.$formname.$sec_element.options[0].selected = false
                    839:         }
                    840:     }
1.91      www       841: }
1.905     raeburn   842: 
                    843: function setRole(crstype) {
1.468     raeburn   844: |;
1.905     raeburn   845:     if ($role_element eq '') {
                    846:         $setsections .= '    return;
                    847: }
                    848: ';
                    849:     } else {
                    850:         $setsections .= qq|
                    851:     var elementLength = document.$formname.$role_element.length;
                    852:     var allroles = Array($rolestr);
                    853:     var courserolenames = Array($courserolestr);
                    854:     var communityrolenames = Array($communityrolestr);
                    855:     if (elementLength != undefined) {
                    856:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    857:             if (crstype == 'Course') {
                    858:                 return;
                    859:             } else {
                    860:                 allroles[5] = 'co';
                    861:                 for (var i=0; i<6; i++) {
                    862:                     document.$formname.$role_element.options[i].value = allroles[i];
                    863:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    864:                 }
                    865:             }
                    866:         } else {
                    867:             if (crstype == 'Community') {
                    868:                 return;
                    869:             } else {
                    870:                 allroles[5] = 'cc';
                    871:                 for (var i=0; i<6; i++) {
                    872:                     document.$formname.$role_element.options[i].value = allroles[i];
                    873:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    874:                 }
                    875:             }
                    876:         }
                    877:     }
                    878:     return;
                    879: }
                    880: |;
                    881:     }
1.1075.2.31  raeburn   882:     if ($credits_element) {
                    883:         $setsections .= qq|
                    884: function setCredits(defaultcredits) {
                    885:     document.$formname.$credits_element.value = defaultcredits;
                    886:     return;
                    887: }
                    888: |;
                    889:     }
1.468     raeburn   890:     return $setsections;
                    891: }
                    892: 
1.91      www       893: sub selectcourse_link {
1.909     raeburn   894:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    895:        $typeelement) = @_;
                    896:    my $type = $selecttype;
1.871     raeburn   897:    my $linktext = &mt('Select Course');
                    898:    if ($selecttype eq 'Community') {
1.909     raeburn   899:        $linktext = &mt('Select Community');
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   935:             if (!field[i].disabled) {
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1075.2.14  raeburn   940:         if (!field.disabled) {
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1075.2.161.  .10(raeb  960:-22):    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    961:-22):    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1075.2.115  raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1075.2.102  raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1075.2.94  raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1015:                 push(@possibles,$id);
1.687     raeburn  1016:             }
                   1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1075.2.115  raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1075.2.32  raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1075.2.32  raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.648     raeburn  1052: =item * &linked_select_forms(...)
1.36      matthew  1053: 
                   1054: linked_select_forms returns a string containing a <script></script> block
                   1055: and html for two <select> menus.  The select menus will be linked in that
                   1056: changing the value of the first menu will result in new values being placed
                   1057: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1058: order unless a defined order is provided.
1.36      matthew  1059: 
                   1060: linked_select_forms takes the following ordered inputs:
                   1061: 
                   1062: =over 4
                   1063: 
1.112     bowersj2 1064: =item * $formname, the name of the <form> tag
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $firstdefault, the default value for the first menu
1.36      matthew  1069: 
1.112     bowersj2 1070: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1071: 
1.112     bowersj2 1072: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1073: 
1.112     bowersj2 1074: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1075: 
1.609     raeburn  1076: =item * $menuorder, the order of values in the first menu
                   1077: 
1.1075.2.31  raeburn  1078: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1079:         event for the first <select> tag
                   1080: 
                   1081: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1082:         event for the second <select> tag
                   1083: 
1.41      ng       1084: =back 
                   1085: 
1.36      matthew  1086: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1087: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1088: values for the first select menu.  The text that coincides with the 
1.41      ng       1089: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1090: and text for the second menu are given in the hash pointed to by 
                   1091: $menu{$choice1}->{'select2'}.  
                   1092: 
1.112     bowersj2 1093:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1094:                        default => "B3",
                   1095:                        select2 => { 
                   1096:                            B1 => "Choice B1",
                   1097:                            B2 => "Choice B2",
                   1098:                            B3 => "Choice B3",
                   1099:                            B4 => "Choice B4"
1.609     raeburn  1100:                            },
                   1101:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1102:                    },
                   1103:                A2 => { text =>"Choice A2" ,
                   1104:                        default => "C2",
                   1105:                        select2 => { 
                   1106:                            C1 => "Choice C1",
                   1107:                            C2 => "Choice C2",
                   1108:                            C3 => "Choice C3"
1.609     raeburn  1109:                            },
                   1110:                        order => ['C2','C1','C3'],
1.112     bowersj2 1111:                    },
                   1112:                A3 => { text =>"Choice A3" ,
                   1113:                        default => "D6",
                   1114:                        select2 => { 
                   1115:                            D1 => "Choice D1",
                   1116:                            D2 => "Choice D2",
                   1117:                            D3 => "Choice D3",
                   1118:                            D4 => "Choice D4",
                   1119:                            D5 => "Choice D5",
                   1120:                            D6 => "Choice D6",
                   1121:                            D7 => "Choice D7"
1.609     raeburn  1122:                            },
                   1123:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1124:                    }
                   1125:                );
1.36      matthew  1126: 
                   1127: =cut
                   1128: 
                   1129: sub linked_select_forms {
                   1130:     my ($formname,
                   1131:         $middletext,
                   1132:         $firstdefault,
                   1133:         $firstselectname,
                   1134:         $secondselectname, 
1.609     raeburn  1135:         $hashref,
                   1136:         $menuorder,
1.1075.2.31  raeburn  1137:         $onchangefirst,
                   1138:         $onchangesecond
1.36      matthew  1139:         ) = @_;
                   1140:     my $second = "document.$formname.$secondselectname";
                   1141:     my $first = "document.$formname.$firstselectname";
                   1142:     # output the javascript to do the changing
                   1143:     my $result = '';
1.776     bisitz   1144:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1145:     $result.="// <![CDATA[\n";
1.36      matthew  1146:     $result.="var select2data = new Object();\n";
                   1147:     $" = '","';
                   1148:     my $debug = '';
                   1149:     foreach my $s1 (sort(keys(%$hashref))) {
                   1150:         $result.="select2data.d_$s1 = new Object();\n";        
                   1151:         $result.="select2data.d_$s1.def = new String('".
                   1152:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1153:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1154:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1155:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1156:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1157:         }
1.36      matthew  1158:         $result.="\"@s2values\");\n";
                   1159:         $result.="select2data.d_$s1.texts = new Array(";        
                   1160:         my @s2texts;
                   1161:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1162:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1163:         }
                   1164:         $result.="\"@s2texts\");\n";
                   1165:     }
                   1166:     $"=' ';
                   1167:     $result.= <<"END";
                   1168: 
                   1169: function select1_changed() {
                   1170:     // Determine new choice
                   1171:     var newvalue = "d_" + $first.value;
                   1172:     // update select2
                   1173:     var values     = select2data[newvalue].values;
                   1174:     var texts      = select2data[newvalue].texts;
                   1175:     var select2def = select2data[newvalue].def;
                   1176:     var i;
                   1177:     // out with the old
                   1178:     for (i = 0; i < $second.options.length; i++) {
                   1179:         $second.options[i] = null;
                   1180:     }
                   1181:     // in with the nuclear
                   1182:     for (i=0;i<values.length; i++) {
                   1183:         $second.options[i] = new Option(values[i]);
1.143     matthew  1184:         $second.options[i].value = values[i];
1.36      matthew  1185:         $second.options[i].text = texts[i];
                   1186:         if (values[i] == select2def) {
                   1187:             $second.options[i].selected = true;
                   1188:         }
                   1189:     }
                   1190: }
1.824     bisitz   1191: // ]]>
1.36      matthew  1192: </script>
                   1193: END
                   1194:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1195:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1196:     my @order = sort(keys(%{$hashref}));
                   1197:     if (ref($menuorder) eq 'ARRAY') {
                   1198:         @order = @{$menuorder};
                   1199:     }
                   1200:     foreach my $value (@order) {
1.36      matthew  1201:         $result.="    <option value=\"$value\" ";
1.253     albertel 1202:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1203:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1204:     }
                   1205:     $result .= "</select>\n";
                   1206:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1207:     $result .= $middletext;
1.1075.2.31  raeburn  1208:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1209:     if ($onchangesecond) {
                   1210:         $result .= ' onchange="'.$onchangesecond.'"';
                   1211:     }
                   1212:     $result .= ">\n";
1.36      matthew  1213:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1214:     
                   1215:     my @secondorder = sort(keys(%select2));
                   1216:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1217:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1218:     }
                   1219:     foreach my $value (@secondorder) {
1.36      matthew  1220:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1221:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1222:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1223:     }
                   1224:     $result .= "</select>\n";
                   1225:     #    return $debug;
                   1226:     return $result;
                   1227: }   #  end of sub linked_select_forms {
                   1228: 
1.45      matthew  1229: =pod
1.44      bowersj2 1230: 
1.1075.2.161.  .6(raebu 1231:22): =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1232: 
1.112     bowersj2 1233: Returns a string corresponding to an HTML link to the given help
                   1234: $topic, where $topic corresponds to the name of a .tex file in
                   1235: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1236: spaces. 
                   1237: 
                   1238: $text will optionally be linked to the same topic, allowing you to
                   1239: link text in addition to the graphic. If you do not want to link
                   1240: text, but wish to specify one of the later parameters, pass an
                   1241: empty string. 
                   1242: 
                   1243: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1244: the link will not open a new window. If false, the link will open
                   1245: a new window using Javascript. (Default is false.) 
                   1246: 
                   1247: $width and $height are optional numerical parameters that will
                   1248: override the width and height of the popped up window, which may
1.973     raeburn  1249: be useful for certain help topics with big pictures included.
                   1250: 
                   1251: $imgid is the id of the img tag used for the help icon. This may be
                   1252: used in a javascript call to switch the image src.  See 
                   1253: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1254: 
1.1075.2.161.  .6(raebu 1255:22): $links_target will optionally be set to a target (_top, _parent or _self).
                   1256:22): 
1.44      bowersj2 1257: =cut
                   1258: 
                   1259: sub help_open_topic {
1.1075.2.161.  .6(raebu 1260:22):     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1261:     $text = "" if (not defined $text);
1.44      bowersj2 1262:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1263:     $width = 500 if (not defined $width);
1.44      bowersj2 1264:     $height = 400 if (not defined $height);
                   1265:     my $filename = $topic;
                   1266:     $filename =~ s/ /_/g;
                   1267: 
1.48      bowersj2 1268:     my $template = "";
                   1269:     my $link;
1.572     banghart 1270:     
1.159     www      1271:     $topic=~s/\W/\_/g;
1.44      bowersj2 1272: 
1.572     banghart 1273:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1274:         if ($env{'browser.mobile'}) {
                   1275: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1276:         } else {
                   1277:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1278:         }
1.1037    www      1279:     } elsif ($stayOnPage eq 'popup') {
                   1280:         $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 1281:     } else {
1.48      bowersj2 1282: 	$link = "/adm/help/${filename}.hlp";
                   1283:     }
                   1284: 
                   1285:     # Add the text
1.1075.2.161.  .6(raebu 1286:22):     my $target = ' target="_top"';
                   1287:22):     if ($links_target) {
                   1288:22):         $target = ' target="'.$links_target.'"';
          .17(raeb 1289:-23):     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1290:-23):              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
          .6(raebu 1291:22):         $target = '';
                   1292:22):     }
1.755     neumanie 1293:     if ($text ne "") {	
1.763     bisitz   1294: 	$template.='<span class="LC_help_open_topic">'
1.1075.2.161.  .6(raebu 1295:22):                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1296:                   .$text.'</a>';
1.48      bowersj2 1297:     }
                   1298: 
1.763     bisitz   1299:     # (Always) Add the graphic
1.179     matthew  1300:     my $title = &mt('Online Help');
1.667     raeburn  1301:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1302:     if ($imgid ne '') {
                   1303:         $imgid = ' id="'.$imgid.'"';
                   1304:     }
1.1075.2.161.  .6(raebu 1305:22):     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1306:               .'<img src="'.$helpicon.'" border="0"'
                   1307:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1308:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1309:               .' /></a>';
                   1310:     if ($text ne "") {	
                   1311:         $template.='</span>';
                   1312:     }
1.44      bowersj2 1313:     return $template;
                   1314: 
1.106     bowersj2 1315: }
                   1316: 
                   1317: # This is a quicky function for Latex cheatsheet editing, since it 
                   1318: # appears in at least four places
                   1319: sub helpLatexCheatsheet {
1.1037    www      1320:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1321:     my $out;
1.106     bowersj2 1322:     my $addOther = '';
1.732     raeburn  1323:     if ($topic) {
1.1037    www      1324: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1325:     }
                   1326:     $out = '<span>' # Start cheatsheet
                   1327: 	  .$addOther
                   1328:           .'<span>'
1.1037    www      1329: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1330: 	  .'</span> <span>'
1.1037    www      1331: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1332: 	  .'</span>';
1.732     raeburn  1333:     unless ($not_author) {
1.763     bisitz   1334:         $out .= ' <span>'
1.1037    www      1335: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1336: 	       .'</span> <span>'
1.1075.2.78  raeburn  1337:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1338:                .'</span>';
1.732     raeburn  1339:     }
1.763     bisitz   1340:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1341:     return $out;
1.172     www      1342: }
                   1343: 
1.430     albertel 1344: sub general_help {
                   1345:     my $helptopic='Student_Intro';
                   1346:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1347: 	$helptopic='Authoring_Intro';
1.907     raeburn  1348:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1349: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1350:     } elsif ($env{'request.role'}=~/^dc/) {
                   1351:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1352:     }
                   1353:     return $helptopic;
                   1354: }
                   1355: 
                   1356: sub update_help_link {
                   1357:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1358:     my $origurl = $ENV{'REQUEST_URI'};
                   1359:     $origurl=~s|^/~|/priv/|;
                   1360:     my $timestamp = time;
                   1361:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1362:         $$datum = &escape($$datum);
                   1363:     }
                   1364: 
                   1365:     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";
                   1366:     my $output .= <<"ENDOUTPUT";
                   1367: <script type="text/javascript">
1.824     bisitz   1368: // <![CDATA[
1.430     albertel 1369: banner_link = '$banner_link';
1.824     bisitz   1370: // ]]>
1.430     albertel 1371: </script>
                   1372: ENDOUTPUT
                   1373:     return $output;
                   1374: }
                   1375: 
                   1376: # now just updates the help link and generates a blue icon
1.193     raeburn  1377: sub help_open_menu {
1.1075.2.161.  .6(raebu 1378:22):     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1379: 	= @_;    
1.949     droeschl 1380:     $stayOnPage = 1;
1.430     albertel 1381:     my $output;
                   1382:     if ($component_help) {
                   1383: 	if (!$text) {
                   1384: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1075.2.161.  .6(raebu 1385:22): 				       $width,$height,'',$links_target);
1.430     albertel 1386: 	} else {
                   1387: 	    my $help_text;
                   1388: 	    $help_text=&unescape($topic);
                   1389: 	    $output='<table><tr><td>'.
                   1390: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1075.2.161.  .6(raebu 1391:22): 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1392: 	}
                   1393:     }
                   1394:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1395:     return $output.$banner_link;
                   1396: }
                   1397: 
                   1398: sub top_nav_help {
1.1075.2.158  raeburn  1399:     my ($text,$linkattr) = @_;
1.436     albertel 1400:     $text = &mt($text);
1.1075.2.60  raeburn  1401:     my $stay_on_page;
                   1402:     unless ($env{'environment.remote'} eq 'on') {
                   1403:         $stay_on_page = 1;
                   1404:     }
1.1075.2.61  raeburn  1405:     my ($link,$banner_link);
                   1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1408: 	                         : "javascript:helpMenu('open')";
                   1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1410:     }
1.201     raeburn  1411:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1412:     if ($link) {
                   1413:         return <<"END";
1.436     albertel 1414: $banner_link
1.1075.2.158  raeburn  1415: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1416: END
1.1075.2.61  raeburn  1417:     } else {
                   1418:         return '&nbsp;'.$text.'&nbsp;';
                   1419:     }
1.436     albertel 1420: }
                   1421: 
                   1422: sub help_menu_js {
1.1075.2.52  raeburn  1423:     my ($httphost) = @_;
1.949     droeschl 1424:     my $stayOnPage = 1;
1.436     albertel 1425:     my $width = 620;
                   1426:     my $height = 600;
1.430     albertel 1427:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1430:     my $start_page =
                   1431:         &Apache::loncommon::start_page('Help Menu', undef,
                   1432: 				       {'frameset'    => 1,
                   1433: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1434:                                         'use_absolute' => $httphost,
1.331     albertel 1435: 					'add_entries' => {
                   1436: 					    'border' => '0',
1.579     raeburn  1437: 					    'rows'   => "110,*",},});
1.331     albertel 1438:     my $end_page =
                   1439:         &Apache::loncommon::end_page({'frameset' => 1,
                   1440: 				      'js_ready' => 1,});
                   1441: 
1.436     albertel 1442:     my $template .= <<"ENDTEMPLATE";
                   1443: <script type="text/javascript">
1.877     bisitz   1444: // <![CDATA[
1.253     albertel 1445: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1446: var banner_link = '';
1.243     raeburn  1447: function helpMenu(target) {
                   1448:     var caller = this;
                   1449:     if (target == 'open') {
                   1450:         var newWindow = null;
                   1451:         try {
1.262     albertel 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1453:         }
                   1454:         catch(error) {
                   1455:             writeHelp(caller);
                   1456:             return;
                   1457:         }
                   1458:         if (newWindow) {
                   1459:             caller = newWindow;
                   1460:         }
1.193     raeburn  1461:     }
1.243     raeburn  1462:     writeHelp(caller);
                   1463:     return;
                   1464: }
                   1465: function writeHelp(caller) {
1.1075.2.61  raeburn  1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1468:     caller.document.close();
                   1469:     caller.focus();
1.193     raeburn  1470: }
1.877     bisitz   1471: // END LON-CAPA Internal -->
1.253     albertel 1472: // ]]>
1.436     albertel 1473: </script>
1.193     raeburn  1474: ENDTEMPLATE
                   1475:     return $template;
                   1476: }
                   1477: 
1.172     www      1478: sub help_open_bug {
                   1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1480:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1482:     $text = "" if (not defined $text);
                   1483: 	$stayOnPage=1;
1.184     albertel 1484:     $width = 600 if (not defined $width);
                   1485:     $height = 600 if (not defined $height);
1.172     www      1486: 
                   1487:     $topic=~s/\W+/\+/g;
                   1488:     my $link='';
                   1489:     my $template='';
1.379     albertel 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1492:     if (!$stayOnPage)
                   1493:     {
                   1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1495:     }
                   1496:     else
                   1497:     {
                   1498: 	$link = $url;
                   1499:     }
1.1075.2.161.  .6(raebu 1500:22): 
                   1501:22):     my $target = '_top';
                   1502:22):     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1503:22):         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1504:22):         $target = '_blank';
                   1505:22):     }
                   1506:22): 
1.172     www      1507:     # Add the text
                   1508:     if ($text ne "")
                   1509:     {
                   1510: 	$template .= 
                   1511:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1075.2.161.  .6(raebu 1512:22):   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1513:     }
                   1514: 
                   1515:     # Add the graphic
1.179     matthew  1516:     my $title = &mt('Report a Bug');
1.215     albertel 1517:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1518:     $template .= <<"ENDTEMPLATE";
1.1075.2.161.  .6(raebu 1519:22):  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1520: ENDTEMPLATE
                   1521:     if ($text ne '') { $template.='</td></tr></table>' };
                   1522:     return $template;
                   1523: 
                   1524: }
                   1525: 
                   1526: sub help_open_faq {
                   1527:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1528:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1529:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1530:     $text = "" if (not defined $text);
                   1531: 	$stayOnPage=1;
                   1532:     $width = 350 if (not defined $width);
                   1533:     $height = 400 if (not defined $height);
                   1534: 
                   1535:     $topic=~s/\W+/\+/g;
                   1536:     my $link='';
                   1537:     my $template='';
                   1538:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1539:     if (!$stayOnPage)
                   1540:     {
                   1541: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1542:     }
                   1543:     else
                   1544:     {
                   1545: 	$link = $url;
                   1546:     }
                   1547: 
                   1548:     # Add the text
                   1549:     if ($text ne "")
                   1550:     {
                   1551: 	$template .= 
1.173     www      1552:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1553:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1554:     }
                   1555: 
                   1556:     # Add the graphic
1.179     matthew  1557:     my $title = &mt('View the FAQ');
1.215     albertel 1558:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1559:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1560:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1561: ENDTEMPLATE
                   1562:     if ($text ne '') { $template.='</td></tr></table>' };
                   1563:     return $template;
                   1564: 
1.44      bowersj2 1565: }
1.37      matthew  1566: 
1.180     matthew  1567: ###############################################################
                   1568: ###############################################################
                   1569: 
1.45      matthew  1570: =pod
                   1571: 
1.648     raeburn  1572: =item * &change_content_javascript():
1.256     matthew  1573: 
                   1574: This and the next function allow you to create small sections of an
                   1575: otherwise static HTML page that you can update on the fly with
                   1576: Javascript, even in Netscape 4.
                   1577: 
                   1578: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1579: must be written to the HTML page once. It will prove the Javascript
                   1580: function "change(name, content)". Calling the change function with the
                   1581: name of the section 
                   1582: you want to update, matching the name passed to C<changable_area>, and
                   1583: the new content you want to put in there, will put the content into
                   1584: that area.
                   1585: 
                   1586: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1587: to contain room for the original contents. You need to "make space"
                   1588: for whatever changes you wish to make, and be B<sure> to check your
                   1589: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1590: it's adequate for updating a one-line status display, but little more.
                   1591: This script will set the space to 100% width, so you only need to
                   1592: worry about height in Netscape 4.
                   1593: 
                   1594: Modern browsers are much less limiting, and if you can commit to the
                   1595: user not using Netscape 4, this feature may be used freely with
                   1596: pretty much any HTML.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub change_content_javascript {
                   1601:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1602:     if ($env{'browser.type'} eq 'netscape' &&
                   1603: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1604: 	return (<<NETSCAPE4);
                   1605: 	function change(name, content) {
                   1606: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1607: 	    doc.open();
                   1608: 	    doc.write(content);
                   1609: 	    doc.close();
                   1610: 	}
                   1611: NETSCAPE4
                   1612:     } else {
                   1613: 	# Otherwise, we need to use semi-standards-compliant code
                   1614: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1615: 	# is really scary, and every useful browser supports it
                   1616: 	return (<<DOMBASED);
                   1617: 	function change(name, content) {
                   1618: 	    element = document.getElementById(name);
                   1619: 	    element.innerHTML = content;
                   1620: 	}
                   1621: DOMBASED
                   1622:     }
                   1623: }
                   1624: 
                   1625: =pod
                   1626: 
1.648     raeburn  1627: =item * &changable_area($name,$origContent):
1.256     matthew  1628: 
                   1629: This provides a "changable area" that can be modified on the fly via
                   1630: the Javascript code provided in C<change_content_javascript>. $name is
                   1631: the name you will use to reference the area later; do not repeat the
                   1632: same name on a given HTML page more then once. $origContent is what
                   1633: the area will originally contain, which can be left blank.
                   1634: 
                   1635: =cut
                   1636: 
                   1637: sub changable_area {
                   1638:     my ($name, $origContent) = @_;
                   1639: 
1.258     albertel 1640:     if ($env{'browser.type'} eq 'netscape' &&
                   1641: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1642: 	# If this is netscape 4, we need to use the Layer tag
                   1643: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1644:     } else {
                   1645: 	return "<span id='$name'>$origContent</span>";
                   1646:     }
                   1647: }
                   1648: 
                   1649: =pod
                   1650: 
1.648     raeburn  1651: =item * &viewport_geometry_js 
1.590     raeburn  1652: 
                   1653: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1654: 
                   1655: =cut
                   1656: 
                   1657: 
                   1658: sub viewport_geometry_js { 
                   1659:     return <<"GEOMETRY";
                   1660: var Geometry = {};
                   1661: function init_geometry() {
                   1662:     if (Geometry.init) { return };
                   1663:     Geometry.init=1;
                   1664:     if (window.innerHeight) {
                   1665:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1666:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1667:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1668:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1669:     }
                   1670:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1671:         Geometry.getViewportHeight =
                   1672:             function() { return document.documentElement.clientHeight; };
                   1673:         Geometry.getViewportWidth =
                   1674:             function() { return document.documentElement.clientWidth; };
                   1675: 
                   1676:         Geometry.getHorizontalScroll =
                   1677:             function() { return document.documentElement.scrollLeft; };
                   1678:         Geometry.getVerticalScroll =
                   1679:             function() { return document.documentElement.scrollTop; };
                   1680:     }
                   1681:     else if (document.body.clientHeight) {
                   1682:         Geometry.getViewportHeight =
                   1683:             function() { return document.body.clientHeight; };
                   1684:         Geometry.getViewportWidth =
                   1685:             function() { return document.body.clientWidth; };
                   1686:         Geometry.getHorizontalScroll =
                   1687:             function() { return document.body.scrollLeft; };
                   1688:         Geometry.getVerticalScroll =
                   1689:             function() { return document.body.scrollTop; };
                   1690:     }
                   1691: }
                   1692: 
                   1693: GEOMETRY
                   1694: }
                   1695: 
                   1696: =pod
                   1697: 
1.648     raeburn  1698: =item * &viewport_size_js()
1.590     raeburn  1699: 
                   1700: 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. 
                   1701: 
                   1702: =cut
                   1703: 
                   1704: sub viewport_size_js {
                   1705:     my $geometry = &viewport_geometry_js();
                   1706:     return <<"DIMS";
                   1707: 
                   1708: $geometry
                   1709: 
                   1710: function getViewportDims(width,height) {
                   1711:     init_geometry();
                   1712:     width.value = Geometry.getViewportWidth();
                   1713:     height.value = Geometry.getViewportHeight();
                   1714:     return;
                   1715: }
                   1716: 
                   1717: DIMS
                   1718: }
                   1719: 
                   1720: =pod
                   1721: 
1.648     raeburn  1722: =item * &resize_textarea_js()
1.565     albertel 1723: 
                   1724: emits the needed javascript to resize a textarea to be as big as possible
                   1725: 
                   1726: creates a function resize_textrea that takes two IDs first should be
                   1727: the id of the element to resize, second should be the id of a div that
                   1728: surrounds everything that comes after the textarea, this routine needs
                   1729: to be attached to the <body> for the onload and onresize events.
                   1730: 
                   1731: =cut
                   1732: 
                   1733: sub resize_textarea_js {
1.590     raeburn  1734:     my $geometry = &viewport_geometry_js();
1.565     albertel 1735:     return <<"RESIZE";
                   1736:     <script type="text/javascript">
1.824     bisitz   1737: // <![CDATA[
1.590     raeburn  1738: $geometry
1.565     albertel 1739: 
1.588     albertel 1740: function getX(element) {
                   1741:     var x = 0;
                   1742:     while (element) {
                   1743: 	x += element.offsetLeft;
                   1744: 	element = element.offsetParent;
                   1745:     }
                   1746:     return x;
                   1747: }
                   1748: function getY(element) {
                   1749:     var y = 0;
                   1750:     while (element) {
                   1751: 	y += element.offsetTop;
                   1752: 	element = element.offsetParent;
                   1753:     }
                   1754:     return y;
                   1755: }
                   1756: 
                   1757: 
1.565     albertel 1758: function resize_textarea(textarea_id,bottom_id) {
                   1759:     init_geometry();
                   1760:     var textarea        = document.getElementById(textarea_id);
                   1761:     //alert(textarea);
                   1762: 
1.588     albertel 1763:     var textarea_top    = getY(textarea);
1.565     albertel 1764:     var textarea_height = textarea.offsetHeight;
                   1765:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1766:     var bottom_top      = getY(bottom);
1.565     albertel 1767:     var bottom_height   = bottom.offsetHeight;
                   1768:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1769:     var fudge           = 23;
1.565     albertel 1770:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1771:     if (new_height < 300) {
                   1772: 	new_height = 300;
                   1773:     }
                   1774:     textarea.style.height=new_height+'px';
                   1775: }
1.824     bisitz   1776: // ]]>
1.565     albertel 1777: </script>
                   1778: RESIZE
                   1779: 
                   1780: }
                   1781: 
1.1075.2.112  raeburn  1782: sub colorfuleditor_js {
                   1783:     return <<"COLORFULEDIT"
                   1784: <script type="text/javascript">
                   1785: // <![CDATA[>
                   1786:     function fold_box(curDepth, lastresource){
                   1787: 
                   1788:     // we need a list because there can be several blocks you need to fold in one tag
                   1789:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1790:     // but there is only one folding button per tag
                   1791:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1792: 
                   1793:         if(block.item(0).style.display == 'none'){
                   1794: 
                   1795:             foldbutton.value = '@{[&mt("Hide")]}';
                   1796:             for (i = 0; i < block.length; i++){
                   1797:                 block.item(i).style.display = '';
                   1798:             }
                   1799:         }else{
                   1800: 
                   1801:             foldbutton.value = '@{[&mt("Show")]}';
                   1802:             for (i = 0; i < block.length; i++){
                   1803:                 // block.item(i).style.visibility = 'collapse';
                   1804:                 block.item(i).style.display = 'none';
                   1805:             }
                   1806:         };
                   1807:         saveState(lastresource);
                   1808:     }
                   1809: 
                   1810:     function saveState (lastresource) {
                   1811: 
                   1812:         var tag_list = getTagList();
                   1813:         if(tag_list != null){
                   1814:             var timestamp = new Date().getTime();
                   1815:             var key = lastresource;
                   1816: 
                   1817:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1818:             // starting with timestamp
                   1819:             var value = timestamp+';';
                   1820: 
                   1821:             // building the list of key-value pairs
                   1822:             for(var i = 0; i < tag_list.length; i++){
                   1823:                 value += tag_list[i]+',';
                   1824:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1825:             }
                   1826: 
                   1827:             // only iterate whole storage if nothing to override
                   1828:             if(localStorage.getItem(key) == null){
                   1829: 
                   1830:                 // prevent storage from growing large
                   1831:                 if(localStorage.length > 50){
                   1832:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1833:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1834:                     var oldest_key;
                   1835: 
                   1836:                     for(var i = 1; i < localStorage.length; i++){
                   1837:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1838:                             oldest_key = localStorage.key(i);
                   1839:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1840:                         }
                   1841:                     }
                   1842:                     localStorage.removeItem(oldest_key);
                   1843:                 }
                   1844:             }
                   1845:             localStorage.setItem(key,value);
                   1846:         }
                   1847:     }
                   1848: 
                   1849:     // restore folding status of blocks (on page load)
                   1850:     function restoreState (lastresource) {
                   1851:         if(localStorage.getItem(lastresource) != null){
                   1852:             var key = lastresource;
                   1853:             var value = localStorage.getItem(key);
                   1854:             var regex_delTimestamp = /^\d+;/;
                   1855: 
                   1856:             value.replace(regex_delTimestamp, '');
                   1857: 
                   1858:             var valueArr = value.split(';');
                   1859:             var pairs;
                   1860:             var elements;
                   1861:             for (var i = 0; i < valueArr.length; i++){
                   1862:                 pairs = valueArr[i].split(',');
                   1863:                 elements = document.getElementsByName(pairs[0]);
                   1864: 
                   1865:                 for (var j = 0; j < elements.length; j++){
                   1866:                     elements[j].style.display = pairs[1];
                   1867:                     if (pairs[1] == "none"){
                   1868:                         var regex_id = /([_\\d]+)\$/;
                   1869:                         regex_id.exec(pairs[0]);
                   1870:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1871:                     }
                   1872:                 }
                   1873:             }
                   1874:         }
                   1875:     }
                   1876: 
                   1877:     function getTagList () {
                   1878: 
                   1879:         var stringToSearch = document.lonhomework.innerHTML;
                   1880: 
                   1881:         var ret = new Array();
                   1882:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1883:         var tag_list = stringToSearch.match(regex_findBlock);
                   1884: 
                   1885:         if(tag_list != null){
                   1886:             for(var i = 0; i < tag_list.length; i++){
                   1887:                 ret.push(tag_list[i].replace(/"/, ''));
                   1888:             }
                   1889:         }
                   1890:         return ret;
                   1891:     }
                   1892: 
                   1893:     function saveScrollPosition (resource) {
                   1894:         var tag_list = getTagList();
                   1895: 
                   1896:         // we dont always want to jump to the first block
                   1897:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1898:         if(\$(window).scrollTop() > 170){
                   1899:             if(tag_list != null){
                   1900:                 var result;
                   1901:                 for(var i = 0; i < tag_list.length; i++){
                   1902:                     if(isElementInViewport(tag_list[i])){
                   1903:                         result += tag_list[i]+';';
                   1904:                     }
                   1905:                 }
                   1906:                 sessionStorage.setItem('anchor_'+resource, result);
                   1907:             }
                   1908:         } else {
                   1909:             // we dont need to save zero, just delete the item to leave everything tidy
                   1910:             sessionStorage.removeItem('anchor_'+resource);
                   1911:         }
                   1912:     }
                   1913: 
                   1914:     function restoreScrollPosition(resource){
                   1915: 
                   1916:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1917:         if(elem != null){
                   1918:             var tag_list = elem.split(';');
                   1919:             var elem_list;
                   1920: 
                   1921:             for(var i = 0; i < tag_list.length; i++){
                   1922:                 elem_list = document.getElementsByName(tag_list[i]);
                   1923: 
                   1924:                 if(elem_list.length > 0){
                   1925:                     elem = elem_list[0];
                   1926:                     break;
                   1927:                 }
                   1928:             }
                   1929:             elem.scrollIntoView();
                   1930:         }
                   1931:     }
                   1932: 
                   1933:     function isElementInViewport(el) {
                   1934: 
                   1935:         // change to last element instead of first
                   1936:         var elem = document.getElementsByName(el);
                   1937:         var rect = elem[0].getBoundingClientRect();
                   1938: 
                   1939:         return (
                   1940:             rect.top >= 0 &&
                   1941:             rect.left >= 0 &&
                   1942:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1943:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1944:         );
                   1945:     }
                   1946: 
                   1947:     function autosize(depth){
                   1948:         var cmInst = window['cm'+depth];
                   1949:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1950: 
                   1951:         // is fixed size, switching to dynamic
                   1952:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1953:             cmInst.setSize("","auto");
                   1954:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1955:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1956: 
                   1957:         // is dynamic size, switching to fixed
                   1958:         } else {
                   1959:             cmInst.setSize("","300px");
                   1960:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1961:             sessionStorage.removeItem("autosized_"+depth);
                   1962:         }
                   1963:     }
                   1964: 
                   1965: 
                   1966: 
                   1967: // ]]>
                   1968: </script>
                   1969: COLORFULEDIT
                   1970: }
                   1971: 
                   1972: sub xmleditor_js {
                   1973:     return <<XMLEDIT
                   1974: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1975: <script type="text/javascript">
                   1976: // <![CDATA[>
                   1977: 
                   1978:     function saveScrollPosition (resource) {
                   1979: 
                   1980:         var scrollPos = \$(window).scrollTop();
                   1981:         sessionStorage.setItem(resource,scrollPos);
                   1982:     }
                   1983: 
                   1984:     function restoreScrollPosition(resource){
                   1985: 
                   1986:         var scrollPos = sessionStorage.getItem(resource);
                   1987:         \$(window).scrollTop(scrollPos);
                   1988:     }
                   1989: 
                   1990:     // unless internet explorer
                   1991:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1992: 
                   1993:         \$(document).ready(function() {
                   1994:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1995:         });
                   1996:     }
                   1997: 
                   1998:     // inserts text at cursor position into codemirror (xml editor only)
                   1999:     function insertText(text){
                   2000:         cm.focus();
                   2001:         var curPos = cm.getCursor();
                   2002:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2003:     }
                   2004: // ]]>
                   2005: </script>
                   2006: XMLEDIT
                   2007: }
                   2008: 
                   2009: sub insert_folding_button {
                   2010:     my $curDepth = $Apache::lonxml::curdepth;
                   2011:     my $lastresource = $env{'request.ambiguous'};
                   2012: 
                   2013:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   2014:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2015: }
                   2016: 
1.1075.2.161.  .21(raeb 2017:-24): =pod
                   2018:-24): 
                   2019:-24): =item * &iframe_wrapper_headjs()
                   2020:-24): 
                   2021:-24): emits javascript containing two global vars to facilitate handling of resizing
                   2022:-24): by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2023:-24): with standard LON-CAPA menus.
                   2024:-24): 
                   2025:-24): =cut
                   2026:-24): 
                   2027:-24): #
                   2028:-24): # Where iframe is in use, if window.onload() executes before the custom resize function
                   2029:-24): # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2030:-24): # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2031:-24): # do not obscure the Functions menu.
                   2032:-24): #
                   2033:-24): 
                   2034:-24): sub iframe_wrapper_headjs {
                   2035:-24):     return <<"ENDJS";
                   2036:-24): <script type="text/javascript">
                   2037:-24): // <![CDATA[
                   2038:-24): var LCnotready = 0;
                   2039:-24): var LCresizedef = 0;
                   2040:-24): // ]]>
                   2041:-24): </script>
                   2042:-24): 
                   2043:-24): ENDJS
                   2044:-24): 
                   2045:-24): }
                   2046:-24): 
                   2047:-24): =pod
                   2048:-24): 
                   2049:-24): =item * &iframe_wrapper_resizejs()
                   2050:-24): 
                   2051:-24): emits javascript used to handle resizing for a page containing
                   2052:-24): an iframe, to ensure that the iframe does not obscure any
                   2053:-24): standard LON-CAPA menu items.
                   2054:-24): 
                   2055:-24): =back
                   2056:-24): 
                   2057:-24): =cut
                   2058:-24): 
                   2059:-24): #
                   2060:-24): # jQuery to use when iframe is in use and a page resize occurs.
                   2061:-24): # This script will ensure that the iframe does not obscure any
                   2062:-24): # standard LON-CAPA inline menus (primary, secondary, and/or
                   2063:-24): # breadcrumbs and Functions menus. Expects javascript from
                   2064:-24): # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2065:-24): # e.g., by inclusion in second arg passed to &start_page().
                   2066:-24): #
                   2067:-24): 
                   2068:-24): sub iframe_wrapper_resizejs {
                   2069:-24):     my $offset = 5;
                   2070:-24):     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2071:-24):     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2072:-24):         $offset = 0;
                   2073:-24):     }
                   2074:-24):     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2075:-24):     \$(document).ready( function() {
                   2076:-24):         \$(window).unbind('resize').resize(function(){
                   2077:-24):             var header = null;
                   2078:-24):             var offset = $offset;
                   2079:-24):             var height = 0;
                   2080:-24):             var hdrtop = 0;
                   2081:-24):             if (\$('div.LC_menus_content:first').length) {
                   2082:-24):                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2083:-24):                     header = \$('div.LC_menus_content:first');
                   2084:-24):                     offset = 12;
                   2085:-24):                 }
                   2086:-24):             } else if (\$('div.LC_head_subbox:first').length) {
                   2087:-24):                 header = \$('div.LC_head_subbox:first');
                   2088:-24):                 offset = 9;
                   2089:-24):             } else {
                   2090:-24):                 if (\$('#LC_breadcrumbs').length) {
                   2091:-24):                     header = \$('#LC_breadcrumbs');
                   2092:-24):                 }
                   2093:-24):             }
                   2094:-24):             if (header != null && header.length) {
                   2095:-24):                 height = header.height();
                   2096:-24):                 hdrtop = header.position().top;
                   2097:-24):             }
                   2098:-24):             var pos = height + hdrtop + offset;
                   2099:-24):             \$('.LC_iframecontainer').css('top', pos);
                   2100:-24):         });
                   2101:-24):         LCresizedef = 1;
                   2102:-24):         if (LCnotready == 1) {
                   2103:-24):             LCnotready = 0;
                   2104:-24):             \$(window).trigger('resize');
                   2105:-24):         }
                   2106:-24):     });
                   2107:-24):     window.onload = function(){
                   2108:-24):          if (LCresizedef) {
                   2109:-24):              LCnotready = 0;
                   2110:-24):              \$(window).trigger('resize');
                   2111:-24):          } else {
                   2112:-24):              LCnotready = 1;
                   2113:-24):          }
                   2114:-24):     };
                   2115:-24): SCRIPT
                   2116:-24): 
                   2117:-24): }
1.1075.2.112  raeburn  2118: 
1.565     albertel 2119: =pod
                   2120: 
1.256     matthew  2121: =head1 Excel and CSV file utility routines
                   2122: 
                   2123: =cut
                   2124: 
                   2125: ###############################################################
                   2126: ###############################################################
                   2127: 
                   2128: =pod
                   2129: 
1.1075.2.56  raeburn  2130: =over 4
                   2131: 
1.648     raeburn  2132: =item * &csv_translate($text) 
1.37      matthew  2133: 
1.185     www      2134: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2135: format.
                   2136: 
                   2137: =cut
                   2138: 
1.180     matthew  2139: ###############################################################
                   2140: ###############################################################
1.37      matthew  2141: sub csv_translate {
                   2142:     my $text = shift;
                   2143:     $text =~ s/\"/\"\"/g;
1.209     albertel 2144:     $text =~ s/\n/ /g;
1.37      matthew  2145:     return $text;
                   2146: }
1.180     matthew  2147: 
                   2148: ###############################################################
                   2149: ###############################################################
                   2150: 
                   2151: =pod
                   2152: 
1.648     raeburn  2153: =item * &define_excel_formats()
1.180     matthew  2154: 
                   2155: Define some commonly used Excel cell formats.
                   2156: 
                   2157: Currently supported formats:
                   2158: 
                   2159: =over 4
                   2160: 
                   2161: =item header
                   2162: 
                   2163: =item bold
                   2164: 
                   2165: =item h1
                   2166: 
                   2167: =item h2
                   2168: 
                   2169: =item h3
                   2170: 
1.256     matthew  2171: =item h4
                   2172: 
                   2173: =item i
                   2174: 
1.180     matthew  2175: =item date
                   2176: 
                   2177: =back
                   2178: 
                   2179: Inputs: $workbook
                   2180: 
                   2181: Returns: $format, a hash reference.
                   2182: 
1.1057    foxr     2183: 
1.180     matthew  2184: =cut
                   2185: 
                   2186: ###############################################################
                   2187: ###############################################################
                   2188: sub define_excel_formats {
                   2189:     my ($workbook) = @_;
                   2190:     my $format;
                   2191:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2192:                                                 bottom    => 1,
                   2193:                                                 align     => 'center');
                   2194:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2195:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2196:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2197:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2198:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2199:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2200:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2201:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2202:     return $format;
                   2203: }
                   2204: 
                   2205: ###############################################################
                   2206: ###############################################################
1.113     bowersj2 2207: 
                   2208: =pod
                   2209: 
1.648     raeburn  2210: =item * &create_workbook()
1.255     matthew  2211: 
                   2212: Create an Excel worksheet.  If it fails, output message on the
                   2213: request object and return undefs.
                   2214: 
                   2215: Inputs: Apache request object
                   2216: 
                   2217: Returns (undef) on failure, 
                   2218:     Excel worksheet object, scalar with filename, and formats 
                   2219:     from &Apache::loncommon::define_excel_formats on success
                   2220: 
                   2221: =cut
                   2222: 
                   2223: ###############################################################
                   2224: ###############################################################
                   2225: sub create_workbook {
                   2226:     my ($r) = @_;
                   2227:         #
                   2228:     # Create the excel spreadsheet
                   2229:     my $filename = '/prtspool/'.
1.258     albertel 2230:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2231:         time.'_'.rand(1000000000).'.xls';
                   2232:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2233:     if (! defined($workbook)) {
                   2234:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2235:         $r->print(
                   2236:             '<p class="LC_error">'
                   2237:            .&mt('Problems occurred in creating the new Excel file.')
                   2238:            .' '.&mt('This error has been logged.')
                   2239:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2240:            .'</p>'
                   2241:         );
1.255     matthew  2242:         return (undef);
                   2243:     }
                   2244:     #
1.1014    foxr     2245:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2246:     #
                   2247:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2248:     return ($workbook,$filename,$format);
                   2249: }
                   2250: 
                   2251: ###############################################################
                   2252: ###############################################################
                   2253: 
                   2254: =pod
                   2255: 
1.648     raeburn  2256: =item * &create_text_file()
1.113     bowersj2 2257: 
1.542     raeburn  2258: Create a file to write to and eventually make available to the user.
1.256     matthew  2259: If file creation fails, outputs an error message on the request object and 
                   2260: return undefs.
1.113     bowersj2 2261: 
1.256     matthew  2262: Inputs: Apache request object, and file suffix
1.113     bowersj2 2263: 
1.256     matthew  2264: Returns (undef) on failure, 
                   2265:     Filehandle and filename on success.
1.113     bowersj2 2266: 
                   2267: =cut
                   2268: 
1.256     matthew  2269: ###############################################################
                   2270: ###############################################################
                   2271: sub create_text_file {
                   2272:     my ($r,$suffix) = @_;
                   2273:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2274:     my $fh;
                   2275:     my $filename = '/prtspool/'.
1.258     albertel 2276:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2277:         time.'_'.rand(1000000000).'.'.$suffix;
                   2278:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2279:     if (! defined($fh)) {
                   2280:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2281:         $r->print(
                   2282:             '<p class="LC_error">'
                   2283:            .&mt('Problems occurred in creating the output file.')
                   2284:            .' '.&mt('This error has been logged.')
                   2285:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2286:            .'</p>'
                   2287:         );
1.113     bowersj2 2288:     }
1.256     matthew  2289:     return ($fh,$filename)
1.113     bowersj2 2290: }
                   2291: 
                   2292: 
1.256     matthew  2293: =pod 
1.113     bowersj2 2294: 
                   2295: =back
                   2296: 
                   2297: =cut
1.37      matthew  2298: 
                   2299: ###############################################################
1.33      matthew  2300: ##        Home server <option> list generating code          ##
                   2301: ###############################################################
1.35      matthew  2302: 
1.169     www      2303: # ------------------------------------------
                   2304: 
                   2305: sub domain_select {
                   2306:     my ($name,$value,$multiple)=@_;
                   2307:     my %domains=map { 
1.514     albertel 2308: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2309:     } &Apache::lonnet::all_domains();
1.169     www      2310:     if ($multiple) {
                   2311: 	$domains{''}=&mt('Any domain');
1.550     albertel 2312: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2313: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2314:     } else {
1.550     albertel 2315: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2316: 	return &select_form($name,$value,\%domains);
1.169     www      2317:     }
                   2318: }
                   2319: 
1.282     albertel 2320: #-------------------------------------------
                   2321: 
                   2322: =pod
                   2323: 
1.519     raeburn  2324: =head1 Routines for form select boxes
                   2325: 
                   2326: =over 4
                   2327: 
1.648     raeburn  2328: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2329: 
                   2330: Returns a string containing a <select> element int multiple mode
                   2331: 
                   2332: 
                   2333: Args:
                   2334:   $name - name of the <select> element
1.506     raeburn  2335:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2336:   $size - number of rows long the select element is
1.283     albertel 2337:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2338:           (shown text should already have been &mt())
1.506     raeburn  2339:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2340: 
1.282     albertel 2341: =cut
                   2342: 
                   2343: #-------------------------------------------
1.169     www      2344: sub multiple_select_form {
1.284     albertel 2345:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2346:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2347:     my $output='';
1.191     matthew  2348:     if (! defined($size)) {
                   2349:         $size = 4;
1.283     albertel 2350:         if (scalar(keys(%$hash))<4) {
                   2351:             $size = scalar(keys(%$hash));
1.191     matthew  2352:         }
                   2353:     }
1.734     bisitz   2354:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2355:     my @order;
1.506     raeburn  2356:     if (ref($order) eq 'ARRAY')  {
                   2357:         @order = @{$order};
                   2358:     } else {
                   2359:         @order = sort(keys(%$hash));
1.501     banghart 2360:     }
                   2361:     if (exists($$hash{'select_form_order'})) {
                   2362:         @order = @{$$hash{'select_form_order'}};
                   2363:     }
                   2364:         
1.284     albertel 2365:     foreach my $key (@order) {
1.356     albertel 2366:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2367:         $output.='selected="selected" ' if ($selected{$key});
                   2368:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2369:     }
                   2370:     $output.="</select>\n";
                   2371:     return $output;
                   2372: }
                   2373: 
1.88      www      2374: #-------------------------------------------
                   2375: 
                   2376: =pod
                   2377: 
1.1075.2.115  raeburn  2378: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2379: 
                   2380: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2381: allow a user to select options from a ref to a hash containing:
                   2382: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2383: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2384: An optional arg -- $readonly -- if true will cause the select form
                   2385: to be disabled, e.g., for the case where an instructor has a section-
                   2386: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2387: 
1.88      www      2388: See lonrights.pm for an example invocation and use.
                   2389: 
                   2390: =cut
                   2391: 
                   2392: #-------------------------------------------
                   2393: sub select_form {
1.1075.2.115  raeburn  2394:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2395:     return unless (ref($hashref) eq 'HASH');
                   2396:     if ($onchange) {
                   2397:         $onchange = ' onchange="'.$onchange.'"';
                   2398:     }
1.1075.2.129  raeburn  2399:     my $disabled;
                   2400:     if ($readonly) {
                   2401:         $disabled = ' disabled="disabled"';
                   2402:     }
                   2403:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2404:     my @keys;
1.970     raeburn  2405:     if (exists($hashref->{'select_form_order'})) {
                   2406: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2407:     } else {
1.970     raeburn  2408: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2409:     }
1.356     albertel 2410:     foreach my $key (@keys) {
                   2411:         $selectform.=
                   2412: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2413:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2414:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2415:     }
                   2416:     $selectform.="</select>";
                   2417:     return $selectform;
                   2418: }
                   2419: 
1.475     www      2420: # For display filters
                   2421: 
                   2422: sub display_filter {
1.1074    raeburn  2423:     my ($context) = @_;
1.475     www      2424:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2425:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2426:     my $phraseinput = 'hidden';
                   2427:     my $includeinput = 'hidden';
                   2428:     my ($checked,$includetypestext);
                   2429:     if ($env{'form.displayfilter'} eq 'containing') {
                   2430:         $phraseinput = 'text'; 
                   2431:         if ($context eq 'parmslog') {
                   2432:             $includeinput = 'checkbox';
                   2433:             if ($env{'form.includetypes'}) {
                   2434:                 $checked = ' checked="checked"';
                   2435:             }
                   2436:             $includetypestext = &mt('Include parameter types');
                   2437:         }
                   2438:     } else {
                   2439:         $includetypestext = '&nbsp;';
                   2440:     }
                   2441:     my ($additional,$secondid,$thirdid);
                   2442:     if ($context eq 'parmslog') {
                   2443:         $additional = 
                   2444:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2445:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2446:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2447:             '</label>';
                   2448:         $secondid = 'includetypes';
                   2449:         $thirdid = 'includetypestext';
                   2450:     }
                   2451:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2452:                                                     '$secondid','$thirdid')";
                   2453:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2454: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2455: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2456: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2457:            &mt('Filter: [_1]',
1.477     www      2458: 	   &select_form($env{'form.displayfilter'},
                   2459: 			'displayfilter',
1.970     raeburn  2460: 			{'currentfolder' => 'Current folder/page',
1.477     www      2461: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2462: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2463: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2464:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2465:                          '" />'.$additional;
                   2466: }
                   2467: 
                   2468: sub display_filter_js {
                   2469:     my $includetext = &mt('Include parameter types');
                   2470:     return <<"ENDJS";
                   2471:   
                   2472: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2473:     var firstType = 'hidden';
                   2474:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2475:         firstType = 'text';
                   2476:     }
                   2477:     firstObject = document.getElementById(firstid);
                   2478:     if (typeof(firstObject) == 'object') {
                   2479:         if (firstObject.type != firstType) {
                   2480:             changeInputType(firstObject,firstType);
                   2481:         }
                   2482:     }
                   2483:     if (context == 'parmslog') {
                   2484:         var secondType = 'hidden';
                   2485:         if (firstType == 'text') {
                   2486:             secondType = 'checkbox';
                   2487:         }
                   2488:         secondObject = document.getElementById(secondid);  
                   2489:         if (typeof(secondObject) == 'object') {
                   2490:             if (secondObject.type != secondType) {
                   2491:                 changeInputType(secondObject,secondType);
                   2492:             }
                   2493:         }
                   2494:         var textItem = document.getElementById(thirdid);
                   2495:         var currtext = textItem.innerHTML;
                   2496:         var newtext;
                   2497:         if (firstType == 'text') {
                   2498:             newtext = '$includetext';
                   2499:         } else {
                   2500:             newtext = '&nbsp;';
                   2501:         }
                   2502:         if (currtext != newtext) {
                   2503:             textItem.innerHTML = newtext;
                   2504:         }
                   2505:     }
                   2506:     return;
                   2507: }
                   2508: 
                   2509: function changeInputType(oldObject,newType) {
                   2510:     var newObject = document.createElement('input');
                   2511:     newObject.type = newType;
                   2512:     if (oldObject.size) {
                   2513:         newObject.size = oldObject.size;
                   2514:     }
                   2515:     if (oldObject.value) {
                   2516:         newObject.value = oldObject.value;
                   2517:     }
                   2518:     if (oldObject.name) {
                   2519:         newObject.name = oldObject.name;
                   2520:     }
                   2521:     if (oldObject.id) {
                   2522:         newObject.id = oldObject.id;
                   2523:     }
                   2524:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2525:     return;
                   2526: }
                   2527: 
                   2528: ENDJS
1.475     www      2529: }
                   2530: 
1.167     www      2531: sub gradeleveldescription {
                   2532:     my $gradelevel=shift;
                   2533:     my %gradelevels=(0 => 'Not specified',
                   2534: 		     1 => 'Grade 1',
                   2535: 		     2 => 'Grade 2',
                   2536: 		     3 => 'Grade 3',
                   2537: 		     4 => 'Grade 4',
                   2538: 		     5 => 'Grade 5',
                   2539: 		     6 => 'Grade 6',
                   2540: 		     7 => 'Grade 7',
                   2541: 		     8 => 'Grade 8',
                   2542: 		     9 => 'Grade 9',
                   2543: 		     10 => 'Grade 10',
                   2544: 		     11 => 'Grade 11',
                   2545: 		     12 => 'Grade 12',
                   2546: 		     13 => 'Grade 13',
                   2547: 		     14 => '100 Level',
                   2548: 		     15 => '200 Level',
                   2549: 		     16 => '300 Level',
                   2550: 		     17 => '400 Level',
                   2551: 		     18 => 'Graduate Level');
                   2552:     return &mt($gradelevels{$gradelevel});
                   2553: }
                   2554: 
1.163     www      2555: sub select_level_form {
                   2556:     my ($deflevel,$name)=@_;
                   2557:     unless ($deflevel) { $deflevel=0; }
1.167     www      2558:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2559:     for (my $i=0; $i<=18; $i++) {
                   2560:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2561:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2562:                 ">".&gradeleveldescription($i)."</option>\n";
                   2563:     }
                   2564:     $selectform.="</select>";
                   2565:     return $selectform;
1.163     www      2566: }
1.167     www      2567: 
1.35      matthew  2568: #-------------------------------------------
                   2569: 
1.45      matthew  2570: =pod
                   2571: 
1.1075.2.115  raeburn  2572: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2573: 
                   2574: Returns a string containing a <select name='$name' size='1'> form to 
                   2575: allow a user to select the domain to preform an operation in.  
                   2576: See loncreateuser.pm for an example invocation and use.
                   2577: 
1.90      www      2578: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2579: selected");
                   2580: 
1.743     raeburn  2581: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2582: 
1.910     raeburn  2583: 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.
                   2584: 
1.1075.2.36  raeburn  2585: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2586: 
1.1075.2.115  raeburn  2587: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2588: 
                   2589: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2590: 
1.35      matthew  2591: =cut
                   2592: 
                   2593: #-------------------------------------------
1.34      matthew  2594: sub select_dom_form {
1.1075.2.115  raeburn  2595:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2596:     if ($onchange) {
1.874     raeburn  2597:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2598:     }
1.1075.2.115  raeburn  2599:     if ($disabled) {
                   2600:         $disabled = ' disabled="disabled"';
                   2601:     }
1.1075.2.36  raeburn  2602:     my (@domains,%exclude);
1.910     raeburn  2603:     if (ref($incdoms) eq 'ARRAY') {
                   2604:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2605:     } else {
                   2606:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2607:     }
1.90      www      2608:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2609:     if (ref($excdoms) eq 'ARRAY') {
                   2610:         map { $exclude{$_} = 1; } @{$excdoms};
                   2611:     }
1.1075.2.115  raeburn  2612:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2613:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2614:         next if ($exclude{$dom});
1.356     albertel 2615:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2616:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2617:         if ($showdomdesc) {
                   2618:             if ($dom ne '') {
                   2619:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2620:                 if ($domdesc ne '') {
                   2621:                     $selectdomain .= ' ('.$domdesc.')';
                   2622:                 }
                   2623:             } 
                   2624:         }
                   2625:         $selectdomain .= "</option>\n";
1.34      matthew  2626:     }
                   2627:     $selectdomain.="</select>";
                   2628:     return $selectdomain;
                   2629: }
                   2630: 
1.35      matthew  2631: #-------------------------------------------
                   2632: 
1.45      matthew  2633: =pod
                   2634: 
1.648     raeburn  2635: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2636: 
1.586     raeburn  2637: input: 4 arguments (two required, two optional) - 
                   2638:     $domain - domain of new user
                   2639:     $name - name of form element
                   2640:     $default - Value of 'default' causes a default item to be first 
                   2641:                             option, and selected by default. 
                   2642:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2643:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2644: output: returns 2 items: 
1.586     raeburn  2645: (a) form element which contains either:
                   2646:    (i) <select name="$name">
                   2647:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2648:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2649:        </select>
                   2650:        form item if there are multiple library servers in $domain, or
                   2651:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2652:        if there is only one library server in $domain.
                   2653: 
                   2654: (b) number of library servers found.
                   2655: 
                   2656: See loncreateuser.pm for example of use.
1.35      matthew  2657: 
                   2658: =cut
                   2659: 
                   2660: #-------------------------------------------
1.586     raeburn  2661: sub home_server_form_item {
                   2662:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2663:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2664:     my $result;
                   2665:     my $numlib = keys(%servers);
                   2666:     if ($numlib > 1) {
                   2667:         $result .= '<select name="'.$name.'" />'."\n";
                   2668:         if ($default) {
1.804     bisitz   2669:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2670:                        '</option>'."\n";
                   2671:         }
                   2672:         foreach my $hostid (sort(keys(%servers))) {
                   2673:             $result.= '<option value="'.$hostid.'">'.
                   2674: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2675:         }
                   2676:         $result .= '</select>'."\n";
                   2677:     } elsif ($numlib == 1) {
                   2678:         my $hostid;
                   2679:         foreach my $item (keys(%servers)) {
                   2680:             $hostid = $item;
                   2681:         }
                   2682:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2683:                    $hostid.'" />';
                   2684:                    if (!$hide) {
                   2685:                        $result .= $hostid.' '.$servers{$hostid};
                   2686:                    }
                   2687:                    $result .= "\n";
                   2688:     } elsif ($default) {
                   2689:         $result .= '<input type="hidden" name="'.$name.
                   2690:                    '" value="default" />';
                   2691:                    if (!$hide) {
                   2692:                        $result .= &mt('default');
                   2693:                    }
                   2694:                    $result .= "\n";
1.33      matthew  2695:     }
1.586     raeburn  2696:     return ($result,$numlib);
1.33      matthew  2697: }
1.112     bowersj2 2698: 
                   2699: =pod
                   2700: 
1.534     albertel 2701: =back 
                   2702: 
1.112     bowersj2 2703: =cut
1.87      matthew  2704: 
                   2705: ###############################################################
1.112     bowersj2 2706: ##                  Decoding User Agent                      ##
1.87      matthew  2707: ###############################################################
                   2708: 
                   2709: =pod
                   2710: 
1.112     bowersj2 2711: =head1 Decoding the User Agent
                   2712: 
                   2713: =over 4
                   2714: 
                   2715: =item * &decode_user_agent()
1.87      matthew  2716: 
                   2717: Inputs: $r
                   2718: 
                   2719: Outputs:
                   2720: 
                   2721: =over 4
                   2722: 
1.112     bowersj2 2723: =item * $httpbrowser
1.87      matthew  2724: 
1.112     bowersj2 2725: =item * $clientbrowser
1.87      matthew  2726: 
1.112     bowersj2 2727: =item * $clientversion
1.87      matthew  2728: 
1.112     bowersj2 2729: =item * $clientmathml
1.87      matthew  2730: 
1.112     bowersj2 2731: =item * $clientunicode
1.87      matthew  2732: 
1.112     bowersj2 2733: =item * $clientos
1.87      matthew  2734: 
1.1075.2.42  raeburn  2735: =item * $clientmobile
                   2736: 
                   2737: =item * $clientinfo
                   2738: 
1.1075.2.77  raeburn  2739: =item * $clientosversion
                   2740: 
1.87      matthew  2741: =back
                   2742: 
1.157     matthew  2743: =back 
                   2744: 
1.87      matthew  2745: =cut
                   2746: 
                   2747: ###############################################################
                   2748: ###############################################################
                   2749: sub decode_user_agent {
1.247     albertel 2750:     my ($r)=@_;
1.87      matthew  2751:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2752:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2753:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2754:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2755:     my $clientbrowser='unknown';
                   2756:     my $clientversion='0';
                   2757:     my $clientmathml='';
                   2758:     my $clientunicode='0';
1.1075.2.42  raeburn  2759:     my $clientmobile=0;
1.1075.2.77  raeburn  2760:     my $clientosversion='';
1.87      matthew  2761:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2762:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2763: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2764: 	    $clientbrowser=$bname;
                   2765:             $httpbrowser=~/$vreg/i;
                   2766: 	    $clientversion=$1;
                   2767:             $clientmathml=($clientversion>=$minv);
                   2768:             $clientunicode=($clientversion>=$univ);
                   2769: 	}
                   2770:     }
                   2771:     my $clientos='unknown';
1.1075.2.42  raeburn  2772:     my $clientinfo;
1.87      matthew  2773:     if (($httpbrowser=~/linux/i) ||
                   2774:         ($httpbrowser=~/unix/i) ||
                   2775:         ($httpbrowser=~/ux/i) ||
                   2776:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2777:     if (($httpbrowser=~/vax/i) ||
                   2778:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2779:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2780:     if (($httpbrowser=~/mac/i) ||
                   2781:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2782:     if ($httpbrowser=~/win/i) {
                   2783:         $clientos='win';
                   2784:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2785:             $clientosversion = $1;
                   2786:         }
                   2787:     }
1.87      matthew  2788:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2789:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2790:         $clientmobile=lc($1);
                   2791:     }
                   2792:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2793:         $clientinfo = 'firefox-'.$1;
                   2794:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2795:         $clientinfo = 'chromeframe-'.$1;
                   2796:     }
1.87      matthew  2797:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2798:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2799:             $clientosversion);
1.87      matthew  2800: }
                   2801: 
1.32      matthew  2802: ###############################################################
                   2803: ##    Authentication changing form generation subroutines    ##
                   2804: ###############################################################
                   2805: ##
                   2806: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2807: ## hash, and have reasonable default values.
                   2808: ##
                   2809: ##    formname = the name given in the <form> tag.
1.35      matthew  2810: #-------------------------------------------
                   2811: 
1.45      matthew  2812: =pod
                   2813: 
1.112     bowersj2 2814: =head1 Authentication Routines
                   2815: 
                   2816: =over 4
                   2817: 
1.648     raeburn  2818: =item * &authform_xxxxxx()
1.35      matthew  2819: 
                   2820: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2821: handle some of the conveniences required for authentication forms.  
                   2822: This is not an optimal method, but it works.  
                   2823: 
                   2824: =over 4
                   2825: 
1.112     bowersj2 2826: =item * authform_header
1.35      matthew  2827: 
1.112     bowersj2 2828: =item * authform_authorwarning
1.35      matthew  2829: 
1.112     bowersj2 2830: =item * authform_nochange
1.35      matthew  2831: 
1.112     bowersj2 2832: =item * authform_kerberos
1.35      matthew  2833: 
1.112     bowersj2 2834: =item * authform_internal
1.35      matthew  2835: 
1.112     bowersj2 2836: =item * authform_filesystem
1.35      matthew  2837: 
1.1075.2.161.  .17(raeb 2838:-23): =item * authform_lti
                   2839:-23): 
1.35      matthew  2840: =back
                   2841: 
1.648     raeburn  2842: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2843: 
1.35      matthew  2844: =cut
                   2845: 
                   2846: #-------------------------------------------
1.32      matthew  2847: sub authform_header{  
                   2848:     my %in = (
                   2849:         formname => 'cu',
1.80      albertel 2850:         kerb_def_dom => '',
1.32      matthew  2851:         @_,
                   2852:     );
                   2853:     $in{'formname'} = 'document.' . $in{'formname'};
                   2854:     my $result='';
1.80      albertel 2855: 
                   2856: #---------------------------------------------- Code for upper case translation
                   2857:     my $Javascript_toUpperCase;
                   2858:     unless ($in{kerb_def_dom}) {
                   2859:         $Javascript_toUpperCase =<<"END";
                   2860:         switch (choice) {
                   2861:            case 'krb': currentform.elements[choicearg].value =
                   2862:                currentform.elements[choicearg].value.toUpperCase();
                   2863:                break;
                   2864:            default:
                   2865:         }
                   2866: END
                   2867:     } else {
                   2868:         $Javascript_toUpperCase = "";
                   2869:     }
                   2870: 
1.165     raeburn  2871:     my $radioval = "'nochange'";
1.591     raeburn  2872:     if (defined($in{'curr_authtype'})) {
                   2873:         if ($in{'curr_authtype'} ne '') {
                   2874:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2875:         }
1.174     matthew  2876:     }
1.165     raeburn  2877:     my $argfield = 'null';
1.591     raeburn  2878:     if (defined($in{'mode'})) {
1.165     raeburn  2879:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2880:             if (defined($in{'curr_autharg'})) {
                   2881:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2882:                     $argfield = "'$in{'curr_autharg'}'";
                   2883:                 }
                   2884:             }
                   2885:         }
                   2886:     }
                   2887: 
1.32      matthew  2888:     $result.=<<"END";
                   2889: var current = new Object();
1.165     raeburn  2890: current.radiovalue = $radioval;
                   2891: current.argfield = $argfield;
1.32      matthew  2892: 
                   2893: function changed_radio(choice,currentform) {
                   2894:     var choicearg = choice + 'arg';
                   2895:     // If a radio button in changed, we need to change the argfield
                   2896:     if (current.radiovalue != choice) {
                   2897:         current.radiovalue = choice;
                   2898:         if (current.argfield != null) {
                   2899:             currentform.elements[current.argfield].value = '';
                   2900:         }
                   2901:         if (choice == 'nochange') {
                   2902:             current.argfield = null;
                   2903:         } else {
                   2904:             current.argfield = choicearg;
                   2905:             switch(choice) {
                   2906:                 case 'krb': 
                   2907:                     currentform.elements[current.argfield].value = 
                   2908:                         "$in{'kerb_def_dom'}";
                   2909:                 break;
                   2910:               default:
                   2911:                 break;
                   2912:             }
                   2913:         }
                   2914:     }
                   2915:     return;
                   2916: }
1.22      www      2917: 
1.32      matthew  2918: function changed_text(choice,currentform) {
                   2919:     var choicearg = choice + 'arg';
                   2920:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2921:         $Javascript_toUpperCase
1.32      matthew  2922:         // clear old field
                   2923:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2924:             currentform.elements[current.argfield].value = '';
                   2925:         }
                   2926:         current.argfield = choicearg;
                   2927:     }
                   2928:     set_auth_radio_buttons(choice,currentform);
                   2929:     return;
1.20      www      2930: }
1.32      matthew  2931: 
                   2932: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2933:     var numauthchoices = currentform.login.length;
                   2934:     if (typeof numauthchoices  == "undefined") {
                   2935:         return;
                   2936:     } 
1.32      matthew  2937:     var i=0;
1.986     raeburn  2938:     while (i < numauthchoices) {
1.32      matthew  2939:         if (currentform.login[i].value == newvalue) { break; }
                   2940:         i++;
                   2941:     }
1.986     raeburn  2942:     if (i == numauthchoices) {
1.32      matthew  2943:         return;
                   2944:     }
                   2945:     current.radiovalue = newvalue;
                   2946:     currentform.login[i].checked = true;
                   2947:     return;
                   2948: }
                   2949: END
                   2950:     return $result;
                   2951: }
                   2952: 
1.1075.2.20  raeburn  2953: sub authform_authorwarning {
1.32      matthew  2954:     my $result='';
1.144     matthew  2955:     $result='<i>'.
                   2956:         &mt('As a general rule, only authors or co-authors should be '.
                   2957:             'filesystem authenticated '.
                   2958:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2959:     return $result;
                   2960: }
                   2961: 
1.1075.2.20  raeburn  2962: sub authform_nochange {
1.32      matthew  2963:     my %in = (
                   2964:               formname => 'document.cu',
                   2965:               kerb_def_dom => 'MSU.EDU',
                   2966:               @_,
                   2967:           );
1.1075.2.20  raeburn  2968:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2969:     my $result;
1.1075.2.20  raeburn  2970:     if (!$authnum) {
                   2971:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2972:     } else {
                   2973:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2974:                   '<input type="radio" name="login" value="nochange" '.
                   2975:                   'checked="checked" onclick="'.
1.281     albertel 2976:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2977: 	    '</label>';
1.586     raeburn  2978:     }
1.32      matthew  2979:     return $result;
                   2980: }
                   2981: 
1.591     raeburn  2982: sub authform_kerberos {
1.32      matthew  2983:     my %in = (
                   2984:               formname => 'document.cu',
                   2985:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2986:               kerb_def_auth => 'krb4',
1.32      matthew  2987:               @_,
                   2988:               );
1.586     raeburn  2989:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2990:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2991:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2992:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2993:        $check5 = ' checked="checked"';
1.80      albertel 2994:     } else {
1.772     bisitz   2995:        $check4 = ' checked="checked"';
1.80      albertel 2996:     }
1.1075.2.117  raeburn  2997:     if ($in{'readonly'}) {
                   2998:         $disabled = ' disabled="disabled"';
                   2999:     }
1.165     raeburn  3000:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3001:     if (defined($in{'curr_authtype'})) {
                   3002:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3003:             $krbcheck = ' checked="checked"';
1.623     raeburn  3004:             if (defined($in{'mode'})) {
                   3005:                 if ($in{'mode'} eq 'modifyuser') {
                   3006:                     $krbcheck = '';
                   3007:                 }
                   3008:             }
1.591     raeburn  3009:             if (defined($in{'curr_kerb_ver'})) {
                   3010:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3011:                     $check5 = ' checked="checked"';
1.591     raeburn  3012:                     $check4 = '';
                   3013:                 } else {
1.772     bisitz   3014:                     $check4 = ' checked="checked"';
1.591     raeburn  3015:                     $check5 = '';
                   3016:                 }
1.586     raeburn  3017:             }
1.591     raeburn  3018:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3019:                 $krbarg = $in{'curr_autharg'};
                   3020:             }
1.586     raeburn  3021:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3022:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3023:                     $result = 
                   3024:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3025:         $in{'curr_autharg'},$krbver);
                   3026:                 } else {
                   3027:                     $result =
                   3028:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3029:                 }
                   3030:                 return $result; 
                   3031:             }
                   3032:         }
                   3033:     } else {
                   3034:         if ($authnum == 1) {
1.784     bisitz   3035:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3036:         }
                   3037:     }
1.586     raeburn  3038:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3039:         return;
1.587     raeburn  3040:     } elsif ($authtype eq '') {
1.591     raeburn  3041:         if (defined($in{'mode'})) {
1.587     raeburn  3042:             if ($in{'mode'} eq 'modifycourse') {
                   3043:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3044:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3045:                 }
                   3046:             }
                   3047:         }
1.586     raeburn  3048:     }
                   3049:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3050:     if ($authtype eq '') {
                   3051:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3052:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  3053:                     $krbcheck.$disabled.' />';
1.586     raeburn  3054:     }
                   3055:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  3056:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3057:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  3058:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3059:          $in{'curr_authtype'} eq 'krb4')) {
                   3060:         $result .= &mt
1.144     matthew  3061:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3062:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3063:          '<label>'.$authtype,
1.281     albertel 3064:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3065:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3066:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3067:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3068:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3069: 	 '</label>');
1.586     raeburn  3070:     } elsif ($can_assign{'krb4'}) {
                   3071:         $result .= &mt
                   3072:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3073:          '[_3] Version 4 [_4]',
                   3074:          '<label>'.$authtype,
                   3075:          '</label><input type="text" size="10" name="krbarg" '.
                   3076:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3077:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3078:          '<label><input type="hidden" name="krbver" value="4" />',
                   3079:          '</label>');
                   3080:     } elsif ($can_assign{'krb5'}) {
                   3081:         $result .= &mt
                   3082:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3083:          '[_3] Version 5 [_4]',
                   3084:          '<label>'.$authtype,
                   3085:          '</label><input type="text" size="10" name="krbarg" '.
                   3086:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  3087:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3088:          '<label><input type="hidden" name="krbver" value="5" />',
                   3089:          '</label>');
                   3090:     }
1.32      matthew  3091:     return $result;
                   3092: }
                   3093: 
1.1075.2.20  raeburn  3094: sub authform_internal {
1.586     raeburn  3095:     my %in = (
1.32      matthew  3096:                 formname => 'document.cu',
                   3097:                 kerb_def_dom => 'MSU.EDU',
                   3098:                 @_,
                   3099:                 );
1.1075.2.117  raeburn  3100:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3101:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3102:     if ($in{'readonly'}) {
                   3103:         $disabled = ' disabled="disabled"';
                   3104:     }
1.591     raeburn  3105:     if (defined($in{'curr_authtype'})) {
                   3106:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3107:             if ($can_assign{'int'}) {
1.772     bisitz   3108:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3109:                 if (defined($in{'mode'})) {
                   3110:                     if ($in{'mode'} eq 'modifyuser') {
                   3111:                         $intcheck = '';
                   3112:                     }
                   3113:                 }
1.591     raeburn  3114:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3115:                     $intarg = $in{'curr_autharg'};
                   3116:                 }
                   3117:             } else {
                   3118:                 $result = &mt('Currently internally authenticated.');
                   3119:                 return $result;
1.165     raeburn  3120:             }
                   3121:         }
1.586     raeburn  3122:     } else {
                   3123:         if ($authnum == 1) {
1.784     bisitz   3124:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3125:         }
                   3126:     }
                   3127:     if (!$can_assign{'int'}) {
                   3128:         return;
1.587     raeburn  3129:     } elsif ($authtype eq '') {
1.591     raeburn  3130:         if (defined($in{'mode'})) {
1.587     raeburn  3131:             if ($in{'mode'} eq 'modifycourse') {
                   3132:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3133:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3134:                 }
                   3135:             }
                   3136:         }
1.165     raeburn  3137:     }
1.586     raeburn  3138:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3139:     if ($authtype eq '') {
                   3140:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3141:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3142:     }
1.605     bisitz   3143:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3144:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3145:     $result = &mt
1.144     matthew  3146:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3147:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3148:     $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  3149:     return $result;
                   3150: }
                   3151: 
1.1075.2.20  raeburn  3152: sub authform_local {
1.32      matthew  3153:     my %in = (
                   3154:               formname => 'document.cu',
                   3155:               kerb_def_dom => 'MSU.EDU',
                   3156:               @_,
                   3157:               );
1.1075.2.117  raeburn  3158:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3159:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3160:     if ($in{'readonly'}) {
                   3161:         $disabled = ' disabled="disabled"';
                   3162:     }
1.591     raeburn  3163:     if (defined($in{'curr_authtype'})) {
                   3164:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3165:             if ($can_assign{'loc'}) {
1.772     bisitz   3166:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3167:                 if (defined($in{'mode'})) {
                   3168:                     if ($in{'mode'} eq 'modifyuser') {
                   3169:                         $loccheck = '';
                   3170:                     }
                   3171:                 }
1.591     raeburn  3172:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3173:                     $locarg = $in{'curr_autharg'};
                   3174:                 }
                   3175:             } else {
                   3176:                 $result = &mt('Currently using local (institutional) authentication.');
                   3177:                 return $result;
1.165     raeburn  3178:             }
                   3179:         }
1.586     raeburn  3180:     } else {
                   3181:         if ($authnum == 1) {
1.784     bisitz   3182:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3183:         }
                   3184:     }
                   3185:     if (!$can_assign{'loc'}) {
                   3186:         return;
1.587     raeburn  3187:     } elsif ($authtype eq '') {
1.591     raeburn  3188:         if (defined($in{'mode'})) {
1.587     raeburn  3189:             if ($in{'mode'} eq 'modifycourse') {
                   3190:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3191:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3192:                 }
                   3193:             }
                   3194:         }
1.165     raeburn  3195:     }
1.586     raeburn  3196:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3197:     if ($authtype eq '') {
                   3198:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3199:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3200:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3201:     }
                   3202:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3203:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3204:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3205:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3206:     return $result;
                   3207: }
                   3208: 
1.1075.2.20  raeburn  3209: sub authform_filesystem {
1.32      matthew  3210:     my %in = (
                   3211:               formname => 'document.cu',
                   3212:               kerb_def_dom => 'MSU.EDU',
                   3213:               @_,
                   3214:               );
1.1075.2.117  raeburn  3215:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3216:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3217:     if ($in{'readonly'}) {
                   3218:         $disabled = ' disabled="disabled"';
                   3219:     }
1.591     raeburn  3220:     if (defined($in{'curr_authtype'})) {
                   3221:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3222:             if ($can_assign{'fsys'}) {
1.772     bisitz   3223:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3224:                 if (defined($in{'mode'})) {
                   3225:                     if ($in{'mode'} eq 'modifyuser') {
                   3226:                         $fsyscheck = '';
                   3227:                     }
                   3228:                 }
1.586     raeburn  3229:             } else {
                   3230:                 $result = &mt('Currently Filesystem Authenticated.');
                   3231:                 return $result;
                   3232:             }           
                   3233:         }
                   3234:     } else {
                   3235:         if ($authnum == 1) {
1.784     bisitz   3236:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3237:         }
                   3238:     }
                   3239:     if (!$can_assign{'fsys'}) {
                   3240:         return;
1.587     raeburn  3241:     } elsif ($authtype eq '') {
1.591     raeburn  3242:         if (defined($in{'mode'})) {
1.587     raeburn  3243:             if ($in{'mode'} eq 'modifycourse') {
                   3244:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3245:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3246:                 }
                   3247:             }
                   3248:         }
1.586     raeburn  3249:     }
                   3250:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3251:     if ($authtype eq '') {
                   3252:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3253:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3254:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3255:     }
1.1075.2.158  raeburn  3256:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3257:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3258:     $result = &mt
1.144     matthew  3259:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3260:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3261:     return $result;
                   3262: }
                   3263: 
1.1075.2.161.  .17(raeb 3264:-23): sub authform_lti {
                   3265:-23):     my %in = (
                   3266:-23):               formname => 'document.cu',
                   3267:-23):               kerb_def_dom => 'MSU.EDU',
                   3268:-23):               @_,
                   3269:-23):               );
                   3270:-23):     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3271:-23):     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3272:-23):     if ($in{'readonly'}) {
                   3273:-23):         $disabled = ' disabled="disabled"';
                   3274:-23):     }
                   3275:-23):     if (defined($in{'curr_authtype'})) {
                   3276:-23):         if ($in{'curr_authtype'} eq 'lti') {
                   3277:-23):             if ($can_assign{'lti'}) {
                   3278:-23):                 $lticheck = 'checked="checked" ';
                   3279:-23):                 if (defined($in{'mode'})) {
                   3280:-23):                     if ($in{'mode'} eq 'modifyuser') {
                   3281:-23):                         $lticheck = '';
                   3282:-23):                     }
                   3283:-23):                 }
                   3284:-23):             } else {
                   3285:-23):                 $result = &mt('Currently LTI Authenticated.');
                   3286:-23):                 return $result;
                   3287:-23):             }
                   3288:-23):         }
                   3289:-23):     } else {
                   3290:-23):         if ($authnum == 1) {
                   3291:-23):             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3292:-23):         }
                   3293:-23):     }
                   3294:-23):     if (!$can_assign{'lti'}) {
                   3295:-23):         return;
                   3296:-23):     } elsif ($authtype eq '') {
                   3297:-23):         if (defined($in{'mode'})) {
                   3298:-23):             if ($in{'mode'} eq 'modifycourse') {
                   3299:-23):                 if ($authnum == 1) {
                   3300:-23):                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3301:-23):                 }
                   3302:-23):             }
                   3303:-23):         }
                   3304:-23):     }
                   3305:-23):     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3306:-23):     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3307:-23):         $authtype = '<input type="radio" name="login" value="lti" '.
                   3308:-23):                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3309:-23):                     $jscall.'"'.$disabled.' />';
                   3310:-23):     }
                   3311:-23):     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3312:-23):     if ($authtype) {
                   3313:-23):         $result = &mt('[_1] LTI Authenticated',
                   3314:-23):                       '<label>'.$authtype.'</label>'.$autharg);
                   3315:-23):     } else {
                   3316:-23):         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3317:-23):                   $autharg;
                   3318:-23):     }
                   3319:-23):     return $result;
                   3320:-23): }
                   3321:-23): 
1.586     raeburn  3322: sub get_assignable_auth {
                   3323:     my ($dom) = @_;
                   3324:     if ($dom eq '') {
                   3325:         $dom = $env{'request.role.domain'};
                   3326:     }
                   3327:     my %can_assign = (
                   3328:                           krb4 => 1,
                   3329:                           krb5 => 1,
                   3330:                           int  => 1,
                   3331:                           loc  => 1,
                   3332:                      );
                   3333:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3334:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3335:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3336:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3337:             my $context;
                   3338:             if ($env{'request.role'} =~ /^au/) {
                   3339:                 $context = 'author';
1.1075.2.117  raeburn  3340:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3341:                 $context = 'domain';
                   3342:             } elsif ($env{'request.course.id'}) {
                   3343:                 $context = 'course';
                   3344:             }
                   3345:             if ($context) {
                   3346:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3347:                    %can_assign = %{$authhash->{$context}}; 
                   3348:                 }
                   3349:             }
                   3350:         }
                   3351:     }
                   3352:     my $authnum = 0;
                   3353:     foreach my $key (keys(%can_assign)) {
                   3354:         if ($can_assign{$key}) {
                   3355:             $authnum ++;
                   3356:         }
                   3357:     }
                   3358:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3359:         $authnum --;
                   3360:     }
                   3361:     return ($authnum,%can_assign);
                   3362: }
                   3363: 
1.1075.2.137  raeburn  3364: sub check_passwd_rules {
                   3365:     my ($domain,$plainpass) = @_;
                   3366:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3367:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3368:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3369:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3370:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3371:             if ($passwdconf{'min'} > $min) {
                   3372:                 $min = $passwdconf{'min'};
                   3373:             }
1.1075.2.137  raeburn  3374:         }
                   3375:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3376:             $max = $passwdconf{'max'};
                   3377:         }
                   3378:         @chars = @{$passwdconf{'chars'}};
                   3379:     }
                   3380:     if (($min) && (length($plainpass) < $min)) {
                   3381:         push(@brokerule,'min');
                   3382:     }
                   3383:     if (($max) && (length($plainpass) > $max)) {
                   3384:         push(@brokerule,'max');
                   3385:     }
                   3386:     if (@chars) {
                   3387:         my %rules;
                   3388:         map { $rules{$_} = 1; } @chars;
                   3389:         if ($rules{'uc'}) {
                   3390:             unless ($plainpass =~ /[A-Z]/) {
                   3391:                 push(@brokerule,'uc');
                   3392:             }
                   3393:         }
                   3394:         if ($rules{'lc'}) {
                   3395:             unless ($plainpass =~ /[a-z]/) {
                   3396:                 push(@brokerule,'lc');
                   3397:             }
                   3398:         }
                   3399:         if ($rules{'num'}) {
                   3400:             unless ($plainpass =~ /\d/) {
                   3401:                 push(@brokerule,'num');
                   3402:             }
                   3403:         }
                   3404:         if ($rules{'spec'}) {
                   3405:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3406:                 push(@brokerule,'spec');
                   3407:             }
                   3408:         }
                   3409:     }
                   3410:     if (@brokerule) {
                   3411:         my %rulenames = &Apache::lonlocal::texthash(
                   3412:             uc   => 'At least one upper case letter',
                   3413:             lc   => 'At least one lower case letter',
                   3414:             num  => 'At least one number',
                   3415:             spec => 'At least one non-alphanumeric',
                   3416:         );
                   3417:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3418:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3419:         $rulenames{'num'} .= ': 0123456789';
                   3420:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3421:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3422:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3423:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3424:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3425:             if (grep(/^$rule$/,@brokerule)) {
                   3426:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3427:             }
                   3428:         }
                   3429:         $warning .= '</ul>';
                   3430:     }
                   3431:     if (wantarray) {
                   3432:         return @brokerule;
                   3433:     }
                   3434:     return $warning;
                   3435: }
                   3436: 
1.1075.2.161.  .5(raebu 3437:22): sub passwd_validation_js {
                   3438:22):     my ($currpasswdval,$domain,$context,$id) = @_;
                   3439:22):     my (%passwdconf,$alertmsg);
                   3440:22):     if ($context eq 'linkprot') {
                   3441:22):         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3442:22):         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3443:22):             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3444:22):                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3445:22):             }
                   3446:22):         }
                   3447:22):         if ($id eq 'add') {
                   3448:22):             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3449:22):         } elsif ($id =~ /^\d+$/) {
                   3450:22):             my $pos = $id+1;
                   3451:22):             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3452:22):         } else {
                   3453:22):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3454:22):         }
          .27(raeb 3455:-24):     } elsif ($context eq 'ltitools') {
                   3456:-24):         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3457:-24):         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3458:-24):             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3459:-24):                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3460:-24):             }
                   3461:-24):         }
                   3462:-24):         if ($id eq 'add') {
                   3463:-24):             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3464:-24):         } elsif ($id =~ /^\d+$/) {
                   3465:-24):             my $pos = $id+1;
                   3466:-24):             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3467:-24):         } else {
                   3468:-24):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3469:-24):         }
          .5(raebu 3470:22):     } else {
                   3471:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3472:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3473:22):     }
                   3474:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3475:22):     $numrules = 0;
                   3476:22):     $min = $Apache::lonnet::passwdmin;
                   3477:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3478:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3479:22):             if ($passwdconf{'min'} > $min) {
                   3480:22):                 $min = $passwdconf{'min'};
                   3481:22):             }
                   3482:22):         }
                   3483:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3484:22):             $max = $passwdconf{'max'};
                   3485:22):             $numrules ++;
                   3486:22):         }
                   3487:22):         @chars = @{$passwdconf{'chars'}};
                   3488:22):         if (@chars) {
                   3489:22):             $numrules ++;
                   3490:22):         }
                   3491:22):     }
                   3492:22):     if ($min > 0) {
                   3493:22):         $numrules ++;
                   3494:22):     }
                   3495:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3496:22):         if ($min) {
                   3497:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3498:22):         }
                   3499:22):         if ($max) {
                   3500:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3501:22):         }
                   3502:22):         my (@charalerts,@charrules);
                   3503:22):         if (@chars) {
                   3504:22):             if (grep(/^uc$/,@chars)) {
                   3505:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3506:22):                 push(@charrules,'uc');
                   3507:22):             }
                   3508:22):             if (grep(/^lc$/,@chars)) {
                   3509:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3510:22):                 push(@charrules,'lc');
                   3511:22):             }
                   3512:22):             if (grep(/^num$/,@chars)) {
                   3513:22):                 push(@charalerts,&mt('contain at least one number'));
                   3514:22):                 push(@charrules,'num');
                   3515:22):             }
                   3516:22):             if (grep(/^spec$/,@chars)) {
                   3517:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3518:22):                 push(@charrules,'spec');
                   3519:22):             }
                   3520:22):         }
                   3521:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3522:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3523:22):             if ($min) {
                   3524:22):                 $intargjs .= qq|
                   3525:22):             if (currpwval.length < $min) {
                   3526:22):                 rulesmsg += ' - $alert{min}';
                   3527:22):             }
                   3528:22): |;
                   3529:22):             }
                   3530:22):             if ($max) {
                   3531:22):                 $intargjs .= qq|
                   3532:22):             if (currpwval.length > $max) {
                   3533:22):                 rulesmsg += ' - $alert{max}';
                   3534:22):             }
                   3535:22): |;
                   3536:22):             }
                   3537:22):             if (@chars > 0) {
                   3538:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3539:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3540:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3541:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3542:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3543:22):                 my %rules;
                   3544:22):                 map { $rules{$_} = 1; } @chars;
                   3545:22):                 if ($rules{'uc'}) {
                   3546:22):                     $intargjs .= qq|
                   3547:22):             var ucRegExp = /[A-Z]/;
                   3548:22):             if (!ucRegExp.test(currpwval)) {
                   3549:22):                 brokerules.push('uc');
                   3550:22):             }
                   3551:22): |;
                   3552:22):                 }
                   3553:22):                 if ($rules{'lc'}) {
                   3554:22):                     $intargjs .= qq|
                   3555:22):             var lcRegExp = /[a-z]/;
                   3556:22):             if (!lcRegExp.test(currpwval)) {
                   3557:22):                 brokerules.push('lc');
                   3558:22):             }
                   3559:22): |;
                   3560:22):                 }
                   3561:22):                 if ($rules{'num'}) {
                   3562:22):                      $intargjs .= qq|
                   3563:22):             var numRegExp = /[0-9]/;
                   3564:22):             if (!numRegExp.test(currpwval)) {
                   3565:22):                 brokerules.push('num');
                   3566:22):             }
                   3567:22): |;
                   3568:22):                 }
                   3569:22):                 if ($rules{'spec'}) {
                   3570:22):                      $intargjs .= q|
                   3571:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3572:22):             if (!specRegExp.test(currpwval)) {
                   3573:22):                 brokerules.push('spec');
                   3574:22):             }
                   3575:22): |;
                   3576:22):                 }
                   3577:22):                 $intargjs .= qq|
                   3578:22):             if (brokerules.length > 0) {
                   3579:22):                 for (var i=0; i<brokerules.length; i++) {
                   3580:22):                     for (var j=0; j<charrules.length; j++) {
                   3581:22):                         if (brokerules[i] == charrules[j]) {
                   3582:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3583:22):                             break;
                   3584:22):                         }
                   3585:22):                     }
                   3586:22):                 }
                   3587:22):             }
                   3588:22): |;
                   3589:22):             }
                   3590:22):             $intargjs .= qq|
                   3591:22):             if (rulesmsg != '') {
                   3592:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3593:22):                 alert(rulesmsg);
                   3594:22):                 return false;
                   3595:22):             }
                   3596:22): |;
                   3597:22):     }
                   3598:22):     return ($numrules,$intargjs);
                   3599:22): }
                   3600:22): 
1.80      albertel 3601: ###############################################################
                   3602: ##    Get Kerberos Defaults for Domain                 ##
                   3603: ###############################################################
                   3604: ##
                   3605: ## Returns default kerberos version and an associated argument
                   3606: ## as listed in file domain.tab. If not listed, provides
                   3607: ## appropriate default domain and kerberos version.
                   3608: ##
                   3609: #-------------------------------------------
                   3610: 
                   3611: =pod
                   3612: 
1.648     raeburn  3613: =item * &get_kerberos_defaults()
1.80      albertel 3614: 
                   3615: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3616: version and domain. If not found, it defaults to version 4 and the 
                   3617: domain of the server.
1.80      albertel 3618: 
1.648     raeburn  3619: =over 4
                   3620: 
1.80      albertel 3621: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3622: 
1.648     raeburn  3623: =back
                   3624: 
                   3625: =back
                   3626: 
1.80      albertel 3627: =cut
                   3628: 
                   3629: #-------------------------------------------
                   3630: sub get_kerberos_defaults {
                   3631:     my $domain=shift;
1.641     raeburn  3632:     my ($krbdef,$krbdefdom);
                   3633:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3634:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3635:         $krbdef = $domdefaults{'auth_def'};
                   3636:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3637:     } else {
1.80      albertel 3638:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3639:         my $krbdefdom=$1;
                   3640:         $krbdefdom=~tr/a-z/A-Z/;
                   3641:         $krbdef = "krb4";
                   3642:     }
                   3643:     return ($krbdef,$krbdefdom);
                   3644: }
1.112     bowersj2 3645: 
1.32      matthew  3646: 
1.46      matthew  3647: ###############################################################
                   3648: ##                Thesaurus Functions                        ##
                   3649: ###############################################################
1.20      www      3650: 
1.46      matthew  3651: =pod
1.20      www      3652: 
1.112     bowersj2 3653: =head1 Thesaurus Functions
                   3654: 
                   3655: =over 4
                   3656: 
1.648     raeburn  3657: =item * &initialize_keywords()
1.46      matthew  3658: 
                   3659: Initializes the package variable %Keywords if it is empty.  Uses the
                   3660: package variable $thesaurus_db_file.
                   3661: 
                   3662: =cut
                   3663: 
                   3664: ###################################################
                   3665: 
                   3666: sub initialize_keywords {
                   3667:     return 1 if (scalar keys(%Keywords));
                   3668:     # If we are here, %Keywords is empty, so fill it up
                   3669:     #   Make sure the file we need exists...
                   3670:     if (! -e $thesaurus_db_file) {
                   3671:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3672:                                  " failed because it does not exist");
                   3673:         return 0;
                   3674:     }
                   3675:     #   Set up the hash as a database
                   3676:     my %thesaurus_db;
                   3677:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3678:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3679:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3680:                                  $thesaurus_db_file);
                   3681:         return 0;
                   3682:     } 
                   3683:     #  Get the average number of appearances of a word.
                   3684:     my $avecount = $thesaurus_db{'average.count'};
                   3685:     #  Put keywords (those that appear > average) into %Keywords
                   3686:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3687:         my ($count,undef) = split /:/,$data;
                   3688:         $Keywords{$word}++ if ($count > $avecount);
                   3689:     }
                   3690:     untie %thesaurus_db;
                   3691:     # Remove special values from %Keywords.
1.356     albertel 3692:     foreach my $value ('total.count','average.count') {
                   3693:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3694:   }
1.46      matthew  3695:     return 1;
                   3696: }
                   3697: 
                   3698: ###################################################
                   3699: 
                   3700: =pod
                   3701: 
1.648     raeburn  3702: =item * &keyword($word)
1.46      matthew  3703: 
                   3704: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3705: than the average number of times in the thesaurus database.  Calls 
                   3706: &initialize_keywords
                   3707: 
                   3708: =cut
                   3709: 
                   3710: ###################################################
1.20      www      3711: 
                   3712: sub keyword {
1.46      matthew  3713:     return if (!&initialize_keywords());
                   3714:     my $word=lc(shift());
                   3715:     $word=~s/\W//g;
                   3716:     return exists($Keywords{$word});
1.20      www      3717: }
1.46      matthew  3718: 
                   3719: ###############################################################
                   3720: 
                   3721: =pod 
1.20      www      3722: 
1.648     raeburn  3723: =item * &get_related_words()
1.46      matthew  3724: 
1.160     matthew  3725: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3726: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3727: will be returned.  The order of the words returned is determined by the
                   3728: database which holds them.
                   3729: 
                   3730: Uses global $thesaurus_db_file.
                   3731: 
1.1057    foxr     3732: 
1.46      matthew  3733: =cut
                   3734: 
                   3735: ###############################################################
                   3736: sub get_related_words {
                   3737:     my $keyword = shift;
                   3738:     my %thesaurus_db;
                   3739:     if (! -e $thesaurus_db_file) {
                   3740:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3741:                                  "failed because the file does not exist");
                   3742:         return ();
                   3743:     }
                   3744:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3745:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3746:         return ();
                   3747:     } 
                   3748:     my @Words=();
1.429     www      3749:     my $count=0;
1.46      matthew  3750:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3751: 	# The first element is the number of times
                   3752: 	# the word appears.  We do not need it now.
1.429     www      3753: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3754: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3755: 	my $threshold=$mostfrequentcount/10;
                   3756:         foreach my $possibleword (@RelatedWords) {
                   3757:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3758:             if ($wordcount>$threshold) {
                   3759: 		push(@Words,$word);
                   3760:                 $count++;
                   3761:                 if ($count>10) { last; }
                   3762: 	    }
1.20      www      3763:         }
                   3764:     }
1.46      matthew  3765:     untie %thesaurus_db;
                   3766:     return @Words;
1.14      harris41 3767: }
1.46      matthew  3768: 
1.112     bowersj2 3769: =pod
                   3770: 
                   3771: =back
                   3772: 
                   3773: =cut
1.61      www      3774: 
                   3775: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3776: =pod
                   3777: 
1.112     bowersj2 3778: =head1 User Name Functions
                   3779: 
                   3780: =over 4
                   3781: 
1.648     raeburn  3782: =item * &plainname($uname,$udom,$first)
1.81      albertel 3783: 
1.112     bowersj2 3784: Takes a users logon name and returns it as a string in
1.226     albertel 3785: "first middle last generation" form 
                   3786: if $first is set to 'lastname' then it returns it as
                   3787: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3788: 
                   3789: =cut
1.61      www      3790: 
1.295     www      3791: 
1.81      albertel 3792: ###############################################################
1.61      www      3793: sub plainname {
1.226     albertel 3794:     my ($uname,$udom,$first)=@_;
1.537     albertel 3795:     return if (!defined($uname) || !defined($udom));
1.295     www      3796:     my %names=&getnames($uname,$udom);
1.226     albertel 3797:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3798: 					  $names{'middlename'},
                   3799: 					  $names{'lastname'},
                   3800: 					  $names{'generation'},$first);
                   3801:     $name=~s/^\s+//;
1.62      www      3802:     $name=~s/\s+$//;
                   3803:     $name=~s/\s+/ /g;
1.353     albertel 3804:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3805:     return $name;
1.61      www      3806: }
1.66      www      3807: 
                   3808: # -------------------------------------------------------------------- Nickname
1.81      albertel 3809: =pod
                   3810: 
1.648     raeburn  3811: =item * &nickname($uname,$udom)
1.81      albertel 3812: 
                   3813: Gets a users name and returns it as a string as
                   3814: 
                   3815: "&quot;nickname&quot;"
1.66      www      3816: 
1.81      albertel 3817: if the user has a nickname or
                   3818: 
                   3819: "first middle last generation"
                   3820: 
                   3821: if the user does not
                   3822: 
                   3823: =cut
1.66      www      3824: 
                   3825: sub nickname {
                   3826:     my ($uname,$udom)=@_;
1.537     albertel 3827:     return if (!defined($uname) || !defined($udom));
1.295     www      3828:     my %names=&getnames($uname,$udom);
1.68      albertel 3829:     my $name=$names{'nickname'};
1.66      www      3830:     if ($name) {
                   3831:        $name='&quot;'.$name.'&quot;'; 
                   3832:     } else {
                   3833:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3834: 	     $names{'lastname'}.' '.$names{'generation'};
                   3835:        $name=~s/\s+$//;
                   3836:        $name=~s/\s+/ /g;
                   3837:     }
                   3838:     return $name;
                   3839: }
                   3840: 
1.295     www      3841: sub getnames {
                   3842:     my ($uname,$udom)=@_;
1.537     albertel 3843:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3844:     if ($udom eq 'public' && $uname eq 'public') {
                   3845: 	return ('lastname' => &mt('Public'));
                   3846:     }
1.295     www      3847:     my $id=$uname.':'.$udom;
                   3848:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3849:     if ($cached) {
                   3850: 	return %{$names};
                   3851:     } else {
                   3852: 	my %loadnames=&Apache::lonnet::get('environment',
                   3853:                     ['firstname','middlename','lastname','generation','nickname'],
                   3854: 					 $udom,$uname);
                   3855: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3856: 	return %loadnames;
                   3857:     }
                   3858: }
1.61      www      3859: 
1.542     raeburn  3860: # -------------------------------------------------------------------- getemails
1.648     raeburn  3861: 
1.542     raeburn  3862: =pod
                   3863: 
1.648     raeburn  3864: =item * &getemails($uname,$udom)
1.542     raeburn  3865: 
                   3866: Gets a user's email information and returns it as a hash with keys:
                   3867: notification, critnotification, permanentemail
                   3868: 
                   3869: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3870: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3871:  
1.648     raeburn  3872: 
1.542     raeburn  3873: =cut
                   3874: 
1.648     raeburn  3875: 
1.466     albertel 3876: sub getemails {
                   3877:     my ($uname,$udom)=@_;
                   3878:     if ($udom eq 'public' && $uname eq 'public') {
                   3879: 	return;
                   3880:     }
1.467     www      3881:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3882:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3883:     my $id=$uname.':'.$udom;
                   3884:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3885:     if ($cached) {
                   3886: 	return %{$names};
                   3887:     } else {
                   3888: 	my %loadnames=&Apache::lonnet::get('environment',
                   3889:                     			   ['notification','critnotification',
                   3890: 					    'permanentemail'],
                   3891: 					   $udom,$uname);
                   3892: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3893: 	return %loadnames;
                   3894:     }
                   3895: }
                   3896: 
1.551     albertel 3897: sub flush_email_cache {
                   3898:     my ($uname,$udom)=@_;
                   3899:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3900:     if (!$uname) { $uname=$env{'user.name'};   }
                   3901:     return if ($udom eq 'public' && $uname eq 'public');
                   3902:     my $id=$uname.':'.$udom;
                   3903:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3904: }
                   3905: 
1.728     raeburn  3906: # -------------------------------------------------------------------- getlangs
                   3907: 
                   3908: =pod
                   3909: 
                   3910: =item * &getlangs($uname,$udom)
                   3911: 
                   3912: Gets a user's language preference and returns it as a hash with key:
                   3913: language.
                   3914: 
                   3915: =cut
                   3916: 
                   3917: 
                   3918: sub getlangs {
                   3919:     my ($uname,$udom) = @_;
                   3920:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3921:     if (!$uname) { $uname=$env{'user.name'};   }
                   3922:     my $id=$uname.':'.$udom;
                   3923:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3924:     if ($cached) {
                   3925:         return %{$langs};
                   3926:     } else {
                   3927:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3928:                                            $udom,$uname);
                   3929:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3930:         return %loadlangs;
                   3931:     }
                   3932: }
                   3933: 
                   3934: sub flush_langs_cache {
                   3935:     my ($uname,$udom)=@_;
                   3936:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3937:     if (!$uname) { $uname=$env{'user.name'};   }
                   3938:     return if ($udom eq 'public' && $uname eq 'public');
                   3939:     my $id=$uname.':'.$udom;
                   3940:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3941: }
                   3942: 
1.61      www      3943: # ------------------------------------------------------------------ Screenname
1.81      albertel 3944: 
                   3945: =pod
                   3946: 
1.648     raeburn  3947: =item * &screenname($uname,$udom)
1.81      albertel 3948: 
                   3949: Gets a users screenname and returns it as a string
                   3950: 
                   3951: =cut
1.61      www      3952: 
                   3953: sub screenname {
                   3954:     my ($uname,$udom)=@_;
1.258     albertel 3955:     if ($uname eq $env{'user.name'} &&
                   3956: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3957:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3958:     return $names{'screenname'};
1.62      www      3959: }
                   3960: 
1.212     albertel 3961: 
1.802     bisitz   3962: # ------------------------------------------------------------- Confirm Wrapper
                   3963: =pod
                   3964: 
1.1075.2.42  raeburn  3965: =item * &confirmwrapper($message)
1.802     bisitz   3966: 
                   3967: Wrap messages about completion of operation in box
                   3968: 
                   3969: =cut
                   3970: 
                   3971: sub confirmwrapper {
                   3972:     my ($message)=@_;
                   3973:     if ($message) {
                   3974:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3975:                .$message."\n"
                   3976:                .'</div>'."\n";
                   3977:     } else {
                   3978:         return $message;
                   3979:     }
                   3980: }
                   3981: 
1.62      www      3982: # ------------------------------------------------------------- Message Wrapper
                   3983: 
                   3984: sub messagewrapper {
1.369     www      3985:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3986:     return 
1.441     albertel 3987:         '<a href="/adm/email?compose=individual&amp;'.
                   3988:         'recname='.$username.'&amp;recdom='.$domain.
                   3989: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3990:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3991: }
1.802     bisitz   3992: 
1.74      www      3993: # --------------------------------------------------------------- Notes Wrapper
                   3994: 
                   3995: sub noteswrapper {
                   3996:     my ($link,$un,$do)=@_;
                   3997:     return 
1.896     amueller 3998: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3999: }
1.802     bisitz   4000: 
1.62      www      4001: # ------------------------------------------------------------- Aboutme Wrapper
                   4002: 
                   4003: sub aboutmewrapper {
1.1070    raeburn  4004:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4005:     if (!defined($username)  && !defined($domain)) {
                   4006:         return;
                   4007:     }
1.1075.2.15  raeburn  4008:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4009: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4010: }
                   4011: 
                   4012: # ------------------------------------------------------------ Syllabus Wrapper
                   4013: 
                   4014: sub syllabuswrapper {
1.707     bisitz   4015:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4016:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4017: }
1.14      harris41 4018: 
1.1075.2.161.  .11(raeb 4019:-22): sub aboutme_on {
                   4020:-22):     my ($uname,$udom)=@_;
                   4021:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   4022:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4023:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4024:-22):     my $hashkey=$uname.':'.$udom;
                   4025:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4026:-22):     if ($cached) {
                   4027:-22):         return $aboutme;
                   4028:-22):     }
                   4029:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4030:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4031:-22):     return $aboutme;
                   4032:-22): }
                   4033:-22): 
                   4034:-22): sub devalidate_aboutme_cache {
                   4035:-22):     my ($uname,$udom)=@_;
                   4036:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4037:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   4038:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4039:-22):     my $id=$uname.':'.$udom;
                   4040:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4041:-22): }
                   4042:-22): 
1.802     bisitz   4043: # -----------------------------------------------------------------------------
                   4044: 
1.208     matthew  4045: sub track_student_link {
1.887     raeburn  4046:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4047:     my $link ="/adm/trackstudent?";
1.208     matthew  4048:     my $title = 'View recent activity';
                   4049:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4050:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4051:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4052:         $title .= ' of this student';
1.268     albertel 4053:     } 
1.208     matthew  4054:     if (defined($target) && $target !~ /^\s*$/) {
                   4055:         $target = qq{target="$target"};
                   4056:     } else {
                   4057:         $target = '';
                   4058:     }
1.268     albertel 4059:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4060:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4061:     $title = &mt($title);
                   4062:     $linktext = &mt($linktext);
1.448     albertel 4063:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4064: 	&help_open_topic('View_recent_activity');
1.208     matthew  4065: }
                   4066: 
1.781     raeburn  4067: sub slot_reservations_link {
                   4068:     my ($linktext,$sname,$sdom,$target) = @_;
                   4069:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4070:     my $title = 'View slot reservation history';
                   4071:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4072:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4073:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4074:         $title .= ' of this student';
                   4075:     }
                   4076:     if (defined($target) && $target !~ /^\s*$/) {
                   4077:         $target = qq{target="$target"};
                   4078:     } else {
                   4079:         $target = '';
                   4080:     }
                   4081:     $title = &mt($title);
                   4082:     $linktext = &mt($linktext);
                   4083:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4084: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4085: 
                   4086: }
                   4087: 
1.508     www      4088: # ===================================================== Display a student photo
                   4089: 
                   4090: 
1.509     albertel 4091: sub student_image_tag {
1.508     www      4092:     my ($domain,$user)=@_;
                   4093:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4094:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4095: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4096:     } else {
                   4097: 	return '';
                   4098:     }
                   4099: }
                   4100: 
1.112     bowersj2 4101: =pod
                   4102: 
                   4103: =back
                   4104: 
                   4105: =head1 Access .tab File Data
                   4106: 
                   4107: =over 4
                   4108: 
1.648     raeburn  4109: =item * &languageids() 
1.112     bowersj2 4110: 
                   4111: returns list of all language ids
                   4112: 
                   4113: =cut
                   4114: 
1.14      harris41 4115: sub languageids {
1.16      harris41 4116:     return sort(keys(%language));
1.14      harris41 4117: }
                   4118: 
1.112     bowersj2 4119: =pod
                   4120: 
1.648     raeburn  4121: =item * &languagedescription() 
1.112     bowersj2 4122: 
                   4123: returns description of a specified language id
                   4124: 
                   4125: =cut
                   4126: 
1.14      harris41 4127: sub languagedescription {
1.125     www      4128:     my $code=shift;
                   4129:     return  ($supported_language{$code}?'* ':'').
                   4130:             $language{$code}.
1.126     www      4131: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4132: }
                   4133: 
1.1048    foxr     4134: =pod
                   4135: 
                   4136: =item * &plainlanguagedescription
                   4137: 
                   4138: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4139: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4140: 
                   4141: =cut
                   4142: 
1.145     www      4143: sub plainlanguagedescription {
                   4144:     my $code=shift;
                   4145:     return $language{$code};
                   4146: }
                   4147: 
1.1048    foxr     4148: =pod
                   4149: 
                   4150: =item * &supportedlanguagecode
                   4151: 
                   4152: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4153: code.
                   4154: 
                   4155: =cut
                   4156: 
1.145     www      4157: sub supportedlanguagecode {
                   4158:     my $code=shift;
                   4159:     return $supported_language{$code};
1.97      www      4160: }
                   4161: 
1.112     bowersj2 4162: =pod
                   4163: 
1.1048    foxr     4164: =item * &latexlanguage()
                   4165: 
                   4166: Given a language key code returns the correspondnig language to use
                   4167: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4168: is no supported hyphenation for the language code.
                   4169: 
                   4170: =cut
                   4171: 
                   4172: sub latexlanguage {
                   4173:     my $code = shift;
                   4174:     return $latex_language{$code};
                   4175: }
                   4176: 
                   4177: =pod
                   4178: 
                   4179: =item * &latexhyphenation()
                   4180: 
                   4181: Same as above but what's supplied is the language as it might be stored
                   4182: in the metadata.
                   4183: 
                   4184: =cut
                   4185: 
                   4186: sub latexhyphenation {
                   4187:     my $key = shift;
                   4188:     return $latex_language_bykey{$key};
                   4189: }
                   4190: 
                   4191: =pod
                   4192: 
1.648     raeburn  4193: =item * &copyrightids() 
1.112     bowersj2 4194: 
                   4195: returns list of all copyrights
                   4196: 
                   4197: =cut
                   4198: 
                   4199: sub copyrightids {
                   4200:     return sort(keys(%cprtag));
                   4201: }
                   4202: 
                   4203: =pod
                   4204: 
1.648     raeburn  4205: =item * &copyrightdescription() 
1.112     bowersj2 4206: 
                   4207: returns description of a specified copyright id
                   4208: 
                   4209: =cut
                   4210: 
                   4211: sub copyrightdescription {
1.166     www      4212:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4213: }
1.197     matthew  4214: 
                   4215: =pod
                   4216: 
1.648     raeburn  4217: =item * &source_copyrightids() 
1.192     taceyjo1 4218: 
                   4219: returns list of all source copyrights
                   4220: 
                   4221: =cut
                   4222: 
                   4223: sub source_copyrightids {
                   4224:     return sort(keys(%scprtag));
                   4225: }
                   4226: 
                   4227: =pod
                   4228: 
1.648     raeburn  4229: =item * &source_copyrightdescription() 
1.192     taceyjo1 4230: 
                   4231: returns description of a specified source copyright id
                   4232: 
                   4233: =cut
                   4234: 
                   4235: sub source_copyrightdescription {
                   4236:     return &mt($scprtag{shift(@_)});
                   4237: }
1.112     bowersj2 4238: 
                   4239: =pod
                   4240: 
1.648     raeburn  4241: =item * &filecategories() 
1.112     bowersj2 4242: 
                   4243: returns list of all file categories
                   4244: 
                   4245: =cut
                   4246: 
                   4247: sub filecategories {
                   4248:     return sort(keys(%category_extensions));
                   4249: }
                   4250: 
                   4251: =pod
                   4252: 
1.648     raeburn  4253: =item * &filecategorytypes() 
1.112     bowersj2 4254: 
                   4255: returns list of file types belonging to a given file
                   4256: category
                   4257: 
                   4258: =cut
                   4259: 
                   4260: sub filecategorytypes {
1.356     albertel 4261:     my ($cat) = @_;
                   4262:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4263: }
                   4264: 
                   4265: =pod
                   4266: 
1.648     raeburn  4267: =item * &fileembstyle() 
1.112     bowersj2 4268: 
                   4269: returns embedding style for a specified file type
                   4270: 
                   4271: =cut
                   4272: 
                   4273: sub fileembstyle {
                   4274:     return $fe{lc(shift(@_))};
1.169     www      4275: }
                   4276: 
1.351     www      4277: sub filemimetype {
                   4278:     return $fm{lc(shift(@_))};
                   4279: }
                   4280: 
1.169     www      4281: 
                   4282: sub filecategoryselect {
                   4283:     my ($name,$value)=@_;
1.189     matthew  4284:     return &select_form($value,$name,
1.970     raeburn  4285:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4286: }
                   4287: 
                   4288: =pod
                   4289: 
1.648     raeburn  4290: =item * &filedescription() 
1.112     bowersj2 4291: 
                   4292: returns description for a specified file type
                   4293: 
                   4294: =cut
                   4295: 
                   4296: sub filedescription {
1.188     matthew  4297:     my $file_description = $fd{lc(shift())};
                   4298:     $file_description =~ s:([\[\]]):~$1:g;
                   4299:     return &mt($file_description);
1.112     bowersj2 4300: }
                   4301: 
                   4302: =pod
                   4303: 
1.648     raeburn  4304: =item * &filedescriptionex() 
1.112     bowersj2 4305: 
                   4306: returns description for a specified file type with
                   4307: extra formatting
                   4308: 
                   4309: =cut
                   4310: 
                   4311: sub filedescriptionex {
                   4312:     my $ex=shift;
1.188     matthew  4313:     my $file_description = $fd{lc($ex)};
                   4314:     $file_description =~ s:([\[\]]):~$1:g;
                   4315:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4316: }
                   4317: 
                   4318: # End of .tab access
                   4319: =pod
                   4320: 
                   4321: =back
                   4322: 
                   4323: =cut
                   4324: 
                   4325: # ------------------------------------------------------------------ File Types
                   4326: sub fileextensions {
                   4327:     return sort(keys(%fe));
                   4328: }
                   4329: 
1.97      www      4330: # ----------------------------------------------------------- Display Languages
                   4331: # returns a hash with all desired display languages
                   4332: #
                   4333: 
                   4334: sub display_languages {
                   4335:     my %languages=();
1.695     raeburn  4336:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4337: 	$languages{$lang}=1;
1.97      www      4338:     }
                   4339:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4340:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4341: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4342: 	    $languages{$lang}=1;
1.97      www      4343:         }
                   4344:     }
                   4345:     return %languages;
1.14      harris41 4346: }
                   4347: 
1.582     albertel 4348: sub languages {
                   4349:     my ($possible_langs) = @_;
1.695     raeburn  4350:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4351:     if (!ref($possible_langs)) {
                   4352: 	if( wantarray ) {
                   4353: 	    return @preferred_langs;
                   4354: 	} else {
                   4355: 	    return $preferred_langs[0];
                   4356: 	}
                   4357:     }
                   4358:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4359:     my @preferred_possibilities;
                   4360:     foreach my $preferred_lang (@preferred_langs) {
                   4361: 	if (exists($possibilities{$preferred_lang})) {
                   4362: 	    push(@preferred_possibilities, $preferred_lang);
                   4363: 	}
                   4364:     }
                   4365:     if( wantarray ) {
                   4366: 	return @preferred_possibilities;
                   4367:     }
                   4368:     return $preferred_possibilities[0];
                   4369: }
                   4370: 
1.742     raeburn  4371: sub user_lang {
                   4372:     my ($touname,$toudom,$fromcid) = @_;
                   4373:     my @userlangs;
                   4374:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4375:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4376:                     $env{'course.'.$fromcid.'.languages'}));
                   4377:     } else {
                   4378:         my %langhash = &getlangs($touname,$toudom);
                   4379:         if ($langhash{'languages'} ne '') {
                   4380:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4381:         } else {
                   4382:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4383:             if ($domdefs{'lang_def'} ne '') {
                   4384:                 @userlangs = ($domdefs{'lang_def'});
                   4385:             }
                   4386:         }
                   4387:     }
                   4388:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4389:     my $user_lh = Apache::localize->get_handle(@languages);
                   4390:     return $user_lh;
                   4391: }
                   4392: 
                   4393: 
1.112     bowersj2 4394: ###############################################################
                   4395: ##               Student Answer Attempts                     ##
                   4396: ###############################################################
                   4397: 
                   4398: =pod
                   4399: 
                   4400: =head1 Alternate Problem Views
                   4401: 
                   4402: =over 4
                   4403: 
1.648     raeburn  4404: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4405:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4406: 
                   4407: Return string with previous attempt on problem. Arguments:
                   4408: 
                   4409: =over 4
                   4410: 
                   4411: =item * $symb: Problem, including path
                   4412: 
                   4413: =item * $username: username of the desired student
                   4414: 
                   4415: =item * $domain: domain of the desired student
1.14      harris41 4416: 
1.112     bowersj2 4417: =item * $course: Course ID
1.14      harris41 4418: 
1.112     bowersj2 4419: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4420:     something
1.14      harris41 4421: 
1.112     bowersj2 4422: =item * $regexp: if string matches this regexp, the string will be
                   4423:     sent to $gradesub
1.14      harris41 4424: 
1.112     bowersj2 4425: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4426: 
1.1075.2.86  raeburn  4427: =item * $usec: section of the desired student
                   4428: 
                   4429: =item * $identifier: counter for student (multiple students one problem) or
                   4430:     problem (one student; whole sequence).
                   4431: 
1.112     bowersj2 4432: =back
1.14      harris41 4433: 
1.112     bowersj2 4434: The output string is a table containing all desired attempts, if any.
1.16      harris41 4435: 
1.112     bowersj2 4436: =cut
1.1       albertel 4437: 
                   4438: sub get_previous_attempt {
1.1075.2.86  raeburn  4439:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4440:   my $prevattempts='';
1.43      ng       4441:   no strict 'refs';
1.1       albertel 4442:   if ($symb) {
1.3       albertel 4443:     my (%returnhash)=
                   4444:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4445:     if ($returnhash{'version'}) {
                   4446:       my %lasthash=();
                   4447:       my $version;
                   4448:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4449:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4450:             if ($key =~ /\.rawrndseed$/) {
                   4451:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4452:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4453:             } else {
                   4454:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4455:             }
1.19      harris41 4456:         }
1.1       albertel 4457:       }
1.596     albertel 4458:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4459:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4460:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4461:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4462:       foreach my $key (sort(keys(%lasthash))) {
                   4463: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4464: 	if ($#parts > 0) {
1.31      albertel 4465: 	  my $data=$parts[-1];
1.989     raeburn  4466:           next if ($data eq 'foilorder');
1.31      albertel 4467: 	  pop(@parts);
1.1010    www      4468:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4469:           if ($data eq 'type') {
                   4470:               unless ($showsurv) {
                   4471:                   my $id = join(',',@parts);
                   4472:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4473:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4474:                       $lasthidden{$ign.'.'.$id} = 1;
                   4475:                   }
1.945     raeburn  4476:               }
1.1075.2.86  raeburn  4477:               if ($identifier ne '') {
                   4478:                   my $id = join(',',@parts);
                   4479:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4480:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4481:                       $hidestatus{$ign.'.'.$id} = 1;
                   4482:                   }
                   4483:               }
                   4484:           } elsif ($data eq 'regrader') {
                   4485:               if (($identifier ne '') && (@parts)) {
                   4486:                   my $id = join(',',@parts);
                   4487:                   $regraded{$ign.'.'.$id} = 1;
                   4488:               }
1.1010    www      4489:           } 
1.31      albertel 4490: 	} else {
1.41      ng       4491: 	  if ($#parts == 0) {
                   4492: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4493: 	  } else {
                   4494: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4495: 	  }
1.31      albertel 4496: 	}
1.16      harris41 4497:       }
1.596     albertel 4498:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4499:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4500:         my (%solved,%resets,%probstatus);
                   4501:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4502:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4503:                 foreach my $id (keys(%regraded)) {
                   4504:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4505:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4506:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4507:                         push(@{$resets{$id}},$version);
                   4508:                     }
                   4509:                 }
                   4510:             }
                   4511:         }
1.40      ng       4512: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4513:             my (@hidden,@unsolved);
1.945     raeburn  4514:             if (%typeparts) {
                   4515:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4516:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4517:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4518:                         push(@hidden,$id);
1.1075.2.86  raeburn  4519:                     } elsif ($identifier ne '') {
                   4520:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4521:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4522:                                 ($hidestatus{$id})) {
                   4523:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4524:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4525:                                 push(@{$solved{$id}},$version);
                   4526:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4527:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4528:                                 my $skip;
                   4529:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4530:                                     foreach my $reset (@{$resets{$id}}) {
                   4531:                                         if ($reset > $solved{$id}[-1]) {
                   4532:                                             $skip=1;
                   4533:                                             last;
                   4534:                                         }
                   4535:                                     }
                   4536:                                 }
                   4537:                                 unless ($skip) {
                   4538:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4539:                                     push(@unsolved,$partslist);
                   4540:                                 }
                   4541:                             }
                   4542:                         }
1.945     raeburn  4543:                     }
                   4544:                 }
                   4545:             }
                   4546:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4547:                            '<td>'.&mt('Transaction [_1]',$version);
                   4548:             if (@unsolved) {
                   4549:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4550:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4551:                                  &mt('Hide').'</label></span>';
                   4552:             }
                   4553:             $prevattempts .= '</td>';
1.945     raeburn  4554:             if (@hidden) {
                   4555:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4556:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4557:                     my $hide;
                   4558:                     foreach my $id (@hidden) {
                   4559:                         if ($key =~ /^\Q$id\E/) {
                   4560:                             $hide = 1;
                   4561:                             last;
                   4562:                         }
                   4563:                     }
                   4564:                     if ($hide) {
                   4565:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4566:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4567:                             my $value = &format_previous_attempt_value($key,
                   4568:                                              $returnhash{$version.':'.$key});
                   4569:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4570:                         } else {
                   4571:                             $prevattempts.='<td>&nbsp;</td>';
                   4572:                         }
                   4573:                     } else {
                   4574:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4575:                             my $value = $returnhash{$version.':'.$key};
                   4576:                             if ($key =~ /\.rndseed$/) {
                   4577:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4578:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4579:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4580:                                 }
                   4581:                             }
                   4582:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4583:                                            '&nbsp;</td>';
1.945     raeburn  4584:                         } else {
                   4585:                             $prevattempts.='<td>&nbsp;</td>';
                   4586:                         }
                   4587:                     }
                   4588:                 }
                   4589:             } else {
                   4590: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4591:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4592:                     my $value = $returnhash{$version.':'.$key};
                   4593:                     if ($key =~ /\.rndseed$/) {
                   4594:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4595:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4596:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4597:                         }
                   4598:                     }
                   4599:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4600:                                    '&nbsp;</td>';
1.945     raeburn  4601: 	        }
                   4602:             }
                   4603: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4604: 	 }
1.1       albertel 4605:       }
1.945     raeburn  4606:       my @currhidden = keys(%lasthidden);
1.596     albertel 4607:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4608:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4609:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4610:           if (%typeparts) {
                   4611:               my $hidden;
                   4612:               foreach my $id (@currhidden) {
                   4613:                   if ($key =~ /^\Q$id\E/) {
                   4614:                       $hidden = 1;
                   4615:                       last;
                   4616:                   }
                   4617:               }
                   4618:               if ($hidden) {
                   4619:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4620:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4621:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4622:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4623:                           $value = &$gradesub($value);
                   4624:                       }
                   4625:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4626:                   } else {
                   4627:                       $prevattempts.='<td>&nbsp;</td>';
                   4628:                   }
                   4629:               } else {
                   4630:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4631:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4632:                       $value = &$gradesub($value);
                   4633:                   }
                   4634:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4635:               }
                   4636:           } else {
                   4637: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4638: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4639:                   $value = &$gradesub($value);
                   4640:               }
                   4641: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4642:           }
1.16      harris41 4643:       }
1.596     albertel 4644:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4645:     } else {
1.1075.2.161.  .17(raeb 4646:-23):       my $msg;
                   4647:-23):       if ($symb =~ /ext\.tool$/) {
                   4648:-23):           $msg = &mt('No grade passed back.');
                   4649:-23):       } else {
                   4650:-23):           $msg = &mt('Nothing submitted - no attempts.');
                   4651:-23):       }
1.596     albertel 4652:       $prevattempts=
                   4653: 	  &start_data_table().&start_data_table_row().
1.1075.2.161.  .17(raeb 4654:-23): 	  '<td>'.$msg.'</td>'.
1.596     albertel 4655: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4656:     }
                   4657:   } else {
1.596     albertel 4658:     $prevattempts=
                   4659: 	  &start_data_table().&start_data_table_row().
                   4660: 	  '<td>'.&mt('No data.').'</td>'.
                   4661: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4662:   }
1.10      albertel 4663: }
                   4664: 
1.581     albertel 4665: sub format_previous_attempt_value {
                   4666:     my ($key,$value) = @_;
1.1011    www      4667:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4668: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4669:     } elsif (ref($value) eq 'ARRAY') {
                   4670: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4671:     } elsif ($key =~ /answerstring$/) {
                   4672:         my %answers = &Apache::lonnet::str2hash($value);
                   4673:         my @anskeys = sort(keys(%answers));
                   4674:         if (@anskeys == 1) {
                   4675:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4676:             if ($answer =~ m{\0}) {
                   4677:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4678:             }
                   4679:             my $tag_internal_answer_name = 'INTERNAL';
                   4680:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4681:                 $value = $answer; 
                   4682:             } else {
                   4683:                 $value = $anskeys[0].'='.$answer;
                   4684:             }
                   4685:         } else {
                   4686:             foreach my $ans (@anskeys) {
                   4687:                 my $answer = $answers{$ans};
1.1001    raeburn  4688:                 if ($answer =~ m{\0}) {
                   4689:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4690:                 }
                   4691:                 $value .=  $ans.'='.$answer.'<br />';;
                   4692:             } 
                   4693:         }
1.581     albertel 4694:     } else {
                   4695: 	$value = &unescape($value);
                   4696:     }
                   4697:     return $value;
                   4698: }
                   4699: 
                   4700: 
1.107     albertel 4701: sub relative_to_absolute {
                   4702:     my ($url,$output)=@_;
                   4703:     my $parser=HTML::TokeParser->new(\$output);
                   4704:     my $token;
                   4705:     my $thisdir=$url;
                   4706:     my @rlinks=();
                   4707:     while ($token=$parser->get_token) {
                   4708: 	if ($token->[0] eq 'S') {
                   4709: 	    if ($token->[1] eq 'a') {
                   4710: 		if ($token->[2]->{'href'}) {
                   4711: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4712: 		}
                   4713: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4714: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4715: 	    } elsif ($token->[1] eq 'base') {
                   4716: 		$thisdir=$token->[2]->{'href'};
                   4717: 	    }
                   4718: 	}
                   4719:     }
                   4720:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4721:     foreach my $link (@rlinks) {
1.726     raeburn  4722: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4723: 		($link=~/^\//) ||
                   4724: 		($link=~/^javascript:/i) ||
                   4725: 		($link=~/^mailto:/i) ||
                   4726: 		($link=~/^\#/)) {
                   4727: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4728: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4729: 	}
                   4730:     }
                   4731: # -------------------------------------------------- Deal with Applet codebases
                   4732:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4733:     return $output;
                   4734: }
                   4735: 
1.112     bowersj2 4736: =pod
                   4737: 
1.648     raeburn  4738: =item * &get_student_view()
1.112     bowersj2 4739: 
                   4740: show a snapshot of what student was looking at
                   4741: 
                   4742: =cut
                   4743: 
1.10      albertel 4744: sub get_student_view {
1.186     albertel 4745:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4746:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4747:   my (%form);
1.10      albertel 4748:   my @elements=('symb','courseid','domain','username');
                   4749:   foreach my $element (@elements) {
1.186     albertel 4750:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4751:   }
1.186     albertel 4752:   if (defined($moreenv)) {
                   4753:       %form=(%form,%{$moreenv});
                   4754:   }
1.236     albertel 4755:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4756:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4757:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4758:   $userview=~s/\<body[^\>]*\>//gi;
                   4759:   $userview=~s/\<\/body\>//gi;
                   4760:   $userview=~s/\<html\>//gi;
                   4761:   $userview=~s/\<\/html\>//gi;
                   4762:   $userview=~s/\<head\>//gi;
                   4763:   $userview=~s/\<\/head\>//gi;
                   4764:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4765:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4766:   if (wantarray) {
                   4767:      return ($userview,$response);
                   4768:   } else {
                   4769:      return $userview;
                   4770:   }
                   4771: }
                   4772: 
                   4773: sub get_student_view_with_retries {
                   4774:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4775: 
                   4776:     my $ok = 0;                 # True if we got a good response.
                   4777:     my $content;
                   4778:     my $response;
                   4779: 
                   4780:     # Try to get the student_view done. within the retries count:
                   4781:     
                   4782:     do {
                   4783:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4784:          $ok      = $response->is_success;
                   4785:          if (!$ok) {
                   4786:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4787:          }
                   4788:          $retries--;
                   4789:     } while (!$ok && ($retries > 0));
                   4790:     
                   4791:     if (!$ok) {
                   4792:        $content = '';          # On error return an empty content.
                   4793:     }
1.651     www      4794:     if (wantarray) {
                   4795:        return ($content, $response);
                   4796:     } else {
                   4797:        return $content;
                   4798:     }
1.11      albertel 4799: }
                   4800: 
1.1075.2.149  raeburn  4801: sub css_links {
                   4802:     my ($currsymb,$level) = @_;
                   4803:     my ($links,@symbs,%cssrefs,%httpref);
                   4804:     if ($level eq 'map') {
                   4805:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4806:         if (ref($navmap)) {
                   4807:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4808:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4809:             foreach my $res (@resources) {
                   4810:                 if (ref($res) && $res->symb()) {
                   4811:                     push(@symbs,$res->symb());
                   4812:                 }
                   4813:             }
                   4814:         }
                   4815:     } else {
                   4816:         @symbs = ($currsymb);
                   4817:     }
                   4818:     foreach my $symb (@symbs) {
                   4819:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4820:         if ($css_href =~ /\S/) {
                   4821:             unless ($css_href =~ m{https?://}) {
                   4822:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4823:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4824:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4825:                 unless ($css_href =~ m{^/}) {
                   4826:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4827:                 }
                   4828:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4829:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4830:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4831:                         my $thisurl = $proburl;
                   4832:                         if ($env{'httpref.'.$proburl}) {
                   4833:                             $thisurl = $env{'httpref.'.$proburl};
                   4834:                         }
                   4835:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4836:                     }
                   4837:                 }
                   4838:             }
                   4839:             $cssrefs{$css_href} = 1;
                   4840:         }
                   4841:     }
                   4842:     if (keys(%httpref)) {
                   4843:         &Apache::lonnet::appenv(\%httpref);
                   4844:     }
                   4845:     if (keys(%cssrefs)) {
                   4846:         foreach my $css_href (keys(%cssrefs)) {
                   4847:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4848:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4849:         }
                   4850:     }
                   4851:     return $links;
                   4852: }
                   4853: 
1.112     bowersj2 4854: =pod
                   4855: 
1.648     raeburn  4856: =item * &get_student_answers() 
1.112     bowersj2 4857: 
                   4858: show a snapshot of how student was answering problem
                   4859: 
                   4860: =cut
                   4861: 
1.11      albertel 4862: sub get_student_answers {
1.100     sakharuk 4863:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4864:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4865:   my (%moreenv);
1.11      albertel 4866:   my @elements=('symb','courseid','domain','username');
                   4867:   foreach my $element (@elements) {
1.186     albertel 4868:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4869:   }
1.186     albertel 4870:   $moreenv{'grade_target'}='answer';
                   4871:   %moreenv=(%form,%moreenv);
1.497     raeburn  4872:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4873:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4874:   return $userview;
1.1       albertel 4875: }
1.116     albertel 4876: 
                   4877: =pod
                   4878: 
                   4879: =item * &submlink()
                   4880: 
1.242     albertel 4881: Inputs: $text $uname $udom $symb $target
1.116     albertel 4882: 
                   4883: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4884: 
                   4885: =cut
                   4886: 
                   4887: ###############################################
                   4888: sub submlink {
1.242     albertel 4889:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4890:     if (!($uname && $udom)) {
                   4891: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4892: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4893: 	if (!$symb) { $symb=$cursymb; }
                   4894:     }
1.254     matthew  4895:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4896:     $symb=&escape($symb);
1.960     bisitz   4897:     if ($target) { $target=" target=\"$target\""; }
                   4898:     return
                   4899:         '<a href="/adm/grades?command=submission'.
                   4900:         '&amp;symb='.$symb.
                   4901:         '&amp;student='.$uname.
                   4902:         '&amp;userdom='.$udom.'"'.
                   4903:         $target.'>'.$text.'</a>';
1.242     albertel 4904: }
                   4905: ##############################################
                   4906: 
                   4907: =pod
                   4908: 
                   4909: =item * &pgrdlink()
                   4910: 
                   4911: Inputs: $text $uname $udom $symb $target
                   4912: 
                   4913: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4914: 
                   4915: =cut
                   4916: 
                   4917: ###############################################
                   4918: sub pgrdlink {
                   4919:     my $link=&submlink(@_);
                   4920:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4921:     return $link;
                   4922: }
                   4923: ##############################################
                   4924: 
                   4925: =pod
                   4926: 
                   4927: =item * &pprmlink()
                   4928: 
                   4929: Inputs: $text $uname $udom $symb $target
                   4930: 
                   4931: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4932: student and a specific resource
1.242     albertel 4933: 
                   4934: =cut
                   4935: 
                   4936: ###############################################
                   4937: sub pprmlink {
                   4938:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4939:     if (!($uname && $udom)) {
                   4940: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4941: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4942: 	if (!$symb) { $symb=$cursymb; }
                   4943:     }
1.254     matthew  4944:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4945:     $symb=&escape($symb);
1.242     albertel 4946:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4947:     return '<a href="/adm/parmset?command=set&amp;'.
                   4948: 	'symb='.$symb.'&amp;uname='.$uname.
                   4949: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4950: }
                   4951: ##############################################
1.37      matthew  4952: 
1.112     bowersj2 4953: =pod
                   4954: 
                   4955: =back
                   4956: 
                   4957: =cut
                   4958: 
1.37      matthew  4959: ###############################################
1.51      www      4960: 
                   4961: 
                   4962: sub timehash {
1.687     raeburn  4963:     my ($thistime) = @_;
                   4964:     my $timezone = &Apache::lonlocal::gettimezone();
                   4965:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4966:                      ->set_time_zone($timezone);
                   4967:     my $wday = $dt->day_of_week();
                   4968:     if ($wday == 7) { $wday = 0; }
                   4969:     return ( 'second' => $dt->second(),
                   4970:              'minute' => $dt->minute(),
                   4971:              'hour'   => $dt->hour(),
                   4972:              'day'     => $dt->day_of_month(),
                   4973:              'month'   => $dt->month(),
                   4974:              'year'    => $dt->year(),
                   4975:              'weekday' => $wday,
                   4976:              'dayyear' => $dt->day_of_year(),
                   4977:              'dlsav'   => $dt->is_dst() );
1.51      www      4978: }
                   4979: 
1.370     www      4980: sub utc_string {
                   4981:     my ($date)=@_;
1.371     www      4982:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4983: }
                   4984: 
1.51      www      4985: sub maketime {
                   4986:     my %th=@_;
1.687     raeburn  4987:     my ($epoch_time,$timezone,$dt);
                   4988:     $timezone = &Apache::lonlocal::gettimezone();
                   4989:     eval {
                   4990:         $dt = DateTime->new( year   => $th{'year'},
                   4991:                              month  => $th{'month'},
                   4992:                              day    => $th{'day'},
                   4993:                              hour   => $th{'hour'},
                   4994:                              minute => $th{'minute'},
                   4995:                              second => $th{'second'},
                   4996:                              time_zone => $timezone,
                   4997:                          );
                   4998:     };
                   4999:     if (!$@) {
                   5000:         $epoch_time = $dt->epoch;
                   5001:         if ($epoch_time) {
                   5002:             return $epoch_time;
                   5003:         }
                   5004:     }
1.51      www      5005:     return POSIX::mktime(
                   5006:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5007:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5008: }
                   5009: 
                   5010: #########################################
1.51      www      5011: 
                   5012: sub findallcourses {
1.482     raeburn  5013:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5014:     my %roles;
                   5015:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5016:     my %courses;
1.51      www      5017:     my $now=time;
1.482     raeburn  5018:     if (!defined($uname)) {
                   5019:         $uname = $env{'user.name'};
                   5020:     }
                   5021:     if (!defined($udom)) {
                   5022:         $udom = $env{'user.domain'};
                   5023:     }
                   5024:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5025:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5026:         if (!%roles) {
                   5027:             %roles = (
                   5028:                        cc => 1,
1.907     raeburn  5029:                        co => 1,
1.482     raeburn  5030:                        in => 1,
                   5031:                        ep => 1,
                   5032:                        ta => 1,
                   5033:                        cr => 1,
                   5034:                        st => 1,
                   5035:              );
                   5036:         }
                   5037:         foreach my $entry (keys(%roleshash)) {
                   5038:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5039:             if ($trole =~ /^cr/) { 
                   5040:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5041:             } else {
                   5042:                 next if (!exists($roles{$trole}));
                   5043:             }
                   5044:             if ($tend) {
                   5045:                 next if ($tend < $now);
                   5046:             }
                   5047:             if ($tstart) {
                   5048:                 next if ($tstart > $now);
                   5049:             }
1.1058    raeburn  5050:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5051:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5052:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5053:             if ($secpart eq '') {
                   5054:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5055:                 $sec = 'none';
1.1058    raeburn  5056:                 $value .= $cnum.'/';
1.482     raeburn  5057:             } else {
                   5058:                 $cnum = $cnumpart;
                   5059:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5060:                 $value .= $cnum.'/'.$sec;
                   5061:             }
                   5062:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5063:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5064:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5065:                 }
                   5066:             } else {
                   5067:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5068:             }
1.482     raeburn  5069:         }
                   5070:     } else {
                   5071:         foreach my $key (keys(%env)) {
1.483     albertel 5072: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5073:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5074: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5075: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5076: 	        next if (%roles && !exists($roles{$role}));
                   5077: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5078:                 my $active=1;
                   5079:                 if ($starttime) {
                   5080: 		    if ($now<$starttime) { $active=0; }
                   5081:                 }
                   5082:                 if ($endtime) {
                   5083:                     if ($now>$endtime) { $active=0; }
                   5084:                 }
                   5085:                 if ($active) {
1.1058    raeburn  5086:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5087:                     if ($sec eq '') {
                   5088:                         $sec = 'none';
1.1058    raeburn  5089:                     } else {
                   5090:                         $value .= $sec;
                   5091:                     }
                   5092:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5093:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5094:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5095:                         }
                   5096:                     } else {
                   5097:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5098:                     }
1.474     raeburn  5099:                 }
                   5100:             }
1.51      www      5101:         }
                   5102:     }
1.474     raeburn  5103:     return %courses;
1.51      www      5104: }
1.37      matthew  5105: 
1.54      www      5106: ###############################################
1.474     raeburn  5107: 
                   5108: sub blockcheck {
1.1075.2.158  raeburn  5109:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  5110: 
1.1075.2.161.  .4(raebu 5111:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  5112:         my ($has_evb,$check_ipaccess);
                   5113:         my $dom = $env{'user.domain'};
                   5114:         if ($env{'request.course.id'}) {
                   5115:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5116:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5117:             my $checkrole = "cm./$cdom/$cnum";
                   5118:             my $sec = $env{'request.course.sec'};
                   5119:             if ($sec ne '') {
                   5120:                 $checkrole .= "/$sec";
                   5121:             }
                   5122:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5123:                 ($env{'request.role'} !~ /^st/)) {
                   5124:                 $has_evb = 1;
                   5125:             }
                   5126:             unless ($has_evb) {
                   5127:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5128:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5129:                     if ($udom eq $cdom) {
                   5130:                         $check_ipaccess = 1;
                   5131:                     }
                   5132:                 }
                   5133:             }
1.1075.2.161.  .3(raebu 5134:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5135:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5136:22):             my $checkrole;
                   5137:22):             if ($env{'request.role.domain'} eq '') {
                   5138:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   5139:22):             } else {
                   5140:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5141:22):             }
                   5142:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5143:22):                 $has_evb = 1;
                   5144:22):             }
1.1075.2.158  raeburn  5145:         }
                   5146:         unless ($has_evb || $check_ipaccess) {
                   5147:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5148:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5149:                 $dom = $udom;
                   5150:             }
                   5151:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5152:                 $check_ipaccess = 1;
                   5153:             } else {
                   5154:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5155:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5156:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5157:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5158:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5159:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5160:                         $check_ipaccess = 1;
                   5161:                     }
                   5162:                 }
                   5163:             }
                   5164:         }
                   5165:         if ($check_ipaccess) {
                   5166:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5167:             unless (defined($cached)) {
                   5168:                 my %domconfig =
                   5169:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5170:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5171:             }
                   5172:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5173:                 foreach my $id (keys(%{$ipaccessref})) {
                   5174:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5175:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5176:                         if ($range) {
                   5177:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5178:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5179:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5180:                                         return ('','','',$id,$dom);
                   5181:                                         last;
                   5182:                                     }
                   5183:                                 }
                   5184:                             }
                   5185:                         }
                   5186:                     }
                   5187:                 }
                   5188:             }
                   5189:         }
1.1075.2.161.  .4(raebu 5190:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5191:22):             return ();
                   5192:22):         }
1.1075.2.158  raeburn  5193:     }
1.1075.2.73  raeburn  5194:     if (defined($udom) && defined($uname)) {
                   5195:         # If uname and udom are for a course, check for blocks in the course.
                   5196:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5197:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5198:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5199:             return ($startblock,$endblock,$triggerblock);
                   5200:         }
                   5201:     } else {
1.490     raeburn  5202:         $udom = $env{'user.domain'};
                   5203:         $uname = $env{'user.name'};
                   5204:     }
                   5205: 
1.502     raeburn  5206:     my $startblock = 0;
                   5207:     my $endblock = 0;
1.1062    raeburn  5208:     my $triggerblock = '';
1.1075.2.160  raeburn  5209:     my %live_courses;
                   5210:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5211:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5212:     }
1.474     raeburn  5213: 
1.490     raeburn  5214:     # If uname is for a user, and activity is course-specific, i.e.,
                   5215:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5216: 
1.490     raeburn  5217:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5218:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5219:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5220:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5221:         foreach my $key (keys(%live_courses)) {
                   5222:             if ($key ne $env{'request.course.id'}) {
                   5223:                 delete($live_courses{$key});
                   5224:             }
                   5225:         }
                   5226:     }
                   5227: 
                   5228:     my $otheruser = 0;
                   5229:     my %own_courses;
                   5230:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5231:         # Resource belongs to user other than current user.
                   5232:         $otheruser = 1;
                   5233:         # Gather courses for current user
                   5234:         %own_courses = 
                   5235:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5236:     }
                   5237: 
                   5238:     # Gather active course roles - course coordinator, instructor, 
                   5239:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5240: 
                   5241:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5242:         my ($cdom,$cnum);
                   5243:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5244:             $cdom = $env{'course.'.$course.'.domain'};
                   5245:             $cnum = $env{'course.'.$course.'.num'};
                   5246:         } else {
1.490     raeburn  5247:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5248:         }
                   5249:         my $no_ownblock = 0;
                   5250:         my $no_userblock = 0;
1.533     raeburn  5251:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5252:             # Check if current user has 'evb' priv for this
                   5253:             if (defined($own_courses{$course})) {
                   5254:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5255:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5256:                     if ($sec ne 'none') {
                   5257:                         $checkrole .= '/'.$sec;
                   5258:                     }
                   5259:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5260:                         $no_ownblock = 1;
                   5261:                         last;
                   5262:                     }
                   5263:                 }
                   5264:             }
                   5265:             # if they have 'evb' priv and are currently not playing student
                   5266:             next if (($no_ownblock) &&
                   5267:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5268:         }
1.474     raeburn  5269:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5270:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5271:             if ($sec ne 'none') {
1.482     raeburn  5272:                 $checkrole .= '/'.$sec;
1.474     raeburn  5273:             }
1.490     raeburn  5274:             if ($otheruser) {
                   5275:                 # Resource belongs to user other than current user.
                   5276:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5277:                 my (%allroles,%userroles);
                   5278:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5279:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5280:                         my ($trole,$tdom,$tnum,$tsec);
                   5281:                         if ($entry =~ /^cr/) {
                   5282:                             ($trole,$tdom,$tnum,$tsec) = 
                   5283:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5284:                         } else {
                   5285:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5286:                         }
                   5287:                         my ($spec,$area,$trest);
                   5288:                         $area = '/'.$tdom.'/'.$tnum;
                   5289:                         $trest = $tnum;
                   5290:                         if ($tsec ne '') {
                   5291:                             $area .= '/'.$tsec;
                   5292:                             $trest .= '/'.$tsec;
                   5293:                         }
                   5294:                         $spec = $trole.'.'.$area;
                   5295:                         if ($trole =~ /^cr/) {
                   5296:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5297:                                                               $tdom,$spec,$trest,$area);
                   5298:                         } else {
                   5299:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5300:                                                                 $tdom,$spec,$trest,$area);
                   5301:                         }
                   5302:                     }
1.1075.2.124  raeburn  5303:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5304:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5305:                         if ($1) {
                   5306:                             $no_userblock = 1;
                   5307:                             last;
                   5308:                         }
1.486     raeburn  5309:                     }
                   5310:                 }
1.490     raeburn  5311:             } else {
                   5312:                 # Resource belongs to current user
                   5313:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5314:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5315:                     $no_ownblock = 1;
                   5316:                     last;
                   5317:                 }
1.474     raeburn  5318:             }
                   5319:         }
                   5320:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5321:         next if (($no_ownblock) &&
1.491     albertel 5322:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5323:         next if ($no_userblock);
1.474     raeburn  5324: 
1.1075.2.128  raeburn  5325:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5326:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5327:         
1.1062    raeburn  5328:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5329:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5330:         if (($start != 0) && 
                   5331:             (($startblock == 0) || ($startblock > $start))) {
                   5332:             $startblock = $start;
1.1062    raeburn  5333:             if ($trigger ne '') {
                   5334:                 $triggerblock = $trigger;
                   5335:             }
1.502     raeburn  5336:         }
                   5337:         if (($end != 0)  &&
                   5338:             (($endblock == 0) || ($endblock < $end))) {
                   5339:             $endblock = $end;
1.1062    raeburn  5340:             if ($trigger ne '') {
                   5341:                 $triggerblock = $trigger;
                   5342:             }
1.502     raeburn  5343:         }
1.490     raeburn  5344:     }
1.1062    raeburn  5345:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5346: }
                   5347: 
                   5348: sub get_blocks {
1.1075.2.147  raeburn  5349:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5350:     my $startblock = 0;
                   5351:     my $endblock = 0;
1.1062    raeburn  5352:     my $triggerblock = '';
1.490     raeburn  5353:     my $course = $cdom.'_'.$cnum;
                   5354:     $setters->{$course} = {};
                   5355:     $setters->{$course}{'staff'} = [];
                   5356:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5357:     $setters->{$course}{'triggers'} = [];
                   5358:     my (@blockers,%triggered);
                   5359:     my $now = time;
                   5360:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5361:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5362:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5363:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5364:             $blocked = 1;
                   5365:             $nosymbcache = 1;
1.1075.2.148  raeburn  5366:             $noenccheck = 1;
1.1075.2.147  raeburn  5367:         }
1.1075.2.148  raeburn  5368:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5369:         foreach my $block (@blockers) {
                   5370:             if ($block =~ /^firstaccess____(.+)$/) {
                   5371:                 my $item = $1;
                   5372:                 my $type = 'map';
                   5373:                 my $timersymb = $item;
                   5374:                 if ($item eq 'course') {
                   5375:                     $type = 'course';
                   5376:                 } elsif ($item =~ /___\d+___/) {
                   5377:                     $type = 'resource';
                   5378:                 } else {
                   5379:                     $timersymb = &Apache::lonnet::symbread($item);
                   5380:                 }
                   5381:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5382:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5383:                 $triggered{$block} = {
                   5384:                                        start => $start,
                   5385:                                        end   => $end,
                   5386:                                        type  => $type,
                   5387:                                      };
                   5388:             }
                   5389:         }
                   5390:     } else {
                   5391:         foreach my $block (keys(%commblocks)) {
                   5392:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5393:                 my ($start,$end) = ($1,$2);
                   5394:                 if ($start <= time && $end >= time) {
                   5395:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5396:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5397:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5398:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5399:                                     push(@blockers,$block);
                   5400:                                 }
                   5401:                             }
                   5402:                         }
                   5403:                     }
                   5404:                 }
                   5405:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5406:                 my $item = $1;
                   5407:                 my $timersymb = $item; 
                   5408:                 my $type = 'map';
                   5409:                 if ($item eq 'course') {
                   5410:                     $type = 'course';
                   5411:                 } elsif ($item =~ /___\d+___/) {
                   5412:                     $type = 'resource';
                   5413:                 } else {
                   5414:                     $timersymb = &Apache::lonnet::symbread($item);
                   5415:                 }
                   5416:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5417:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5418:                 if ($start && $end) {
                   5419:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5420:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5421:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5422:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5423:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5424:                                         push(@blockers,$block);
                   5425:                                         $triggered{$block} = {
                   5426:                                                                start => $start,
                   5427:                                                                end   => $end,
                   5428:                                                                type  => $type,
                   5429:                                                              };
                   5430:                                     }
                   5431:                                 }
                   5432:                             }
1.1062    raeburn  5433:                         }
                   5434:                     }
1.490     raeburn  5435:                 }
1.1062    raeburn  5436:             }
                   5437:         }
                   5438:     }
                   5439:     foreach my $blocker (@blockers) {
                   5440:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5441:             &parse_block_record($commblocks{$blocker});
                   5442:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5443:         my ($start,$end,$triggertype);
                   5444:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5445:             ($start,$end) = ($1,$2);
                   5446:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5447:             $start = $triggered{$blocker}{'start'};
                   5448:             $end = $triggered{$blocker}{'end'};
                   5449:             $triggertype = $triggered{$blocker}{'type'};
                   5450:         }
                   5451:         if ($start) {
                   5452:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5453:             if ($triggertype) {
                   5454:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5455:             } else {
                   5456:                 push(@{$$setters{$course}{'triggers'}},0);
                   5457:             }
                   5458:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5459:                 $startblock = $start;
                   5460:                 if ($triggertype) {
                   5461:                     $triggerblock = $blocker;
1.474     raeburn  5462:                 }
                   5463:             }
1.1062    raeburn  5464:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5465:                $endblock = $end;
                   5466:                if ($triggertype) {
                   5467:                    $triggerblock = $blocker;
                   5468:                }
                   5469:             }
1.474     raeburn  5470:         }
                   5471:     }
1.1062    raeburn  5472:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5473: }
                   5474: 
                   5475: sub parse_block_record {
                   5476:     my ($record) = @_;
                   5477:     my ($setuname,$setudom,$title,$blocks);
                   5478:     if (ref($record) eq 'HASH') {
                   5479:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5480:         $title = &unescape($record->{'event'});
                   5481:         $blocks = $record->{'blocks'};
                   5482:     } else {
                   5483:         my @data = split(/:/,$record,3);
                   5484:         if (scalar(@data) eq 2) {
                   5485:             $title = $data[1];
                   5486:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5487:         } else {
                   5488:             ($setuname,$setudom,$title) = @data;
                   5489:         }
                   5490:         $blocks = { 'com' => 'on' };
                   5491:     }
                   5492:     return ($setuname,$setudom,$title,$blocks);
                   5493: }
                   5494: 
1.854     kalberla 5495: sub blocking_status {
1.1075.2.158  raeburn  5496:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5497:     my %setters;
1.890     droeschl 5498: 
1.1061    raeburn  5499: # check for active blocking
1.1075.2.158  raeburn  5500:     if ($clientip eq '') {
                   5501:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5502:     }
                   5503:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5504:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5505:     my $blocked = 0;
1.1075.2.158  raeburn  5506:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5507:         $blocked = 1;
                   5508:     }
1.890     droeschl 5509: 
1.1061    raeburn  5510: # caller just wants to know whether a block is active
                   5511:     if (!wantarray) { return $blocked; }
                   5512: 
                   5513: # build a link to a popup window containing the details
                   5514:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5515: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5516:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5517:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5518:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5519:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5520:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5521:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5522:         if ($symb) {
                   5523:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5524:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5525:         }
1.1062    raeburn  5526:     }
1.1061    raeburn  5527: 
                   5528:     my $output .= <<'END_MYBLOCK';
                   5529: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5530:     var options = "width=" + w + ",height=" + h + ",";
                   5531:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5532:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5533:     var newWin = window.open(url, wdwName, options);
                   5534:     newWin.focus();
                   5535: }
1.890     droeschl 5536: END_MYBLOCK
1.854     kalberla 5537: 
1.1061    raeburn  5538:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5539:   
1.1061    raeburn  5540:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5541:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5542:     my $class = 'LC_comblock';
1.1062    raeburn  5543:     if ($activity eq 'docs') {
                   5544:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5545:         $class = '';
1.1063    raeburn  5546:     } elsif ($activity eq 'printout') {
                   5547:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5548:     } elsif ($activity eq 'passwd') {
                   5549:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5550:     } elsif ($activity eq 'grades') {
                   5551:         $text = &mt('Gradebook Blocked');
                   5552:     } elsif ($activity eq 'search') {
                   5553:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5554:21):     } elsif ($activity eq 'alert') {
                   5555:21):         $text = &mt('Checking Critical Messages Blocked');
                   5556:21):     } elsif ($activity eq 'reinit') {
                   5557:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5558:     } elsif ($activity eq 'about') {
                   5559:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5560:     } elsif ($activity eq 'wishlist') {
                   5561:         $text = &mt('Access to Stored Links Blocked');
                   5562:     } elsif ($activity eq 'annotate') {
                   5563:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5564:     }
1.1061    raeburn  5565:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5566: <div class='$class'>
1.869     kalberla 5567:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5568:   title='$text'>
                   5569:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5570:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5571:   title='$text'>$text</a>
1.867     kalberla 5572: </div>
                   5573: 
                   5574: END_BLOCK
1.474     raeburn  5575: 
1.1061    raeburn  5576:     return ($blocked, $output);
1.854     kalberla 5577: }
1.490     raeburn  5578: 
1.60      matthew  5579: ###############################################
                   5580: 
1.682     raeburn  5581: sub check_ip_acc {
1.1075.2.105  raeburn  5582:     my ($acc,$clientip)=@_;
1.682     raeburn  5583:     &Apache::lonxml::debug("acc is $acc");
                   5584:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5585:         return 1;
                   5586:     }
                   5587:     my $allowed=0;
1.1075.2.144  raeburn  5588:     my $ip;
                   5589:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5590:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5591:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5592:     } else {
1.1075.2.150  raeburn  5593:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5594:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5595:     }
1.682     raeburn  5596: 
                   5597:     my $name;
1.1075.2.161.  .1(raebu 5598:21):     my %access = (
                   5599:21):                      allowfrom => 1,
                   5600:21):                      denyfrom  => 0,
                   5601:21):                  );
                   5602:21):     my @allows;
                   5603:21):     my @denies;
                   5604:21):     foreach my $item (split(',',$acc)) {
                   5605:21):         $item =~ s/^\s*//;
                   5606:21):         $item =~ s/\s*$//;
                   5607:21):         if ($item =~ /^\!(.+)$/) {
                   5608:21):             push(@denies,$1);
                   5609:21):         } else {
                   5610:21):             push(@allows,$item);
                   5611:21):         }
                   5612:21):     }
                   5613:21):     my $numdenies = scalar(@denies);
                   5614:21):     my $numallows = scalar(@allows);
                   5615:21):     my $count = 0;
                   5616:21):     foreach my $pattern (@denies,@allows) {
                   5617:21):         $count ++;
                   5618:21):         my $acctype = 'allowfrom';
                   5619:21):         if ($count <= $numdenies) {
                   5620:21):             $acctype = 'denyfrom';
                   5621:21):         }
1.682     raeburn  5622:         if ($pattern =~ /\*$/) {
                   5623:             #35.8.*
                   5624:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5625:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5626:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5627:             #35.8.3.[34-56]
                   5628:             my $low=$2;
                   5629:             my $high=$3;
                   5630:             $pattern=$1;
                   5631:             if ($ip =~ /^\Q$pattern\E/) {
                   5632:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5633:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5634:             }
                   5635:         } elsif ($pattern =~ /^\*/) {
                   5636:             #*.msu.edu
                   5637:             $pattern=~s/\*//;
                   5638:             if (!defined($name)) {
                   5639:                 use Socket;
                   5640:                 my $netaddr=inet_aton($ip);
                   5641:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5642:             }
1.1075.2.161.  .1(raebu 5643:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5644:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5645:             #127.0.0.1
1.1075.2.161.  .1(raebu 5646:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5647:         } else {
                   5648:             #some.name.com
                   5649:             if (!defined($name)) {
                   5650:                 use Socket;
                   5651:                 my $netaddr=inet_aton($ip);
                   5652:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5653:             }
1.1075.2.161.  .1(raebu 5654:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5655:21):         }
                   5656:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5657:21):     }
                   5658:21):     if ($allowed eq '') {
                   5659:21):         if ($numdenies && !$numallows) {
                   5660:21):             $allowed = 1;
                   5661:21):         } else {
                   5662:21):             $allowed = 0;
1.682     raeburn  5663:         }
                   5664:     }
                   5665:     return $allowed;
                   5666: }
                   5667: 
                   5668: ###############################################
                   5669: 
1.60      matthew  5670: =pod
                   5671: 
1.112     bowersj2 5672: =head1 Domain Template Functions
                   5673: 
                   5674: =over 4
                   5675: 
                   5676: =item * &determinedomain()
1.60      matthew  5677: 
                   5678: Inputs: $domain (usually will be undef)
                   5679: 
1.63      www      5680: Returns: Determines which domain should be used for designs
1.60      matthew  5681: 
                   5682: =cut
1.54      www      5683: 
1.60      matthew  5684: ###############################################
1.63      www      5685: sub determinedomain {
                   5686:     my $domain=shift;
1.531     albertel 5687:     if (! $domain) {
1.60      matthew  5688:         # Determine domain if we have not been given one
1.893     raeburn  5689:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5690:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5691:         if ($env{'request.role.domain'}) { 
                   5692:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5693:         }
                   5694:     }
1.63      www      5695:     return $domain;
                   5696: }
                   5697: ###############################################
1.517     raeburn  5698: 
1.518     albertel 5699: sub devalidate_domconfig_cache {
                   5700:     my ($udom)=@_;
                   5701:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5702: }
                   5703: 
                   5704: # ---------------------- Get domain configuration for a domain
                   5705: sub get_domainconf {
                   5706:     my ($udom) = @_;
                   5707:     my $cachetime=1800;
                   5708:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5709:     if (defined($cached)) { return %{$result}; }
                   5710: 
                   5711:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5712: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5713:     my (%designhash,%legacy);
1.518     albertel 5714:     if (keys(%domconfig) > 0) {
                   5715:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5716:             if (keys(%{$domconfig{'login'}})) {
                   5717:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5718:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5719:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5720:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5721:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5722:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5723:                                         if ($key eq 'loginvia') {
                   5724:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5725:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5726:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5727:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5728:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5729:                                                 } else {
                   5730:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5731:                                                 }
1.948     raeburn  5732:                                             }
1.1075.2.87  raeburn  5733:                                         } elsif ($key eq 'headtag') {
                   5734:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5735:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5736:                                             }
1.946     raeburn  5737:                                         }
1.1075.2.87  raeburn  5738:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5739:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5740:                                         }
1.946     raeburn  5741:                                     }
                   5742:                                 }
                   5743:                             }
1.1075.2.158  raeburn  5744:                         } elsif ($key eq 'saml') {
                   5745:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5746:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5747:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5748:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5749:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5750:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5751:                                         }
                   5752:                                     }
                   5753:                                 }
                   5754:                             }
1.946     raeburn  5755:                         } else {
                   5756:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5757:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5758:                                     $domconfig{'login'}{$key}{$img};
                   5759:                             }
1.699     raeburn  5760:                         }
                   5761:                     } else {
                   5762:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5763:                     }
1.632     raeburn  5764:                 }
                   5765:             } else {
                   5766:                 $legacy{'login'} = 1;
1.518     albertel 5767:             }
1.632     raeburn  5768:         } else {
                   5769:             $legacy{'login'} = 1;
1.518     albertel 5770:         }
                   5771:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5772:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5773:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5774:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5775:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5776:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5777:                         }
1.518     albertel 5778:                     }
                   5779:                 }
1.632     raeburn  5780:             } else {
                   5781:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5782:             }
1.632     raeburn  5783:         } else {
                   5784:             $legacy{'rolecolors'} = 1;
1.518     albertel 5785:         }
1.948     raeburn  5786:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5787:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5788:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5789:             }
                   5790:         }
1.632     raeburn  5791:         if (keys(%legacy) > 0) {
                   5792:             my %legacyhash = &get_legacy_domconf($udom);
                   5793:             foreach my $item (keys(%legacyhash)) {
                   5794:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5795:                     if ($legacy{'login'}) { 
                   5796:                         $designhash{$item} = $legacyhash{$item};
                   5797:                     }
                   5798:                 } else {
                   5799:                     if ($legacy{'rolecolors'}) {
                   5800:                         $designhash{$item} = $legacyhash{$item};
                   5801:                     }
1.518     albertel 5802:                 }
                   5803:             }
                   5804:         }
1.632     raeburn  5805:     } else {
                   5806:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5807:     }
                   5808:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5809: 				  $cachetime);
                   5810:     return %designhash;
                   5811: }
                   5812: 
1.632     raeburn  5813: sub get_legacy_domconf {
                   5814:     my ($udom) = @_;
                   5815:     my %legacyhash;
                   5816:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5817:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5818:     if (-e $designfile) {
1.1075.2.128  raeburn  5819:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5820:             while (my $line = <$fh>) {
                   5821:                 next if ($line =~ /^\#/);
                   5822:                 chomp($line);
                   5823:                 my ($key,$val)=(split(/\=/,$line));
                   5824:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5825:             }
                   5826:             close($fh);
                   5827:         }
                   5828:     }
1.1026    raeburn  5829:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5830:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5831:     }
                   5832:     return %legacyhash;
                   5833: }
                   5834: 
1.63      www      5835: =pod
                   5836: 
1.112     bowersj2 5837: =item * &domainlogo()
1.63      www      5838: 
                   5839: Inputs: $domain (usually will be undef)
                   5840: 
                   5841: Returns: A link to a domain logo, if the domain logo exists.
                   5842: If the domain logo does not exist, a description of the domain.
                   5843: 
                   5844: =cut
1.112     bowersj2 5845: 
1.63      www      5846: ###############################################
                   5847: sub domainlogo {
1.517     raeburn  5848:     my $domain = &determinedomain(shift);
1.518     albertel 5849:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5850:     # See if there is a logo
                   5851:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5852:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5853:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5854: 	    if ($imgsrc =~ m{^/res/}) {
                   5855: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5856: 		&Apache::lonnet::repcopy($local_name);
                   5857: 	    }
                   5858: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5859:22):         }
                   5860:22):         my $alttext = $domain;
                   5861:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5862:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5863:22):         }
                   5864:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5865:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5866:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5867:     } else {
1.60      matthew  5868:         return '';
1.59      www      5869:     }
                   5870: }
1.63      www      5871: ##############################################
                   5872: 
                   5873: =pod
                   5874: 
1.112     bowersj2 5875: =item * &designparm()
1.63      www      5876: 
                   5877: Inputs: $which parameter; $domain (usually will be undef)
                   5878: 
                   5879: Returns: value of designparamter $which
                   5880: 
                   5881: =cut
1.112     bowersj2 5882: 
1.397     albertel 5883: 
1.400     albertel 5884: ##############################################
1.397     albertel 5885: sub designparm {
                   5886:     my ($which,$domain)=@_;
                   5887:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5888:         return $env{'environment.color.'.$which};
1.96      www      5889:     }
1.63      www      5890:     $domain=&determinedomain($domain);
1.1016    raeburn  5891:     my %domdesign;
                   5892:     unless ($domain eq 'public') {
                   5893:         %domdesign = &get_domainconf($domain);
                   5894:     }
1.520     raeburn  5895:     my $output;
1.517     raeburn  5896:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5897:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5898:     } else {
1.520     raeburn  5899:         $output = $defaultdesign{$which};
                   5900:     }
                   5901:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5902:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5903:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5904:             if ($output =~ m{^/res/}) {
                   5905:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5906:                 &Apache::lonnet::repcopy($local_name);
                   5907:             }
1.520     raeburn  5908:             $output = &lonhttpdurl($output);
                   5909:         }
1.63      www      5910:     }
1.520     raeburn  5911:     return $output;
1.63      www      5912: }
1.59      www      5913: 
1.822     bisitz   5914: ##############################################
                   5915: =pod
                   5916: 
1.832     bisitz   5917: =item * &authorspace()
                   5918: 
1.1028    raeburn  5919: Inputs: $url (usually will be undef).
1.832     bisitz   5920: 
1.1075.2.40  raeburn  5921: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5922:          directory being viewed (or for which action is being taken). 
                   5923:          If $url is provided, and begins /priv/<domain>/<uname>
                   5924:          the path will be that portion of the $context argument.
                   5925:          Otherwise the path will be for the author space of the current
                   5926:          user when the current role is author, or for that of the 
                   5927:          co-author/assistant co-author space when the current role 
                   5928:          is co-author or assistant co-author.
1.832     bisitz   5929: 
                   5930: =cut
                   5931: 
                   5932: sub authorspace {
1.1028    raeburn  5933:     my ($url) = @_;
                   5934:     if ($url ne '') {
                   5935:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5936:            return $1;
                   5937:         }
                   5938:     }
1.832     bisitz   5939:     my $caname = '';
1.1024    www      5940:     my $cadom = '';
1.1028    raeburn  5941:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5942:         ($cadom,$caname) =
1.832     bisitz   5943:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5944:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5945:         $caname = $env{'user.name'};
1.1024    www      5946:         $cadom = $env{'user.domain'};
1.832     bisitz   5947:     }
1.1028    raeburn  5948:     if (($caname ne '') && ($cadom ne '')) {
                   5949:         return "/priv/$cadom/$caname/";
                   5950:     }
                   5951:     return;
1.832     bisitz   5952: }
                   5953: 
                   5954: ##############################################
                   5955: =pod
                   5956: 
1.822     bisitz   5957: =item * &head_subbox()
                   5958: 
                   5959: Inputs: $content (contains HTML code with page functions, etc.)
                   5960: 
                   5961: Returns: HTML div with $content
                   5962:          To be included in page header
                   5963: 
                   5964: =cut
                   5965: 
                   5966: sub head_subbox {
                   5967:     my ($content)=@_;
                   5968:     my $output =
1.993     raeburn  5969:         '<div class="LC_head_subbox">'
1.822     bisitz   5970:        .$content
                   5971:        .'</div>'
                   5972: }
                   5973: 
                   5974: ##############################################
                   5975: =pod
                   5976: 
                   5977: =item * &CSTR_pageheader()
                   5978: 
1.1026    raeburn  5979: Input: (optional) filename from which breadcrumb trail is built.
                   5980:        In most cases no input as needed, as $env{'request.filename'}
                   5981:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5982:22):        frameset flag
                   5983:22):        If page header is being requested for use in a frameset, then
                   5984:22):        the second (option) argument -- frameset will be true, and
                   5985:22):        the target attribute set for links should be target="_parent".
          .26(raeb 5986:-24):        If $title is supplied as the third arg, that will be used to
                   5987:-24):        the left of the breadcrumbs tail for the current path.
1.822     bisitz   5988: 
                   5989: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5990:          To be included on Authoring Space pages
1.822     bisitz   5991: 
                   5992: =cut
                   5993: 
                   5994: sub CSTR_pageheader {
1.1075.2.161.  .26(raeb 5995:-24):     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  5996:     if ($trailfile eq '') {
                   5997:         $trailfile = $env{'request.filename'};
                   5998:     }
                   5999: 
                   6000: # this is for resources; directories have customtitle, and crumbs
                   6001: # and select recent are created in lonpubdir.pm
                   6002: 
                   6003:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6004:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  6005:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6006:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6007:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6008: 
                   6009:     my $parentpath = '';
                   6010:     my $lastitem = '';
                   6011:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6012:         $parentpath = $1;
                   6013:         $lastitem = $2;
                   6014:     } else {
                   6015:         $lastitem = $thisdisfn;
                   6016:     }
1.921     bisitz   6017: 
1.1075.2.161.  .26(raeb 6018:-24):     if ($title eq '') {
                   6019:-24):         $title = &mt('Authoring Space');
                   6020:-24):     }
                   6021:-24): 
          .6(raebu 6022:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6023:22):     if ($frameset) {
                   6024:22):         $target = ' target="_parent"';
                   6025:22):         $crumbtarget = '_parent';
          .17(raeb 6026:-23):     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   6027:-23):         $target = '';
                   6028:-23):         $crumbtarget = '';
          .6(raebu 6029:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   6030:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6031:22):         $crumbtarget = $env{'request.deeplink.target'};
                   6032:22):     }
                   6033:22): 
1.921     bisitz   6034:     my $output =
1.822     bisitz   6035:          '<div>'
                   6036:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.161.  .26(raeb 6037:-24):         .'<b>'.$title.'</b> '
          .6(raebu 6038:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6039:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6040: 
                   6041:     if ($lastitem) {
                   6042:         $output .=
                   6043:              '<span class="LC_filename">'
                   6044:             .$lastitem
                   6045:             .'</span>';
                   6046:     }
                   6047:     $output .=
                   6048:          '<br />'
1.1075.2.161.  .6(raebu 6049:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   6050:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6051:         .'</form>'
1.1075.2.161.  .6(raebu 6052:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   6053:         .'</div>';
1.921     bisitz   6054: 
                   6055:     return $output;
1.822     bisitz   6056: }
                   6057: 
1.1075.2.161.  .21(raeb 6058:-24): ##############################################
                   6059:-24): =pod
                   6060:-24): 
                   6061:-24): =item * &nocodemirror()
                   6062:-24): 
                   6063:-24): Input: None
                   6064:-24): 
                   6065:-24): Returns: 1 if CodeMirror is deactivated based on
                   6066:-24):          user's preference, or domain default,
                   6067:-24):          if user indicated use of default.
                   6068:-24): 
                   6069:-24): =cut
                   6070:-24): 
                   6071:-24): sub nocodemirror {
                   6072:-24):     my $nocodem = $env{'environment.nocodemirror'};
                   6073:-24):     unless ($nocodem) {
                   6074:-24):         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6075:-24):         if ($domdefs{'nocodemirror'}) {
                   6076:-24):             $nocodem = 'yes';
                   6077:-24):         }
                   6078:-24):     }
                   6079:-24):     if ($nocodem eq 'yes') {
                   6080:-24):         return 1;
                   6081:-24):     }
                   6082:-24):     return;
                   6083:-24): }
                   6084:-24): 
                   6085:-24): ##############################################
                   6086:-24): =pod
                   6087:-24): 
                   6088:-24): =item * &permitted_editors()
                   6089:-24): 
                   6090:-24): Input: $uri (optional)
                   6091:-24): 
                   6092:-24): Returns: %editors hash in which keys are editors
          .25(raeb 6093:-24):          permitted in current Authoring Space,
                   6094:-24):          or in current course for web pages
                   6095:-24):          created in a course.
                   6096:-24): 
          .21(raeb 6097:-24):          Value for each key is 1. Possible keys
          .25(raeb 6098:-24):          are: edit, xml, and daxe. 
                   6099:-24): 
                   6100:-24):          For a regular Authoring Space, if no specific
          .21(raeb 6101:-24):          set of editors has been set for the Author
                   6102:-24):          who owns the Authoring Space, then the
                   6103:-24):          domain default will be used.  If no domain
                   6104:-24):          default has been set, then the keys will be
                   6105:-24):          edit and xml.
                   6106:-24): 
          .25(raeb 6107:-24):          For a course author, or for web pages created
                   6108:-24):          in a course, if no specific set of editors has
                   6109:-24):          been set for the course, then the domain
                   6110:-24):          course default will be used. If no domain
                   6111:-24):          course default has been set, then the keys
                   6112:-24):          will be edit and xml.
                   6113:-24): 
          .21(raeb 6114:-24): =cut
                   6115:-24): 
                   6116:-24): sub permitted_editors {
                   6117:-24):     my ($uri) = @_;
          .25(raeb 6118:-24):     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
          .21(raeb 6119:-24):     if ($env{'request.role'} =~ m{^au\./}) {
                   6120:-24):         $is_author = 1;
                   6121:-24):     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6122:-24):         ($audom,$auname) = ($1,$2);
                   6123:-24):         if (($audom ne '') && ($auname ne '')) {
                   6124:-24):             if (($env{'user.domain'} eq $audom) &&
                   6125:-24):                 ($env{'user.name'} eq $auname)) {
                   6126:-24):                 $is_author = 1;
                   6127:-24):             } else {
                   6128:-24):                 $is_coauthor = 1;
                   6129:-24):             }
                   6130:-24):         }
                   6131:-24):     } elsif ($env{'request.course.id'}) {
          .25(raeb 6132:-24):         my ($cdom,$cnum);
                   6133:-24):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6134:-24):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6135:-24):         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
                   6136:-24):             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6137:-24):             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
                   6138:-24):             $is_course = 1;
                   6139:-24):         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
          .21(raeb 6140:-24):             ($audom,$auname) = ($1,$2);
                   6141:-24):         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6142:-24):             ($audom,$auname) = ($1,$2);
                   6143:-24):         } elsif (($uri eq '/daxesave') &&
          .25(raeb 6144:-24):                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6145:-24):                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6146:-24):             $is_course = 1;
                   6147:-24):         } elsif (($uri eq '/daxesave') &&
          .21(raeb 6148:-24):                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6149:-24):             ($audom,$auname) = ($1,$2);
                   6150:-24):         }
          .25(raeb 6151:-24):         unless ($is_course) {
                   6152:-24):             if (($audom ne '') && ($auname ne '')) {
                   6153:-24):                 if (($env{'user.domain'} eq $audom) &&
                   6154:-24):                     ($env{'user.name'} eq $auname)) {
                   6155:-24):                     $is_author = 1;
                   6156:-24):                 } else {
                   6157:-24):                     $is_coauthor = 1;
                   6158:-24):                 }
          .21(raeb 6159:-24):             }
                   6160:-24):         }
                   6161:-24):     }
                   6162:-24):     if ($is_author) {
                   6163:-24):         if (exists($env{'environment.editors'})) {
                   6164:-24):             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6165:-24):         } else {
                   6166:-24):             %editors = ( edit => 1,
                   6167:-24):                          xml => 1,
                   6168:-24):                        );
                   6169:-24):         }
                   6170:-24):     } elsif ($is_coauthor) {
                   6171:-24):         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6172:-24):             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6173:-24):         } else {
                   6174:-24):             %editors = ( edit => 1,
                   6175:-24):                          xml => 1,
                   6176:-24):                        );
                   6177:-24):         }
          .25(raeb 6178:-24):     } elsif ($is_course) {
                   6179:-24):         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6180:-24):             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6181:-24):         } else {
                   6182:-24):             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6183:-24):             if (exists($domdefaults{'crseditors'})) {
                   6184:-24):                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6185:-24):             } else {
                   6186:-24):                 %editors = ( edit => 1,
                   6187:-24):                              xml => 1,
                   6188:-24):                            );
                   6189:-24):             }
                   6190:-24):         }
          .21(raeb 6191:-24):     } else {
                   6192:-24):         %editors = ( edit => 1,
                   6193:-24):                      xml => 1,
                   6194:-24):                    );
                   6195:-24):     }
                   6196:-24):     return %editors;
                   6197:-24): }
                   6198:-24): 
1.60      matthew  6199: ###############################################
                   6200: ###############################################
                   6201: 
                   6202: =pod
                   6203: 
1.112     bowersj2 6204: =back
                   6205: 
1.549     albertel 6206: =head1 HTML Helpers
1.112     bowersj2 6207: 
                   6208: =over 4
                   6209: 
                   6210: =item * &bodytag()
1.60      matthew  6211: 
                   6212: Returns a uniform header for LON-CAPA web pages.
                   6213: 
                   6214: Inputs: 
                   6215: 
1.112     bowersj2 6216: =over 4
                   6217: 
                   6218: =item * $title, A title to be displayed on the page.
                   6219: 
                   6220: =item * $function, the current role (can be undef).
                   6221: 
                   6222: =item * $addentries, extra parameters for the <body> tag.
                   6223: 
                   6224: =item * $bodyonly, if defined, only return the <body> tag.
                   6225: 
                   6226: =item * $domain, if defined, force a given domain.
                   6227: 
                   6228: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6229:             text interface only)
1.60      matthew  6230: 
1.814     bisitz   6231: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6232:                      navigational links
1.317     albertel 6233: 
1.338     albertel 6234: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6235: 
1.1075.2.12  raeburn  6236: =item * $no_inline_link, if true and in remote mode, don't show the
                   6237:          'Switch To Inline Menu' link
                   6238: 
1.460     albertel 6239: =item * $args, optional argument valid values are
                   6240:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  6241:             use_absolute     -> for external resource or syllabus, this will
                   6242:                                 contain https://<hostname> if server uses
                   6243:                                 https (as per hosts.tab), but request is for http
                   6244:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6245: 
1.1075.2.15  raeburn  6246: =item * $advtoolsref, optional argument, ref to an array containing
                   6247:             inlineremote items to be added in "Functions" menu below
                   6248:             breadcrumbs.
                   6249: 
1.1075.2.161.  .1(raebu 6250:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   6251:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   6252:21):             the scope of use, i.e., launch was for access to a single, a map
                   6253:21):             or the entire course.
                   6254:21): 
                   6255:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6256:21):             context, this will contain the URL for the landing item in
                   6257:21):             the course, after launch from an LTI Consumer
                   6258:21): 
                   6259:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6260:21):             context, this will contain a reference to hash of items
                   6261:21):             to be included in the page header and/or inline menu.
                   6262:21): 
          .8(raebu 6263:22): =item * $menucoll, optional argument, if specific menu collection is in
                   6264:22):             effect, either set as the default for the course, or set for
                   6265:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   6266:22):             then $menucoll will be the number of that collection.
                   6267:22): 
                   6268:22): =item * $menuref, optional argument, reference to a hash, containing the
                   6269:22):             menu options included for the menu in effect, based on the
                   6270:22):             configuration for the numbered menu collection in use.
                   6271:22): 
                   6272:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6273:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6274:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   6275:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6276:22):             being called a second time.
                   6277:22): 
1.112     bowersj2 6278: =back
                   6279: 
1.60      matthew  6280: Returns: A uniform header for LON-CAPA web pages.  
                   6281: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6282: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6283: other decorations will be returned.
                   6284: 
                   6285: =cut
                   6286: 
1.54      www      6287: sub bodytag {
1.831     bisitz   6288:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 6289:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 6290:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6291: 
1.954     raeburn  6292:     my $public;
                   6293:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6294:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6295:         $public = 1;
                   6296:     }
1.460     albertel 6297:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  6298:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  6299:     my $hostname = $args->{'hostname'};
1.339     albertel 6300: 
1.183     matthew  6301:     $function = &get_users_function() if (!$function);
1.339     albertel 6302:     my $img =    &designparm($function.'.img',$domain);
                   6303:     my $font =   &designparm($function.'.font',$domain);
                   6304:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6305: 
1.803     bisitz   6306:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6307: 		   'bgcolor' => $pgbg,
1.339     albertel 6308: 		   'text'    => $font,
                   6309:                    'alink'   => &designparm($function.'.alink',$domain),
                   6310: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6311: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6312:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6313: 
1.63      www      6314:  # role and realm
1.1075.2.68  raeburn  6315:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6316:     if ($realm) {
                   6317:         $realm = '/'.$realm;
                   6318:     }
1.1075.2.159  raeburn  6319:     if ($role eq 'ca') {
1.479     albertel 6320:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6321:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6322:     } 
1.55      www      6323: # realm
1.1075.2.158  raeburn  6324:     my ($cid,$sec);
1.258     albertel 6325:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  6326:         $cid = $env{'request.course.id'};
                   6327:         if ($env{'request.course.sec'}) {
                   6328:             $sec = $env{'request.course.sec'};
                   6329:         }
                   6330:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6331:         if (&Apache::lonnet::is_course($1,$2)) {
                   6332:             $cid = $1.'_'.$2;
                   6333:             $sec = $3;
                   6334:         }
                   6335:     }
                   6336:     if ($cid) {
1.378     raeburn  6337:         if ($env{'request.role'} !~ /^cr/) {
                   6338:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6339:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6340:             if ($env{'request.role.desc'}) {
                   6341:                 $role = $env{'request.role.desc'};
                   6342:             } else {
                   6343:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6344:             }
1.1075.2.115  raeburn  6345:         } else {
                   6346:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6347:         }
1.1075.2.158  raeburn  6348:         if ($sec) {
                   6349:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6350:         }   
1.1075.2.158  raeburn  6351: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6352:     } else {
                   6353:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6354:     }
1.433     albertel 6355: 
1.359     albertel 6356:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6357: 
1.438     albertel 6358:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6359: 
1.101     www      6360: # construct main body tag
1.359     albertel 6361:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6362: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6363: 
1.1075.2.38  raeburn  6364:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6365: 
                   6366:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6367:         return $bodytag;
1.1075.2.38  raeburn  6368:     }
1.359     albertel 6369: 
1.954     raeburn  6370:     if ($public) {
1.433     albertel 6371: 	undef($role);
                   6372:     }
1.1075.2.158  raeburn  6373: 
1.1075.2.161.  .1(raebu 6374:21):     my $showcrstitle = 1;
                   6375:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6376:21):         if (ref($ltimenu) eq 'HASH') {
                   6377:21):             unless ($ltimenu->{'role'}) {
                   6378:21):                 undef($role);
                   6379:21):             }
                   6380:21):             unless ($ltimenu->{'coursetitle'}) {
                   6381:21):                 $realm='&nbsp;';
                   6382:21):                 $showcrstitle = 0;
                   6383:21):             }
                   6384:21):         }
                   6385:21):     } elsif (($cid) && ($menucoll)) {
                   6386:21):         if (ref($menuref) eq 'HASH') {
                   6387:21):             unless ($menuref->{'role'}) {
                   6388:21):                 undef($role);
                   6389:21):             }
                   6390:21):             unless ($menuref->{'crs'}) {
                   6391:21):                 $realm='&nbsp;';
                   6392:21):                 $showcrstitle = 0;
                   6393:21):             }
                   6394:21):         }
                   6395:21):     }
                   6396:21): 
1.762     bisitz   6397:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6398:     #
                   6399:     # Extra info if you are the DC
                   6400:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6401:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6402:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6403:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6404:         $dc_info =~ s/\s+$//;
1.359     albertel 6405:     }
                   6406: 
1.1075.2.161.  .1(raebu 6407:21):     my $crstype;
                   6408:21):     if ($cid) {
                   6409:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6410:21):     } elsif ($args->{'crstype'}) {
                   6411:21):         $crstype = $args->{'crstype'};
                   6412:21):     }
                   6413:21): 
1.1075.2.108  raeburn  6414:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6415: 
1.1075.2.13  raeburn  6416:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6417: 
1.1075.2.38  raeburn  6418: 
                   6419: 
1.1075.2.21  raeburn  6420:     my $funclist;
                   6421:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  6422:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  6423:                     Apache::lonmenu::serverform();
                   6424:         my $forbodytag;
                   6425:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6426:                                             $forcereg,$args->{'group'},
                   6427:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6428:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  6429:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6430:             $funclist = $forbodytag;
                   6431:         }
                   6432:     } else {
1.903     droeschl 6433: 
                   6434:         #    if ($env{'request.state'} eq 'construct') {
                   6435:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6436:         #    }
                   6437: 
1.1075.2.38  raeburn  6438:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6439:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6440: 
1.1075.2.161.  .23(raeb 6441:-24):         my $collapsible;
          .21(raeb 6442:-24):         if ($args->{'collapsible_header'} ne '') {
          .23(raeb 6443:-24):             $collapsible = 1;
                   6444:-24):             my ($menustate,$tiptext,$divclass);
                   6445:-24):             if ($args->{'start_collapsed'}) {
                   6446:-24):                 $menustate = 'collapsed';
                   6447:-24):                 $tiptext = 'display';
                   6448:-24):                 $divclass = 'hidden';
                   6449:-24):             } else {
                   6450:-24):                 $menustate = 'expanded';
                   6451:-24):                 $tiptext = 'hide';
                   6452:-24):                 $divclass = 'shown';
                   6453:-24):             }
                   6454:-24):             my $alttext = &mt('menu state: '.$menustate);
                   6455:-24):             my $tooltip = &mt($tiptext.' standard menus');
          .21(raeb 6456:-24):             $bodytag .= <<"END";
                   6457:-24): <div id="LC_expandingContainer" style="display:inline;">
                   6458:-24): <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
          .23(raeb 6459:-24): <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   6460:-24): <div class="LC_menus_content $divclass">
          .21(raeb 6461:-24): END
                   6462:-24):         }
          .1(raebu 6463:21):         unless ($args->{'no_primary_menu'}) {
          .4(raebu 6464:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6465:22):                                                               $args->{'links_disabled'},
          .21(raeb 6466:-24):                                                               $args->{'links_target'},
          .23(raeb 6467:-24):                                                               $collapsible);
          .1(raebu 6468:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6469:21):                 if ($dc_info) {
                   6470:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6471:21):                 }
                   6472:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6473:21):                                <em>$realm</em> $dc_info</div>|;
                   6474:21):                 return $bodytag;
1.1075.2.1  raeburn  6475:             }
1.894     droeschl 6476: 
1.1075.2.161.  .1(raebu 6477:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6478:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6479:21):             }
1.916     droeschl 6480: 
1.1075.2.161.  .1(raebu 6481:21):             $bodytag .= $right;
1.852     droeschl 6482: 
1.1075.2.161.  .1(raebu 6483:21):             if ($dc_info) {
                   6484:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6485:21):             }
                   6486:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6487:         }
1.916     droeschl 6488: 
1.1075.2.61  raeburn  6489:         #if directed to not display the secondary menu, don't.
                   6490:         if ($args->{'no_secondary_menu'}) {
                   6491:             return $bodytag;
                   6492:         }
1.903     droeschl 6493:         #don't show menus for public users
1.954     raeburn  6494:         if (!$public){
1.1075.2.161.  .1(raebu 6495:21):             unless ($args->{'no_inline_menu'}) {
                   6496:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6497:21):                                                             $args->{'no_primary_menu'},
                   6498:21):                                                             $menucoll,$menuref,
          .6(raebu 6499:22):                                                             $args->{'links_disabled'},
                   6500:22):                                                             $args->{'links_target'});
          .1(raebu 6501:21):             }
1.903     droeschl 6502:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6503:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6504:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6505:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6506:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6507:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6508:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6509:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6510:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6511:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6512:             } else {
1.1075.2.21  raeburn  6513:                 my $forbodytag;
                   6514:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6515:                                                     $forcereg,$args->{'group'},
                   6516:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6517:                                                     $advtoolsref,'',$hostname,
                   6518:                                                     \$forbodytag);
1.1075.2.21  raeburn  6519:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6520:                     $bodytag .= $forbodytag;
                   6521:                 }
1.920     raeburn  6522:             }
1.903     droeschl 6523:         }else{
                   6524:             # this is to seperate menu from content when there's no secondary
                   6525:             # menu. Especially needed for public accessible ressources.
                   6526:             $bodytag .= '<hr style="clear:both" />';
                   6527:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6528:         }
1.1075.2.161.  .21(raeb 6529:-24):         if ($args->{'collapsible_header'} ne '') {
                   6530:-24):             $bodytag .= $args->{'collapsible_header'}.
                   6531:-24):                         '<div id="LC_collapsible_separator"></div>'.
                   6532:-24):                         '</div></div>';
                   6533:-24):         }
1.235     raeburn  6534:         return $bodytag;
1.1075.2.12  raeburn  6535:     }
                   6536: 
                   6537: #
                   6538: # Top frame rendering, Remote is up
                   6539: #
                   6540: 
                   6541:     my $imgsrc = $img;
                   6542:     if ($img =~ /^\/adm/) {
                   6543:         $imgsrc = &lonhttpdurl($img);
                   6544:     }
                   6545:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   6546: 
1.1075.2.60  raeburn  6547:     my $help=($no_inline_link?''
                   6548:               :&Apache::loncommon::top_nav_help('Help'));
                   6549: 
1.1075.2.12  raeburn  6550:     # Explicit link to get inline menu
                   6551:     my $menu= ($no_inline_link?''
                   6552:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6553: 
                   6554:     if ($dc_info) {
                   6555:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6556:     }
                   6557: 
1.1075.2.38  raeburn  6558:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6559:     unless ($public) {
                   6560:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6561:                                 undef,'LC_menubuttons_link');
                   6562:     }
                   6563: 
1.1075.2.12  raeburn  6564:     unless ($env{'form.inhibitmenu'}) {
                   6565:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  6566:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  6567:                        <li>$help</li>
1.1075.2.12  raeburn  6568:                        <li>$menu</li>
                   6569:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6570:     }
1.1075.2.13  raeburn  6571:     if ($env{'request.state'} eq 'construct') {
                   6572:         if (!$public){
                   6573:             if ($env{'request.state'} eq 'construct') {
                   6574:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6575:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  6576:                             &Apache::lonhtmlcommon::scripttag('','end').
                   6577:                             &Apache::lonmenu::innerregister($forcereg,
                   6578:                                                             $args->{'bread_crumbs'});
                   6579:             }
                   6580:         }
                   6581:     }
1.1075.2.21  raeburn  6582:     return $bodytag."\n".$funclist;
1.182     matthew  6583: }
                   6584: 
1.917     raeburn  6585: sub dc_courseid_toggle {
                   6586:     my ($dc_info) = @_;
1.980     raeburn  6587:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6588:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6589:            &mt('(More ...)').'</a></span>'.
                   6590:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6591: }
                   6592: 
1.330     albertel 6593: sub make_attr_string {
                   6594:     my ($register,$attr_ref) = @_;
                   6595: 
                   6596:     if ($attr_ref && !ref($attr_ref)) {
                   6597: 	die("addentries Must be a hash ref ".
                   6598: 	    join(':',caller(1))." ".
                   6599: 	    join(':',caller(0))." ");
                   6600:     }
                   6601: 
                   6602:     if ($register) {
1.339     albertel 6603: 	my ($on_load,$on_unload);
                   6604: 	foreach my $key (keys(%{$attr_ref})) {
                   6605: 	    if      (lc($key) eq 'onload') {
                   6606: 		$on_load.=$attr_ref->{$key}.';';
                   6607: 		delete($attr_ref->{$key});
                   6608: 
                   6609: 	    } elsif (lc($key) eq 'onunload') {
                   6610: 		$on_unload.=$attr_ref->{$key}.';';
                   6611: 		delete($attr_ref->{$key});
                   6612: 	    }
                   6613: 	}
1.1075.2.12  raeburn  6614:         if ($env{'environment.remote'} eq 'on') {
                   6615:             $attr_ref->{'onload'}  =
                   6616:                 &Apache::lonmenu::loadevents().  $on_load;
                   6617:             $attr_ref->{'onunload'}=
                   6618:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6619:         } else {  
                   6620: 	    $attr_ref->{'onload'}  = $on_load;
                   6621: 	    $attr_ref->{'onunload'}= $on_unload;
                   6622:         }
1.330     albertel 6623:     }
1.339     albertel 6624: 
1.330     albertel 6625:     my $attr_string;
1.1075.2.56  raeburn  6626:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6627: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6628:     }
                   6629:     return $attr_string;
                   6630: }
                   6631: 
                   6632: 
1.182     matthew  6633: ###############################################
1.251     albertel 6634: ###############################################
                   6635: 
                   6636: =pod
                   6637: 
                   6638: =item * &endbodytag()
                   6639: 
                   6640: Returns a uniform footer for LON-CAPA web pages.
                   6641: 
1.635     raeburn  6642: Inputs: 1 - optional reference to an args hash
                   6643: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6644: a 'Continue' link is not displayed if the page contains an
                   6645: internal redirect in the <head></head> section,
                   6646: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6647: 
                   6648: =cut
                   6649: 
                   6650: sub endbodytag {
1.635     raeburn  6651:     my ($args) = @_;
1.1075.2.6  raeburn  6652:     my $endbodytag;
                   6653:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6654:         $endbodytag='</body>';
                   6655:     }
1.315     albertel 6656:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6657:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6658:22):             my ($endbodyjs,$idattr);
                   6659:22):             if ($env{'internal.head.to_opener'}) {
                   6660:22):                 my $linkid = 'LC_continue_link';
                   6661:22):                 $idattr = ' id="'.$linkid.'"';
                   6662:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6663:22):                 $endbodyjs=<<ENDJS;
                   6664:22): <script type="text/javascript">
                   6665:22): // <![CDATA[
                   6666:22): function ebFunction(evt) {
                   6667:22):     evt.preventDefault();
                   6668:22):     var dest = '$redirect_for_js';
                   6669:22):     if (window.opener != null && !window.opener.closed) {
                   6670:22):         window.opener.location.href=dest;
                   6671:22):         window.close();
                   6672:22):     } else {
                   6673:22):         window.location.href=dest;
                   6674:22):     }
                   6675:22):     return false;
                   6676:22): }
                   6677:22): 
                   6678:22): \$(document).ready(function () {
                   6679:22):   if (document.getElementById('$linkid')) {
                   6680:22):     var clickelem = document.getElementById('$linkid');
                   6681:22):     clickelem.addEventListener('click',ebFunction,false);
                   6682:22):   }
                   6683:22): });
                   6684:22): // ]]>
                   6685:22): </script>
                   6686:22): ENDJS
                   6687:22):             }
1.635     raeburn  6688: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6689:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6690: 	        &mt('Continue').'</a>'.
                   6691: 	        $endbodytag;
                   6692:         }
1.315     albertel 6693:     }
1.1075.2.161.  .19(raeb 6694:-23):     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   6695:-23):         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   6696:-23):     }
1.251     albertel 6697:     return $endbodytag;
                   6698: }
                   6699: 
1.352     albertel 6700: =pod
                   6701: 
                   6702: =item * &standard_css()
                   6703: 
                   6704: Returns a style sheet
                   6705: 
                   6706: Inputs: (all optional)
                   6707:             domain         -> force to color decorate a page for a specific
                   6708:                                domain
                   6709:             function       -> force usage of a specific rolish color scheme
                   6710:             bgcolor        -> override the default page bgcolor
                   6711: 
                   6712: =cut
                   6713: 
1.343     albertel 6714: sub standard_css {
1.345     albertel 6715:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6716:     $function  = &get_users_function() if (!$function);
                   6717:     my $img    = &designparm($function.'.img',   $domain);
                   6718:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6719:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6720:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6721: #second colour for later usage
1.345     albertel 6722:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6723:     my $pgbg_or_bgcolor =
                   6724: 	         $bgcolor ||
1.352     albertel 6725: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6726:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6727:     my $alink  = &designparm($function.'.alink', $domain);
                   6728:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6729:     my $link   = &designparm($function.'.link',  $domain);
                   6730: 
1.602     albertel 6731:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6732:     my $mono                 = 'monospace';
1.850     bisitz   6733:     my $data_table_head      = $sidebg;
                   6734:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6735:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6736:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6737:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6738:     my $mail_new             = '#FFBB77';
                   6739:     my $mail_new_hover       = '#DD9955';
                   6740:     my $mail_read            = '#BBBB77';
                   6741:     my $mail_read_hover      = '#999944';
                   6742:     my $mail_replied         = '#AAAA88';
                   6743:     my $mail_replied_hover   = '#888855';
                   6744:     my $mail_other           = '#99BBBB';
                   6745:     my $mail_other_hover     = '#669999';
1.391     albertel 6746:     my $table_header         = '#DDDDDD';
1.489     raeburn  6747:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6748:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6749:     my $button_hover         = '#BF2317';
1.392     albertel 6750: 
1.608     albertel 6751:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6752:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6753:                                              : '0 3px 0 4px';
1.448     albertel 6754: 
1.523     albertel 6755: 
1.343     albertel 6756:     return <<END;
1.947     droeschl 6757: 
                   6758: /* needed for iframe to allow 100% height in FF */
                   6759: body, html { 
                   6760:     margin: 0;
                   6761:     padding: 0 0.5%;
                   6762:     height: 99%; /* to avoid scrollbars */
                   6763: }
                   6764: 
1.795     www      6765: body {
1.911     bisitz   6766:   font-family: $sans;
                   6767:   line-height:130%;
                   6768:   font-size:0.83em;
                   6769:   color:$font;
1.795     www      6770: }
                   6771: 
1.959     onken    6772: a:focus,
                   6773: a:focus img {
1.795     www      6774:   color: red;
                   6775: }
1.698     harmsja  6776: 
1.911     bisitz   6777: form, .inline {
                   6778:   display: inline;
1.795     www      6779: }
1.721     harmsja  6780: 
1.1075.2.161.  .21(raeb 6781:-24): .LC_menus_content.shown{
          .24(raeb 6782:-24):   display: block;
          .21(raeb 6783:-24): }
                   6784:-24): 
                   6785:-24): .LC_menus_content.hidden {
                   6786:-24):   display: none;
                   6787:-24): }
                   6788:-24): 
1.795     www      6789: .LC_right {
1.911     bisitz   6790:   text-align:right;
1.795     www      6791: }
                   6792: 
                   6793: .LC_middle {
1.911     bisitz   6794:   vertical-align:middle;
1.795     www      6795: }
1.721     harmsja  6796: 
1.1075.2.38  raeburn  6797: .LC_floatleft {
                   6798:   float: left;
                   6799: }
                   6800: 
                   6801: .LC_floatright {
                   6802:   float: right;
                   6803: }
                   6804: 
1.911     bisitz   6805: .LC_400Box {
                   6806:   width:400px;
                   6807: }
1.721     harmsja  6808: 
1.1075.2.161.  .21(raeb 6809:-24): #LC_collapsible_separator {
                   6810:-24):     border: 1px solid black;
                   6811:-24):     width: 99.9%;
                   6812:-24):     height: 0px;
                   6813:-24): }
                   6814:-24): 
1.947     droeschl 6815: .LC_iframecontainer {
                   6816:     width: 98%;
                   6817:     margin: 0;
                   6818:     position: fixed;
                   6819:     top: 8.5em;
                   6820:     bottom: 0;
                   6821: }
                   6822: 
                   6823: .LC_iframecontainer iframe{
                   6824:     border: none;
                   6825:     width: 100%;
                   6826:     height: 100%;
                   6827: }
                   6828: 
1.778     bisitz   6829: .LC_filename {
                   6830:   font-family: $mono;
                   6831:   white-space:pre;
1.921     bisitz   6832:   font-size: 120%;
1.778     bisitz   6833: }
                   6834: 
                   6835: .LC_fileicon {
                   6836:   border: none;
                   6837:   height: 1.3em;
                   6838:   vertical-align: text-bottom;
                   6839:   margin-right: 0.3em;
                   6840:   text-decoration:none;
                   6841: }
                   6842: 
1.1008    www      6843: .LC_setting {
                   6844:   text-decoration:underline;
                   6845: }
                   6846: 
1.350     albertel 6847: .LC_error {
                   6848:   color: red;
                   6849: }
1.795     www      6850: 
1.1075.2.15  raeburn  6851: .LC_warning {
                   6852:   color: darkorange;
                   6853: }
                   6854: 
1.457     albertel 6855: .LC_diff_removed {
1.733     bisitz   6856:   color: red;
1.394     albertel 6857: }
1.532     albertel 6858: 
                   6859: .LC_info,
1.457     albertel 6860: .LC_success,
                   6861: .LC_diff_added {
1.350     albertel 6862:   color: green;
                   6863: }
1.795     www      6864: 
1.802     bisitz   6865: div.LC_confirm_box {
                   6866:   background-color: #FAFAFA;
                   6867:   border: 1px solid $lg_border_color;
                   6868:   margin-right: 0;
                   6869:   padding: 5px;
                   6870: }
                   6871: 
                   6872: div.LC_confirm_box .LC_error img,
                   6873: div.LC_confirm_box .LC_success img {
                   6874:   vertical-align: middle;
                   6875: }
                   6876: 
1.1075.2.108  raeburn  6877: .LC_maxwidth {
                   6878:   max-width: 100%;
                   6879:   height: auto;
                   6880: }
                   6881: 
                   6882: .LC_textsize_mobile {
                   6883:   \@media only screen and (max-device-width: 480px) {
                   6884:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6885:   }
                   6886: }
                   6887: 
1.440     albertel 6888: .LC_icon {
1.771     droeschl 6889:   border: none;
1.790     droeschl 6890:   vertical-align: middle;
1.771     droeschl 6891: }
                   6892: 
1.543     albertel 6893: .LC_docs_spacer {
                   6894:   width: 25px;
                   6895:   height: 1px;
1.771     droeschl 6896:   border: none;
1.543     albertel 6897: }
1.346     albertel 6898: 
1.532     albertel 6899: .LC_internal_info {
1.735     bisitz   6900:   color: #999999;
1.532     albertel 6901: }
                   6902: 
1.794     www      6903: .LC_discussion {
1.1050    www      6904:   background: $data_table_dark;
1.911     bisitz   6905:   border: 1px solid black;
                   6906:   margin: 2px;
1.794     www      6907: }
                   6908: 
                   6909: .LC_disc_action_left {
1.1050    www      6910:   background: $sidebg;
1.911     bisitz   6911:   text-align: left;
1.1050    www      6912:   padding: 4px;
                   6913:   margin: 2px;
1.794     www      6914: }
                   6915: 
                   6916: .LC_disc_action_right {
1.1050    www      6917:   background: $sidebg;
1.911     bisitz   6918:   text-align: right;
1.1050    www      6919:   padding: 4px;
                   6920:   margin: 2px;
1.794     www      6921: }
                   6922: 
                   6923: .LC_disc_new_item {
1.911     bisitz   6924:   background: white;
                   6925:   border: 2px solid red;
1.1050    www      6926:   margin: 4px;
                   6927:   padding: 4px;
1.794     www      6928: }
                   6929: 
                   6930: .LC_disc_old_item {
1.911     bisitz   6931:   background: white;
1.1050    www      6932:   margin: 4px;
                   6933:   padding: 4px;
1.794     www      6934: }
                   6935: 
1.458     albertel 6936: table.LC_pastsubmission {
                   6937:   border: 1px solid black;
                   6938:   margin: 2px;
                   6939: }
                   6940: 
1.924     bisitz   6941: table#LC_menubuttons {
1.345     albertel 6942:   width: 100%;
                   6943:   background: $pgbg;
1.392     albertel 6944:   border: 2px;
1.402     albertel 6945:   border-collapse: separate;
1.803     bisitz   6946:   padding: 0;
1.345     albertel 6947: }
1.392     albertel 6948: 
1.801     tempelho 6949: table#LC_title_bar a {
                   6950:   color: $fontmenu;
                   6951: }
1.836     bisitz   6952: 
1.807     droeschl 6953: table#LC_title_bar {
1.819     tempelho 6954:   clear: both;
1.836     bisitz   6955:   display: none;
1.807     droeschl 6956: }
                   6957: 
1.795     www      6958: table#LC_title_bar,
1.933     droeschl 6959: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6960: table#LC_title_bar.LC_with_remote {
1.359     albertel 6961:   width: 100%;
1.392     albertel 6962:   border-color: $pgbg;
                   6963:   border-style: solid;
                   6964:   border-width: $border;
1.379     albertel 6965:   background: $pgbg;
1.801     tempelho 6966:   color: $fontmenu;
1.392     albertel 6967:   border-collapse: collapse;
1.803     bisitz   6968:   padding: 0;
1.819     tempelho 6969:   margin: 0;
1.359     albertel 6970: }
1.795     www      6971: 
1.933     droeschl 6972: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6973:     margin: 0;
                   6974:     padding: 0;
1.933     droeschl 6975:     position: relative;
                   6976:     list-style: none;
1.913     droeschl 6977: }
1.933     droeschl 6978: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6979:     display: inline;
                   6980: }
1.933     droeschl 6981: 
                   6982: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6983:     padding: 0;
1.933     droeschl 6984:     margin: 0;
                   6985:     float: left;
1.913     droeschl 6986: }
1.933     droeschl 6987: .LC_breadcrumb_tools_tools {
                   6988:     padding: 0;
                   6989:     margin: 0;
1.913     droeschl 6990:     float: right;
                   6991: }
                   6992: 
1.359     albertel 6993: table#LC_title_bar td {
                   6994:   background: $tabbg;
                   6995: }
1.795     www      6996: 
1.911     bisitz   6997: table#LC_menubuttons img {
1.803     bisitz   6998:   border: none;
1.346     albertel 6999: }
1.795     www      7000: 
1.842     droeschl 7001: .LC_breadcrumbs_component {
1.911     bisitz   7002:   float: right;
                   7003:   margin: 0 1em;
1.357     albertel 7004: }
1.842     droeschl 7005: .LC_breadcrumbs_component img {
1.911     bisitz   7006:   vertical-align: middle;
1.777     tempelho 7007: }
1.795     www      7008: 
1.1075.2.108  raeburn  7009: .LC_breadcrumbs_hoverable {
                   7010:   background: $sidebg;
                   7011: }
                   7012: 
1.383     albertel 7013: td.LC_table_cell_checkbox {
                   7014:   text-align: center;
                   7015: }
1.795     www      7016: 
                   7017: .LC_fontsize_small {
1.911     bisitz   7018:   font-size: 70%;
1.705     tempelho 7019: }
                   7020: 
1.844     bisitz   7021: #LC_breadcrumbs {
1.911     bisitz   7022:   clear:both;
                   7023:   background: $sidebg;
                   7024:   border-bottom: 1px solid $lg_border_color;
                   7025:   line-height: 2.5em;
1.933     droeschl 7026:   overflow: hidden;
1.911     bisitz   7027:   margin: 0;
                   7028:   padding: 0;
1.995     raeburn  7029:   text-align: left;
1.819     tempelho 7030: }
1.862     bisitz   7031: 
1.1075.2.16  raeburn  7032: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7033:   clear:both;
                   7034:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7035:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  7036:   margin: 0 0 10px 0;
1.966     bisitz   7037:   padding: 3px;
1.995     raeburn  7038:   text-align: left;
1.822     bisitz   7039: }
                   7040: 
1.795     www      7041: .LC_fontsize_medium {
1.911     bisitz   7042:   font-size: 85%;
1.705     tempelho 7043: }
                   7044: 
1.795     www      7045: .LC_fontsize_large {
1.911     bisitz   7046:   font-size: 120%;
1.705     tempelho 7047: }
                   7048: 
1.346     albertel 7049: .LC_menubuttons_inline_text {
                   7050:   color: $font;
1.698     harmsja  7051:   font-size: 90%;
1.701     harmsja  7052:   padding-left:3px;
1.346     albertel 7053: }
                   7054: 
1.934     droeschl 7055: .LC_menubuttons_inline_text img{
                   7056:   vertical-align: middle;
                   7057: }
                   7058: 
1.1051    www      7059: li.LC_menubuttons_inline_text img {
1.951     onken    7060:   cursor:pointer;
1.1002    droeschl 7061:   text-decoration: none;
1.951     onken    7062: }
                   7063: 
1.526     www      7064: .LC_menubuttons_link {
                   7065:   text-decoration: none;
                   7066: }
1.795     www      7067: 
1.522     albertel 7068: .LC_menubuttons_category {
1.521     www      7069:   color: $font;
1.526     www      7070:   background: $pgbg;
1.521     www      7071:   font-size: larger;
                   7072:   font-weight: bold;
                   7073: }
                   7074: 
1.346     albertel 7075: td.LC_menubuttons_text {
1.911     bisitz   7076:   color: $font;
1.346     albertel 7077: }
1.706     harmsja  7078: 
1.346     albertel 7079: .LC_current_location {
                   7080:   background: $tabbg;
                   7081: }
1.795     www      7082: 
1.1075.2.134  raeburn  7083: td.LC_zero_height {
                   7084:   line-height: 0;
                   7085:   cellpadding: 0;
                   7086: }
                   7087: 
1.938     bisitz   7088: table.LC_data_table {
1.347     albertel 7089:   border: 1px solid #000000;
1.402     albertel 7090:   border-collapse: separate;
1.426     albertel 7091:   border-spacing: 1px;
1.610     albertel 7092:   background: $pgbg;
1.347     albertel 7093: }
1.795     www      7094: 
1.422     albertel 7095: .LC_data_table_dense {
                   7096:   font-size: small;
                   7097: }
1.795     www      7098: 
1.507     raeburn  7099: table.LC_nested_outer {
                   7100:   border: 1px solid #000000;
1.589     raeburn  7101:   border-collapse: collapse;
1.803     bisitz   7102:   border-spacing: 0;
1.507     raeburn  7103:   width: 100%;
                   7104: }
1.795     www      7105: 
1.879     raeburn  7106: table.LC_innerpickbox,
1.507     raeburn  7107: table.LC_nested {
1.803     bisitz   7108:   border: none;
1.589     raeburn  7109:   border-collapse: collapse;
1.803     bisitz   7110:   border-spacing: 0;
1.507     raeburn  7111:   width: 100%;
                   7112: }
1.795     www      7113: 
1.911     bisitz   7114: table.LC_data_table tr th,
                   7115: table.LC_calendar tr th,
1.879     raeburn  7116: table.LC_prior_tries tr th,
                   7117: table.LC_innerpickbox tr th {
1.349     albertel 7118:   font-weight: bold;
                   7119:   background-color: $data_table_head;
1.801     tempelho 7120:   color:$fontmenu;
1.701     harmsja  7121:   font-size:90%;
1.347     albertel 7122: }
1.795     www      7123: 
1.879     raeburn  7124: table.LC_innerpickbox tr th,
                   7125: table.LC_innerpickbox tr td {
                   7126:   vertical-align: top;
                   7127: }
                   7128: 
1.711     raeburn  7129: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7130:   background-color: #CCCCCC;
1.711     raeburn  7131:   font-weight: bold;
                   7132:   text-align: left;
                   7133: }
1.795     www      7134: 
1.912     bisitz   7135: table.LC_data_table tr.LC_odd_row > td {
                   7136:   background-color: $data_table_light;
                   7137:   padding: 2px;
                   7138:   vertical-align: top;
                   7139: }
                   7140: 
1.809     bisitz   7141: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7142:   background-color: $data_table_light;
1.912     bisitz   7143:   vertical-align: top;
                   7144: }
                   7145: 
                   7146: table.LC_data_table tr.LC_even_row > td {
                   7147:   background-color: $data_table_dark;
1.425     albertel 7148:   padding: 2px;
1.900     bisitz   7149:   vertical-align: top;
1.347     albertel 7150: }
1.795     www      7151: 
1.809     bisitz   7152: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7153:   background-color: $data_table_dark;
1.900     bisitz   7154:   vertical-align: top;
1.347     albertel 7155: }
1.795     www      7156: 
1.425     albertel 7157: table.LC_data_table tr.LC_data_table_highlight td {
                   7158:   background-color: $data_table_darker;
                   7159: }
1.795     www      7160: 
1.639     raeburn  7161: table.LC_data_table tr td.LC_leftcol_header {
                   7162:   background-color: $data_table_head;
                   7163:   font-weight: bold;
                   7164: }
1.795     www      7165: 
1.451     albertel 7166: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7167: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7168:   font-weight: bold;
                   7169:   font-style: italic;
                   7170:   text-align: center;
                   7171:   padding: 8px;
1.347     albertel 7172: }
1.795     www      7173: 
1.1075.2.30  raeburn  7174: table.LC_data_table tr.LC_empty_row td,
                   7175: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7176:   background-color: $sidebg;
                   7177: }
                   7178: 
                   7179: table.LC_nested tr.LC_empty_row td {
                   7180:   background-color: #FFFFFF;
                   7181: }
                   7182: 
1.890     droeschl 7183: table.LC_caption {
                   7184: }
                   7185: 
1.507     raeburn  7186: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7187:   padding: 4ex
                   7188: }
1.795     www      7189: 
1.507     raeburn  7190: table.LC_nested_outer tr th {
                   7191:   font-weight: bold;
1.801     tempelho 7192:   color:$fontmenu;
1.507     raeburn  7193:   background-color: $data_table_head;
1.701     harmsja  7194:   font-size: small;
1.507     raeburn  7195:   border-bottom: 1px solid #000000;
                   7196: }
1.795     www      7197: 
1.507     raeburn  7198: table.LC_nested_outer tr td.LC_subheader {
                   7199:   background-color: $data_table_head;
                   7200:   font-weight: bold;
                   7201:   font-size: small;
                   7202:   border-bottom: 1px solid #000000;
                   7203:   text-align: right;
1.451     albertel 7204: }
1.795     www      7205: 
1.507     raeburn  7206: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7207:   background-color: #CCCCCC;
1.451     albertel 7208:   font-weight: bold;
                   7209:   font-size: small;
1.507     raeburn  7210:   text-align: center;
                   7211: }
1.795     www      7212: 
1.589     raeburn  7213: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7214: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7215:   text-align: left;
1.451     albertel 7216: }
1.795     www      7217: 
1.507     raeburn  7218: table.LC_nested td {
1.735     bisitz   7219:   background-color: #FFFFFF;
1.451     albertel 7220:   font-size: small;
1.507     raeburn  7221: }
1.795     www      7222: 
1.507     raeburn  7223: table.LC_nested_outer tr th.LC_right_item,
                   7224: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7225: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7226: table.LC_nested tr td.LC_right_item {
1.451     albertel 7227:   text-align: right;
                   7228: }
                   7229: 
1.507     raeburn  7230: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7231:   background-color: #EEEEEE;
1.451     albertel 7232: }
                   7233: 
1.473     raeburn  7234: table.LC_createuser {
                   7235: }
                   7236: 
                   7237: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7238:   font-size: small;
1.473     raeburn  7239: }
                   7240: 
                   7241: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7242:   background-color: #CCCCCC;
1.473     raeburn  7243:   font-weight: bold;
                   7244:   text-align: center;
                   7245: }
                   7246: 
1.349     albertel 7247: table.LC_calendar {
                   7248:   border: 1px solid #000000;
                   7249:   border-collapse: collapse;
1.917     raeburn  7250:   width: 98%;
1.349     albertel 7251: }
1.795     www      7252: 
1.349     albertel 7253: table.LC_calendar_pickdate {
                   7254:   font-size: xx-small;
                   7255: }
1.795     www      7256: 
1.349     albertel 7257: table.LC_calendar tr td {
                   7258:   border: 1px solid #000000;
                   7259:   vertical-align: top;
1.917     raeburn  7260:   width: 14%;
1.349     albertel 7261: }
1.795     www      7262: 
1.349     albertel 7263: table.LC_calendar tr td.LC_calendar_day_empty {
                   7264:   background-color: $data_table_dark;
                   7265: }
1.795     www      7266: 
1.779     bisitz   7267: table.LC_calendar tr td.LC_calendar_day_current {
                   7268:   background-color: $data_table_highlight;
1.777     tempelho 7269: }
1.795     www      7270: 
1.938     bisitz   7271: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7272:   background-color: $mail_new;
                   7273: }
1.795     www      7274: 
1.938     bisitz   7275: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7276:   background-color: $mail_new_hover;
                   7277: }
1.795     www      7278: 
1.938     bisitz   7279: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7280:   background-color: $mail_read;
                   7281: }
1.795     www      7282: 
1.938     bisitz   7283: /*
                   7284: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7285:   background-color: $mail_read_hover;
                   7286: }
1.938     bisitz   7287: */
1.795     www      7288: 
1.938     bisitz   7289: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7290:   background-color: $mail_replied;
                   7291: }
1.795     www      7292: 
1.938     bisitz   7293: /*
                   7294: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7295:   background-color: $mail_replied_hover;
                   7296: }
1.938     bisitz   7297: */
1.795     www      7298: 
1.938     bisitz   7299: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7300:   background-color: $mail_other;
                   7301: }
1.795     www      7302: 
1.938     bisitz   7303: /*
                   7304: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7305:   background-color: $mail_other_hover;
                   7306: }
1.938     bisitz   7307: */
1.494     raeburn  7308: 
1.777     tempelho 7309: table.LC_data_table tr > td.LC_browser_file,
                   7310: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7311:   background: #AAEE77;
1.389     albertel 7312: }
1.795     www      7313: 
1.777     tempelho 7314: table.LC_data_table tr > td.LC_browser_file_locked,
                   7315: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7316:   background: #FFAA99;
1.387     albertel 7317: }
1.795     www      7318: 
1.777     tempelho 7319: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7320:   background: #888888;
1.779     bisitz   7321: }
1.795     www      7322: 
1.777     tempelho 7323: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7324: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7325:   background: #F8F866;
1.777     tempelho 7326: }
1.795     www      7327: 
1.696     bisitz   7328: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7329:   background: #E0E8FF;
1.387     albertel 7330: }
1.696     bisitz   7331: 
1.707     bisitz   7332: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7333:   /* background: #77FF77; */
1.707     bisitz   7334: }
1.795     www      7335: 
1.707     bisitz   7336: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7337:   border-right: 8px solid #FFFF77;
1.707     bisitz   7338: }
1.795     www      7339: 
1.707     bisitz   7340: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7341:   border-right: 8px solid #FFAA77;
1.707     bisitz   7342: }
1.795     www      7343: 
1.707     bisitz   7344: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7345:   border-right: 8px solid #FF7777;
1.707     bisitz   7346: }
1.795     www      7347: 
1.707     bisitz   7348: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7349:   border-right: 8px solid #AAFF77;
1.707     bisitz   7350: }
1.795     www      7351: 
1.707     bisitz   7352: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7353:   border-right: 8px solid #11CC55;
1.707     bisitz   7354: }
                   7355: 
1.388     albertel 7356: span.LC_current_location {
1.701     harmsja  7357:   font-size:larger;
1.388     albertel 7358:   background: $pgbg;
                   7359: }
1.387     albertel 7360: 
1.1029    www      7361: span.LC_current_nav_location {
                   7362:   font-weight:bold;
                   7363:   background: $sidebg;
                   7364: }
                   7365: 
1.395     albertel 7366: span.LC_parm_menu_item {
                   7367:   font-size: larger;
                   7368: }
1.795     www      7369: 
1.395     albertel 7370: span.LC_parm_scope_all {
                   7371:   color: red;
                   7372: }
1.795     www      7373: 
1.395     albertel 7374: span.LC_parm_scope_folder {
                   7375:   color: green;
                   7376: }
1.795     www      7377: 
1.395     albertel 7378: span.LC_parm_scope_resource {
                   7379:   color: orange;
                   7380: }
1.795     www      7381: 
1.395     albertel 7382: span.LC_parm_part {
                   7383:   color: blue;
                   7384: }
1.795     www      7385: 
1.911     bisitz   7386: span.LC_parm_folder,
                   7387: span.LC_parm_symb {
1.395     albertel 7388:   font-size: x-small;
                   7389:   font-family: $mono;
                   7390:   color: #AAAAAA;
                   7391: }
                   7392: 
1.977     bisitz   7393: ul.LC_parm_parmlist li {
                   7394:   display: inline-block;
                   7395:   padding: 0.3em 0.8em;
                   7396:   vertical-align: top;
                   7397:   width: 150px;
                   7398:   border-top:1px solid $lg_border_color;
                   7399: }
                   7400: 
1.795     www      7401: td.LC_parm_overview_level_menu,
                   7402: td.LC_parm_overview_map_menu,
                   7403: td.LC_parm_overview_parm_selectors,
                   7404: td.LC_parm_overview_restrictions  {
1.396     albertel 7405:   border: 1px solid black;
                   7406:   border-collapse: collapse;
                   7407: }
1.795     www      7408: 
1.396     albertel 7409: table.LC_parm_overview_restrictions td {
                   7410:   border-width: 1px 4px 1px 4px;
                   7411:   border-style: solid;
                   7412:   border-color: $pgbg;
                   7413:   text-align: center;
                   7414: }
1.795     www      7415: 
1.396     albertel 7416: table.LC_parm_overview_restrictions th {
                   7417:   background: $tabbg;
                   7418:   border-width: 1px 4px 1px 4px;
                   7419:   border-style: solid;
                   7420:   border-color: $pgbg;
                   7421: }
1.795     www      7422: 
1.398     albertel 7423: table#LC_helpmenu {
1.803     bisitz   7424:   border: none;
1.398     albertel 7425:   height: 55px;
1.803     bisitz   7426:   border-spacing: 0;
1.398     albertel 7427: }
                   7428: 
                   7429: table#LC_helpmenu fieldset legend {
                   7430:   font-size: larger;
                   7431: }
1.795     www      7432: 
1.397     albertel 7433: table#LC_helpmenu_links {
                   7434:   width: 100%;
                   7435:   border: 1px solid black;
                   7436:   background: $pgbg;
1.803     bisitz   7437:   padding: 0;
1.397     albertel 7438:   border-spacing: 1px;
                   7439: }
1.795     www      7440: 
1.397     albertel 7441: table#LC_helpmenu_links tr td {
                   7442:   padding: 1px;
                   7443:   background: $tabbg;
1.399     albertel 7444:   text-align: center;
                   7445:   font-weight: bold;
1.397     albertel 7446: }
1.396     albertel 7447: 
1.795     www      7448: table#LC_helpmenu_links a:link,
                   7449: table#LC_helpmenu_links a:visited,
1.397     albertel 7450: table#LC_helpmenu_links a:active {
                   7451:   text-decoration: none;
                   7452:   color: $font;
                   7453: }
1.795     www      7454: 
1.397     albertel 7455: table#LC_helpmenu_links a:hover {
                   7456:   text-decoration: underline;
                   7457:   color: $vlink;
                   7458: }
1.396     albertel 7459: 
1.417     albertel 7460: .LC_chrt_popup_exists {
                   7461:   border: 1px solid #339933;
                   7462:   margin: -1px;
                   7463: }
1.795     www      7464: 
1.417     albertel 7465: .LC_chrt_popup_up {
                   7466:   border: 1px solid yellow;
                   7467:   margin: -1px;
                   7468: }
1.795     www      7469: 
1.417     albertel 7470: .LC_chrt_popup {
                   7471:   border: 1px solid #8888FF;
                   7472:   background: #CCCCFF;
                   7473: }
1.795     www      7474: 
1.421     albertel 7475: table.LC_pick_box {
                   7476:   border-collapse: separate;
                   7477:   background: white;
                   7478:   border: 1px solid black;
                   7479:   border-spacing: 1px;
                   7480: }
1.795     www      7481: 
1.421     albertel 7482: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7483:   background: $sidebg;
1.421     albertel 7484:   font-weight: bold;
1.900     bisitz   7485:   text-align: left;
1.740     bisitz   7486:   vertical-align: top;
1.421     albertel 7487:   width: 184px;
                   7488:   padding: 8px;
                   7489: }
1.795     www      7490: 
1.579     raeburn  7491: table.LC_pick_box td.LC_pick_box_value {
                   7492:   text-align: left;
                   7493:   padding: 8px;
                   7494: }
1.795     www      7495: 
1.579     raeburn  7496: table.LC_pick_box td.LC_pick_box_select {
                   7497:   text-align: left;
                   7498:   padding: 8px;
                   7499: }
1.795     www      7500: 
1.424     albertel 7501: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7502:   padding: 0;
1.421     albertel 7503:   height: 1px;
                   7504:   background: black;
                   7505: }
1.795     www      7506: 
1.421     albertel 7507: table.LC_pick_box td.LC_pick_box_submit {
                   7508:   text-align: right;
                   7509: }
1.795     www      7510: 
1.579     raeburn  7511: table.LC_pick_box td.LC_evenrow_value {
                   7512:   text-align: left;
                   7513:   padding: 8px;
                   7514:   background-color: $data_table_light;
                   7515: }
1.795     www      7516: 
1.579     raeburn  7517: table.LC_pick_box td.LC_oddrow_value {
                   7518:   text-align: left;
                   7519:   padding: 8px;
                   7520:   background-color: $data_table_light;
                   7521: }
1.795     www      7522: 
1.579     raeburn  7523: span.LC_helpform_receipt_cat {
                   7524:   font-weight: bold;
                   7525: }
1.795     www      7526: 
1.424     albertel 7527: table.LC_group_priv_box {
                   7528:   background: white;
                   7529:   border: 1px solid black;
                   7530:   border-spacing: 1px;
                   7531: }
1.795     www      7532: 
1.424     albertel 7533: table.LC_group_priv_box td.LC_pick_box_title {
                   7534:   background: $tabbg;
                   7535:   font-weight: bold;
                   7536:   text-align: right;
                   7537:   width: 184px;
                   7538: }
1.795     www      7539: 
1.424     albertel 7540: table.LC_group_priv_box td.LC_groups_fixed {
                   7541:   background: $data_table_light;
                   7542:   text-align: center;
                   7543: }
1.795     www      7544: 
1.424     albertel 7545: table.LC_group_priv_box td.LC_groups_optional {
                   7546:   background: $data_table_dark;
                   7547:   text-align: center;
                   7548: }
1.795     www      7549: 
1.424     albertel 7550: table.LC_group_priv_box td.LC_groups_functionality {
                   7551:   background: $data_table_darker;
                   7552:   text-align: center;
                   7553:   font-weight: bold;
                   7554: }
1.795     www      7555: 
1.424     albertel 7556: table.LC_group_priv td {
                   7557:   text-align: left;
1.803     bisitz   7558:   padding: 0;
1.424     albertel 7559: }
                   7560: 
                   7561: .LC_navbuttons {
                   7562:   margin: 2ex 0ex 2ex 0ex;
                   7563: }
1.795     www      7564: 
1.423     albertel 7565: .LC_topic_bar {
                   7566:   font-weight: bold;
                   7567:   background: $tabbg;
1.918     wenzelju 7568:   margin: 1em 0em 1em 2em;
1.805     bisitz   7569:   padding: 3px;
1.918     wenzelju 7570:   font-size: 1.2em;
1.423     albertel 7571: }
1.795     www      7572: 
1.423     albertel 7573: .LC_topic_bar span {
1.918     wenzelju 7574:   left: 0.5em;
                   7575:   position: absolute;
1.423     albertel 7576:   vertical-align: middle;
1.918     wenzelju 7577:   font-size: 1.2em;
1.423     albertel 7578: }
1.795     www      7579: 
1.423     albertel 7580: table.LC_course_group_status {
                   7581:   margin: 20px;
                   7582: }
1.795     www      7583: 
1.423     albertel 7584: table.LC_status_selector td {
                   7585:   vertical-align: top;
                   7586:   text-align: center;
1.424     albertel 7587:   padding: 4px;
                   7588: }
1.795     www      7589: 
1.599     albertel 7590: div.LC_feedback_link {
1.616     albertel 7591:   clear: both;
1.829     kalberla 7592:   background: $sidebg;
1.779     bisitz   7593:   width: 100%;
1.829     kalberla 7594:   padding-bottom: 10px;
                   7595:   border: 1px $tabbg solid;
1.833     kalberla 7596:   height: 22px;
                   7597:   line-height: 22px;
                   7598:   padding-top: 5px;
                   7599: }
                   7600: 
                   7601: div.LC_feedback_link img {
                   7602:   height: 22px;
1.867     kalberla 7603:   vertical-align:middle;
1.829     kalberla 7604: }
                   7605: 
1.911     bisitz   7606: div.LC_feedback_link a {
1.829     kalberla 7607:   text-decoration: none;
1.489     raeburn  7608: }
1.795     www      7609: 
1.867     kalberla 7610: div.LC_comblock {
1.911     bisitz   7611:   display:inline;
1.867     kalberla 7612:   color:$font;
                   7613:   font-size:90%;
                   7614: }
                   7615: 
                   7616: div.LC_feedback_link div.LC_comblock {
                   7617:   padding-left:5px;
                   7618: }
                   7619: 
                   7620: div.LC_feedback_link div.LC_comblock a {
                   7621:   color:$font;
                   7622: }
                   7623: 
1.489     raeburn  7624: span.LC_feedback_link {
1.858     bisitz   7625:   /* background: $feedback_link_bg; */
1.599     albertel 7626:   font-size: larger;
                   7627: }
1.795     www      7628: 
1.599     albertel 7629: span.LC_message_link {
1.858     bisitz   7630:   /* background: $feedback_link_bg; */
1.599     albertel 7631:   font-size: larger;
                   7632:   position: absolute;
                   7633:   right: 1em;
1.489     raeburn  7634: }
1.421     albertel 7635: 
1.515     albertel 7636: table.LC_prior_tries {
1.524     albertel 7637:   border: 1px solid #000000;
                   7638:   border-collapse: separate;
                   7639:   border-spacing: 1px;
1.515     albertel 7640: }
1.523     albertel 7641: 
1.515     albertel 7642: table.LC_prior_tries td {
1.524     albertel 7643:   padding: 2px;
1.515     albertel 7644: }
1.523     albertel 7645: 
                   7646: .LC_answer_correct {
1.795     www      7647:   background: lightgreen;
                   7648:   color: darkgreen;
                   7649:   padding: 6px;
1.523     albertel 7650: }
1.795     www      7651: 
1.523     albertel 7652: .LC_answer_charged_try {
1.797     www      7653:   background: #FFAAAA;
1.795     www      7654:   color: darkred;
                   7655:   padding: 6px;
1.523     albertel 7656: }
1.795     www      7657: 
1.779     bisitz   7658: .LC_answer_not_charged_try,
1.523     albertel 7659: .LC_answer_no_grade,
                   7660: .LC_answer_late {
1.795     www      7661:   background: lightyellow;
1.523     albertel 7662:   color: black;
1.795     www      7663:   padding: 6px;
1.523     albertel 7664: }
1.795     www      7665: 
1.523     albertel 7666: .LC_answer_previous {
1.795     www      7667:   background: lightblue;
                   7668:   color: darkblue;
                   7669:   padding: 6px;
1.523     albertel 7670: }
1.795     www      7671: 
1.779     bisitz   7672: .LC_answer_no_message {
1.777     tempelho 7673:   background: #FFFFFF;
                   7674:   color: black;
1.795     www      7675:   padding: 6px;
1.779     bisitz   7676: }
1.795     www      7677: 
1.1075.2.140  raeburn  7678: .LC_answer_unknown,
                   7679: .LC_answer_warning {
1.779     bisitz   7680:   background: orange;
                   7681:   color: black;
1.795     www      7682:   padding: 6px;
1.777     tempelho 7683: }
1.795     www      7684: 
1.529     albertel 7685: span.LC_prior_numerical,
                   7686: span.LC_prior_string,
                   7687: span.LC_prior_custom,
                   7688: span.LC_prior_reaction,
                   7689: span.LC_prior_math {
1.925     bisitz   7690:   font-family: $mono;
1.523     albertel 7691:   white-space: pre;
                   7692: }
                   7693: 
1.525     albertel 7694: span.LC_prior_string {
1.925     bisitz   7695:   font-family: $mono;
1.525     albertel 7696:   white-space: pre;
                   7697: }
                   7698: 
1.523     albertel 7699: table.LC_prior_option {
                   7700:   width: 100%;
                   7701:   border-collapse: collapse;
                   7702: }
1.795     www      7703: 
1.911     bisitz   7704: table.LC_prior_rank,
1.795     www      7705: table.LC_prior_match {
1.528     albertel 7706:   border-collapse: collapse;
                   7707: }
1.795     www      7708: 
1.528     albertel 7709: table.LC_prior_option tr td,
                   7710: table.LC_prior_rank tr td,
                   7711: table.LC_prior_match tr td {
1.524     albertel 7712:   border: 1px solid #000000;
1.515     albertel 7713: }
                   7714: 
1.855     bisitz   7715: .LC_nobreak {
1.544     albertel 7716:   white-space: nowrap;
1.519     raeburn  7717: }
                   7718: 
1.576     raeburn  7719: span.LC_cusr_emph {
                   7720:   font-style: italic;
                   7721: }
                   7722: 
1.633     raeburn  7723: span.LC_cusr_subheading {
                   7724:   font-weight: normal;
                   7725:   font-size: 85%;
                   7726: }
                   7727: 
1.861     bisitz   7728: div.LC_docs_entry_move {
1.859     bisitz   7729:   border: 1px solid #BBBBBB;
1.545     albertel 7730:   background: #DDDDDD;
1.861     bisitz   7731:   width: 22px;
1.859     bisitz   7732:   padding: 1px;
                   7733:   margin: 0;
1.545     albertel 7734: }
                   7735: 
1.861     bisitz   7736: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7737: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7738:   font-size: x-small;
                   7739: }
1.795     www      7740: 
1.861     bisitz   7741: .LC_docs_entry_parameter {
                   7742:   white-space: nowrap;
                   7743: }
                   7744: 
1.544     albertel 7745: .LC_docs_copy {
1.545     albertel 7746:   color: #000099;
1.544     albertel 7747: }
1.795     www      7748: 
1.544     albertel 7749: .LC_docs_cut {
1.545     albertel 7750:   color: #550044;
1.544     albertel 7751: }
1.795     www      7752: 
1.544     albertel 7753: .LC_docs_rename {
1.545     albertel 7754:   color: #009900;
1.544     albertel 7755: }
1.795     www      7756: 
1.544     albertel 7757: .LC_docs_remove {
1.545     albertel 7758:   color: #990000;
                   7759: }
                   7760: 
1.1075.2.134  raeburn  7761: .LC_domprefs_email,
1.547     albertel 7762: .LC_docs_reinit_warn,
                   7763: .LC_docs_ext_edit {
                   7764:   font-size: x-small;
                   7765: }
                   7766: 
1.545     albertel 7767: table.LC_docs_adddocs td,
                   7768: table.LC_docs_adddocs th {
                   7769:   border: 1px solid #BBBBBB;
                   7770:   padding: 4px;
                   7771:   background: #DDDDDD;
1.543     albertel 7772: }
                   7773: 
1.584     albertel 7774: table.LC_sty_begin {
                   7775:   background: #BBFFBB;
                   7776: }
1.795     www      7777: 
1.584     albertel 7778: table.LC_sty_end {
                   7779:   background: #FFBBBB;
                   7780: }
                   7781: 
1.589     raeburn  7782: table.LC_double_column {
1.803     bisitz   7783:   border-width: 0;
1.589     raeburn  7784:   border-collapse: collapse;
                   7785:   width: 100%;
                   7786:   padding: 2px;
                   7787: }
                   7788: 
                   7789: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7790:   top: 2px;
1.589     raeburn  7791:   left: 2px;
                   7792:   width: 47%;
                   7793:   vertical-align: top;
                   7794: }
                   7795: 
                   7796: table.LC_double_column tr td.LC_right_col {
                   7797:   top: 2px;
1.779     bisitz   7798:   right: 2px;
1.589     raeburn  7799:   width: 47%;
                   7800:   vertical-align: top;
                   7801: }
                   7802: 
1.591     raeburn  7803: div.LC_left_float {
                   7804:   float: left;
                   7805:   padding-right: 5%;
1.597     albertel 7806:   padding-bottom: 4px;
1.591     raeburn  7807: }
                   7808: 
                   7809: div.LC_clear_float_header {
1.597     albertel 7810:   padding-bottom: 2px;
1.591     raeburn  7811: }
                   7812: 
                   7813: div.LC_clear_float_footer {
1.597     albertel 7814:   padding-top: 10px;
1.591     raeburn  7815:   clear: both;
                   7816: }
                   7817: 
1.597     albertel 7818: div.LC_grade_show_user {
1.941     bisitz   7819: /*  border-left: 5px solid $sidebg; */
                   7820:   border-top: 5px solid #000000;
                   7821:   margin: 50px 0 0 0;
1.936     bisitz   7822:   padding: 15px 0 5px 10px;
1.597     albertel 7823: }
1.795     www      7824: 
1.936     bisitz   7825: div.LC_grade_show_user_odd_row {
1.941     bisitz   7826: /*  border-left: 5px solid #000000; */
                   7827: }
                   7828: 
                   7829: div.LC_grade_show_user div.LC_Box {
                   7830:   margin-right: 50px;
1.597     albertel 7831: }
                   7832: 
                   7833: div.LC_grade_submissions,
                   7834: div.LC_grade_message_center,
1.936     bisitz   7835: div.LC_grade_info_links {
1.597     albertel 7836:   margin: 5px;
                   7837:   width: 99%;
                   7838:   background: #FFFFFF;
                   7839: }
1.795     www      7840: 
1.597     albertel 7841: div.LC_grade_submissions_header,
1.936     bisitz   7842: div.LC_grade_message_center_header {
1.705     tempelho 7843:   font-weight: bold;
                   7844:   font-size: large;
1.597     albertel 7845: }
1.795     www      7846: 
1.597     albertel 7847: div.LC_grade_submissions_body,
1.936     bisitz   7848: div.LC_grade_message_center_body {
1.597     albertel 7849:   border: 1px solid black;
                   7850:   width: 99%;
                   7851:   background: #FFFFFF;
                   7852: }
1.795     www      7853: 
1.613     albertel 7854: table.LC_scantron_action {
                   7855:   width: 100%;
                   7856: }
1.795     www      7857: 
1.613     albertel 7858: table.LC_scantron_action tr th {
1.698     harmsja  7859:   font-weight:bold;
                   7860:   font-style:normal;
1.613     albertel 7861: }
1.795     www      7862: 
1.779     bisitz   7863: .LC_edit_problem_header,
1.614     albertel 7864: div.LC_edit_problem_footer {
1.705     tempelho 7865:   font-weight: normal;
                   7866:   font-size:  medium;
1.602     albertel 7867:   margin: 2px;
1.1060    bisitz   7868:   background-color: $sidebg;
1.600     albertel 7869: }
1.795     www      7870: 
1.600     albertel 7871: div.LC_edit_problem_header,
1.602     albertel 7872: div.LC_edit_problem_header div,
1.614     albertel 7873: div.LC_edit_problem_footer,
                   7874: div.LC_edit_problem_footer div,
1.602     albertel 7875: div.LC_edit_problem_editxml_header,
                   7876: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7877:   z-index: 100;
1.600     albertel 7878: }
1.795     www      7879: 
1.600     albertel 7880: div.LC_edit_problem_header_title {
1.705     tempelho 7881:   font-weight: bold;
                   7882:   font-size: larger;
1.602     albertel 7883:   background: $tabbg;
                   7884:   padding: 3px;
1.1060    bisitz   7885:   margin: 0 0 5px 0;
1.602     albertel 7886: }
1.795     www      7887: 
1.602     albertel 7888: table.LC_edit_problem_header_title {
                   7889:   width: 100%;
1.600     albertel 7890:   background: $tabbg;
1.602     albertel 7891: }
                   7892: 
1.1075.2.112  raeburn  7893: div.LC_edit_actionbar {
                   7894:     background-color: $sidebg;
                   7895:     margin: 0;
                   7896:     padding: 0;
                   7897:     line-height: 200%;
1.602     albertel 7898: }
1.795     www      7899: 
1.1075.2.112  raeburn  7900: div.LC_edit_actionbar div{
                   7901:     padding: 0;
                   7902:     margin: 0;
                   7903:     display: inline-block;
1.600     albertel 7904: }
1.795     www      7905: 
1.1075.2.34  raeburn  7906: .LC_edit_opt {
                   7907:   padding-left: 1em;
                   7908:   white-space: nowrap;
                   7909: }
                   7910: 
1.1075.2.57  raeburn  7911: .LC_edit_problem_latexhelper{
                   7912:     text-align: right;
                   7913: }
                   7914: 
                   7915: #LC_edit_problem_colorful div{
                   7916:     margin-left: 40px;
                   7917: }
                   7918: 
1.1075.2.112  raeburn  7919: #LC_edit_problem_codemirror div{
                   7920:     margin-left: 0px;
                   7921: }
                   7922: 
1.911     bisitz   7923: img.stift {
1.803     bisitz   7924:   border-width: 0;
                   7925:   vertical-align: middle;
1.677     riegler  7926: }
1.680     riegler  7927: 
1.923     bisitz   7928: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7929:   vertical-align: top;
1.777     tempelho 7930: }
1.795     www      7931: 
1.716     raeburn  7932: div.LC_createcourse {
1.911     bisitz   7933:   margin: 10px 10px 10px 10px;
1.716     raeburn  7934: }
                   7935: 
1.917     raeburn  7936: .LC_dccid {
1.1075.2.38  raeburn  7937:   float: right;
1.917     raeburn  7938:   margin: 0.2em 0 0 0;
                   7939:   padding: 0;
                   7940:   font-size: 90%;
                   7941:   display:none;
                   7942: }
                   7943: 
1.897     wenzelju 7944: ol.LC_primary_menu a:hover,
1.721     harmsja  7945: ol#LC_MenuBreadcrumbs a:hover,
                   7946: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7947: ul#LC_secondary_menu a:hover,
1.721     harmsja  7948: .LC_FormSectionClearButton input:hover
1.795     www      7949: ul.LC_TabContent   li:hover a {
1.952     onken    7950:   color:$button_hover;
1.911     bisitz   7951:   text-decoration:none;
1.693     droeschl 7952: }
                   7953: 
1.779     bisitz   7954: h1 {
1.911     bisitz   7955:   padding: 0;
                   7956:   line-height:130%;
1.693     droeschl 7957: }
1.698     harmsja  7958: 
1.911     bisitz   7959: h2,
                   7960: h3,
                   7961: h4,
                   7962: h5,
                   7963: h6 {
                   7964:   margin: 5px 0 5px 0;
                   7965:   padding: 0;
                   7966:   line-height:130%;
1.693     droeschl 7967: }
1.795     www      7968: 
                   7969: .LC_hcell {
1.911     bisitz   7970:   padding:3px 15px 3px 15px;
                   7971:   margin: 0;
                   7972:   background-color:$tabbg;
                   7973:   color:$fontmenu;
                   7974:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7975: }
1.795     www      7976: 
1.840     bisitz   7977: .LC_Box > .LC_hcell {
1.911     bisitz   7978:   margin: 0 -10px 10px -10px;
1.835     bisitz   7979: }
                   7980: 
1.721     harmsja  7981: .LC_noBorder {
1.911     bisitz   7982:   border: 0;
1.698     harmsja  7983: }
1.693     droeschl 7984: 
1.721     harmsja  7985: .LC_FormSectionClearButton input {
1.911     bisitz   7986:   background-color:transparent;
                   7987:   border: none;
                   7988:   cursor:pointer;
                   7989:   text-decoration:underline;
1.693     droeschl 7990: }
1.763     bisitz   7991: 
                   7992: .LC_help_open_topic {
1.911     bisitz   7993:   color: #FFFFFF;
                   7994:   background-color: #EEEEFF;
                   7995:   margin: 1px;
                   7996:   padding: 4px;
                   7997:   border: 1px solid #000033;
                   7998:   white-space: nowrap;
                   7999:   /* vertical-align: middle; */
1.759     neumanie 8000: }
1.693     droeschl 8001: 
1.911     bisitz   8002: dl,
                   8003: ul,
                   8004: div,
                   8005: fieldset {
                   8006:   margin: 10px 10px 10px 0;
                   8007:   /* overflow: hidden; */
1.693     droeschl 8008: }
1.795     www      8009: 
1.1075.2.161.  .18(raeb 8010:-23): fieldset#LC_selectuser {
                   8011:-23):     margin: 0;
                   8012:-23):     padding: 0;
                   8013:-23): }
                   8014:-23): 
1.1075.2.90  raeburn  8015: article.geogebraweb div {
                   8016:     margin: 0;
                   8017: }
                   8018: 
1.838     bisitz   8019: fieldset > legend {
1.911     bisitz   8020:   font-weight: bold;
                   8021:   padding: 0 5px 0 5px;
1.838     bisitz   8022: }
                   8023: 
1.813     bisitz   8024: #LC_nav_bar {
1.911     bisitz   8025:   float: left;
1.995     raeburn  8026:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8027:   margin: 0 0 2px 0;
1.807     droeschl 8028: }
                   8029: 
1.916     droeschl 8030: #LC_realm {
                   8031:   margin: 0.2em 0 0 0;
                   8032:   padding: 0;
                   8033:   font-weight: bold;
                   8034:   text-align: center;
1.995     raeburn  8035:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8036: }
                   8037: 
1.911     bisitz   8038: #LC_nav_bar em {
                   8039:   font-weight: bold;
                   8040:   font-style: normal;
1.807     droeschl 8041: }
                   8042: 
1.897     wenzelju 8043: ol.LC_primary_menu {
1.934     droeschl 8044:   margin: 0;
1.1075.2.2  raeburn  8045:   padding: 0;
1.807     droeschl 8046: }
                   8047: 
1.852     droeschl 8048: ol#LC_PathBreadcrumbs {
1.911     bisitz   8049:   margin: 0;
1.693     droeschl 8050: }
                   8051: 
1.897     wenzelju 8052: ol.LC_primary_menu li {
1.1075.2.2  raeburn  8053:   color: RGB(80, 80, 80);
                   8054:   vertical-align: middle;
                   8055:   text-align: left;
                   8056:   list-style: none;
1.1075.2.112  raeburn  8057:   position: relative;
1.1075.2.2  raeburn  8058:   float: left;
1.1075.2.112  raeburn  8059:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8060:   line-height: 1.5em;
1.1075.2.2  raeburn  8061: }
                   8062: 
1.1075.2.113  raeburn  8063: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  8064: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  8065:   display: block;
                   8066:   margin: 0;
                   8067:   padding: 0 5px 0 10px;
                   8068:   text-decoration: none;
                   8069: }
                   8070: 
1.1075.2.112  raeburn  8071: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8072:   display: inline-block;
                   8073:   width: 95%;
                   8074:   text-align: left;
                   8075: }
                   8076: 
                   8077: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8078:   display: inline-block;
                   8079:   width: 5%;
                   8080:   float: right;
                   8081:   text-align: right;
                   8082:   font-size: 70%;
                   8083: }
                   8084: 
                   8085: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  8086:   display: none;
1.1075.2.112  raeburn  8087:   width: 15em;
1.1075.2.2  raeburn  8088:   background-color: $data_table_light;
1.1075.2.112  raeburn  8089:   position: absolute;
                   8090:   top: 100%;
                   8091: }
                   8092: 
                   8093: ol.LC_primary_menu ul ul {
                   8094:   left: 100%;
                   8095:   top: 0;
1.1075.2.2  raeburn  8096: }
                   8097: 
1.1075.2.112  raeburn  8098: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  8099:   display: block;
                   8100:   position: absolute;
                   8101:   margin: 0;
                   8102:   padding: 0;
1.1075.2.5  raeburn  8103:   z-index: 2;
1.1075.2.2  raeburn  8104: }
                   8105: 
                   8106: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  8107: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  8108:   font-size: 90%;
1.911     bisitz   8109:   vertical-align: top;
1.1075.2.2  raeburn  8110:   float: none;
1.1075.2.5  raeburn  8111:   border-left: 1px solid black;
                   8112:   border-right: 1px solid black;
1.1075.2.112  raeburn  8113: /* A dark bottom border to visualize different menu options;
                   8114: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8115:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  8116: }
                   8117: 
1.1075.2.112  raeburn  8118: ol.LC_primary_menu li li p:hover {
                   8119:   color:$button_hover;
                   8120:   text-decoration:none;
                   8121:   background-color:$data_table_dark;
1.1075.2.2  raeburn  8122: }
                   8123: 
                   8124: ol.LC_primary_menu li li a:hover {
                   8125:    color:$button_hover;
                   8126:    background-color:$data_table_dark;
1.693     droeschl 8127: }
                   8128: 
1.1075.2.112  raeburn  8129: /* Font-size equal to the size of the predecessors*/
                   8130: ol.LC_primary_menu li:hover li li {
                   8131:   font-size: 100%;
                   8132: }
                   8133: 
1.897     wenzelju 8134: ol.LC_primary_menu li img {
1.911     bisitz   8135:   vertical-align: bottom;
1.934     droeschl 8136:   height: 1.1em;
1.1075.2.3  raeburn  8137:   margin: 0.2em 0 0 0;
1.693     droeschl 8138: }
                   8139: 
1.897     wenzelju 8140: ol.LC_primary_menu a {
1.911     bisitz   8141:   color: RGB(80, 80, 80);
                   8142:   text-decoration: none;
1.693     droeschl 8143: }
1.795     www      8144: 
1.949     droeschl 8145: ol.LC_primary_menu a.LC_new_message {
                   8146:   font-weight:bold;
                   8147:   color: darkred;
                   8148: }
                   8149: 
1.975     raeburn  8150: ol.LC_docs_parameters {
                   8151:   margin-left: 0;
                   8152:   padding: 0;
                   8153:   list-style: none;
                   8154: }
                   8155: 
                   8156: ol.LC_docs_parameters li {
                   8157:   margin: 0;
                   8158:   padding-right: 20px;
                   8159:   display: inline;
                   8160: }
                   8161: 
1.976     raeburn  8162: ol.LC_docs_parameters li:before {
                   8163:   content: "\\002022 \\0020";
                   8164: }
                   8165: 
                   8166: li.LC_docs_parameters_title {
                   8167:   font-weight: bold;
                   8168: }
                   8169: 
                   8170: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8171:   content: "";
                   8172: }
                   8173: 
1.897     wenzelju 8174: ul#LC_secondary_menu {
1.1075.2.23  raeburn  8175:   clear: right;
1.911     bisitz   8176:   color: $fontmenu;
                   8177:   background: $tabbg;
                   8178:   list-style: none;
                   8179:   padding: 0;
                   8180:   margin: 0;
                   8181:   width: 100%;
1.995     raeburn  8182:   text-align: left;
1.1075.2.4  raeburn  8183:   float: left;
1.808     droeschl 8184: }
                   8185: 
1.897     wenzelju 8186: ul#LC_secondary_menu li {
1.911     bisitz   8187:   font-weight: bold;
                   8188:   line-height: 1.8em;
                   8189:   border-right: 1px solid black;
1.1075.2.4  raeburn  8190:   float: left;
                   8191: }
                   8192: 
                   8193: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8194:   background-color: $data_table_light;
                   8195: }
                   8196: 
                   8197: ul#LC_secondary_menu li a {
                   8198:   padding: 0 0.8em;
                   8199: }
                   8200: 
                   8201: ul#LC_secondary_menu li ul {
                   8202:   display: none;
                   8203: }
                   8204: 
                   8205: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8206:   display: block;
                   8207:   position: absolute;
                   8208:   margin: 0;
                   8209:   padding: 0;
                   8210:   list-style:none;
                   8211:   float: none;
                   8212:   background-color: $data_table_light;
1.1075.2.5  raeburn  8213:   z-index: 2;
1.1075.2.10  raeburn  8214:   margin-left: -1px;
1.1075.2.4  raeburn  8215: }
                   8216: 
                   8217: ul#LC_secondary_menu li ul li {
                   8218:   font-size: 90%;
                   8219:   vertical-align: top;
                   8220:   border-left: 1px solid black;
                   8221:   border-right: 1px solid black;
1.1075.2.33  raeburn  8222:   background-color: $data_table_light;
1.1075.2.4  raeburn  8223:   list-style:none;
                   8224:   float: none;
                   8225: }
                   8226: 
                   8227: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8228:   background-color: $data_table_dark;
1.807     droeschl 8229: }
                   8230: 
1.847     tempelho 8231: ul.LC_TabContent {
1.911     bisitz   8232:   display:block;
                   8233:   background: $sidebg;
                   8234:   border-bottom: solid 1px $lg_border_color;
                   8235:   list-style:none;
1.1020    raeburn  8236:   margin: -1px -10px 0 -10px;
1.911     bisitz   8237:   padding: 0;
1.693     droeschl 8238: }
                   8239: 
1.795     www      8240: ul.LC_TabContent li,
                   8241: ul.LC_TabContentBigger li {
1.911     bisitz   8242:   float:left;
1.741     harmsja  8243: }
1.795     www      8244: 
1.897     wenzelju 8245: ul#LC_secondary_menu li a {
1.911     bisitz   8246:   color: $fontmenu;
                   8247:   text-decoration: none;
1.693     droeschl 8248: }
1.795     www      8249: 
1.721     harmsja  8250: ul.LC_TabContent {
1.952     onken    8251:   min-height:20px;
1.721     harmsja  8252: }
1.795     www      8253: 
                   8254: ul.LC_TabContent li {
1.911     bisitz   8255:   vertical-align:middle;
1.959     onken    8256:   padding: 0 16px 0 10px;
1.911     bisitz   8257:   background-color:$tabbg;
                   8258:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8259:   border-left: solid 1px $font;
1.721     harmsja  8260: }
1.795     www      8261: 
1.847     tempelho 8262: ul.LC_TabContent .right {
1.911     bisitz   8263:   float:right;
1.847     tempelho 8264: }
                   8265: 
1.911     bisitz   8266: ul.LC_TabContent li a,
                   8267: ul.LC_TabContent li {
                   8268:   color:rgb(47,47,47);
                   8269:   text-decoration:none;
                   8270:   font-size:95%;
                   8271:   font-weight:bold;
1.952     onken    8272:   min-height:20px;
                   8273: }
                   8274: 
1.959     onken    8275: ul.LC_TabContent li a:hover,
                   8276: ul.LC_TabContent li a:focus {
1.952     onken    8277:   color: $button_hover;
1.959     onken    8278:   background:none;
                   8279:   outline:none;
1.952     onken    8280: }
                   8281: 
                   8282: ul.LC_TabContent li:hover {
                   8283:   color: $button_hover;
                   8284:   cursor:pointer;
1.721     harmsja  8285: }
1.795     www      8286: 
1.911     bisitz   8287: ul.LC_TabContent li.active {
1.952     onken    8288:   color: $font;
1.911     bisitz   8289:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8290:   border-bottom:solid 1px #FFFFFF;
                   8291:   cursor: default;
1.744     ehlerst  8292: }
1.795     www      8293: 
1.959     onken    8294: ul.LC_TabContent li.active a {
                   8295:   color:$font;
                   8296:   background:#FFFFFF;
                   8297:   outline: none;
                   8298: }
1.1047    raeburn  8299: 
                   8300: ul.LC_TabContent li.goback {
                   8301:   float: left;
                   8302:   border-left: none;
                   8303: }
                   8304: 
1.870     tempelho 8305: #maincoursedoc {
1.911     bisitz   8306:   clear:both;
1.870     tempelho 8307: }
                   8308: 
                   8309: ul.LC_TabContentBigger {
1.911     bisitz   8310:   display:block;
                   8311:   list-style:none;
                   8312:   padding: 0;
1.870     tempelho 8313: }
                   8314: 
1.795     www      8315: ul.LC_TabContentBigger li {
1.911     bisitz   8316:   vertical-align:bottom;
                   8317:   height: 30px;
                   8318:   font-size:110%;
                   8319:   font-weight:bold;
                   8320:   color: #737373;
1.841     tempelho 8321: }
                   8322: 
1.957     onken    8323: ul.LC_TabContentBigger li.active {
                   8324:   position: relative;
                   8325:   top: 1px;
                   8326: }
                   8327: 
1.870     tempelho 8328: ul.LC_TabContentBigger li a {
1.911     bisitz   8329:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8330:   height: 30px;
                   8331:   line-height: 30px;
                   8332:   text-align: center;
                   8333:   display: block;
                   8334:   text-decoration: none;
1.958     onken    8335:   outline: none;  
1.741     harmsja  8336: }
1.795     www      8337: 
1.870     tempelho 8338: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8339:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8340:   color:$font;
1.744     ehlerst  8341: }
1.795     www      8342: 
1.870     tempelho 8343: ul.LC_TabContentBigger li b {
1.911     bisitz   8344:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8345:   display: block;
                   8346:   float: left;
                   8347:   padding: 0 30px;
1.957     onken    8348:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8349: }
                   8350: 
1.956     onken    8351: ul.LC_TabContentBigger li:hover b {
                   8352:   color:$button_hover;
                   8353: }
                   8354: 
1.870     tempelho 8355: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8356:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8357:   color:$font;
1.957     onken    8358:   border: 0;
1.741     harmsja  8359: }
1.693     droeschl 8360: 
1.870     tempelho 8361: 
1.862     bisitz   8362: ul.LC_CourseBreadcrumbs {
                   8363:   background: $sidebg;
1.1020    raeburn  8364:   height: 2em;
1.862     bisitz   8365:   padding-left: 10px;
1.1020    raeburn  8366:   margin: 0;
1.862     bisitz   8367:   list-style-position: inside;
                   8368: }
                   8369: 
1.911     bisitz   8370: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8371: ol#LC_PathBreadcrumbs {
1.911     bisitz   8372:   padding-left: 10px;
                   8373:   margin: 0;
1.933     droeschl 8374:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8375: }
                   8376: 
1.911     bisitz   8377: ol#LC_MenuBreadcrumbs li,
                   8378: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8379: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8380:   display: inline;
1.933     droeschl 8381:   white-space: normal;  
1.693     droeschl 8382: }
                   8383: 
1.823     bisitz   8384: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8385: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8386:   text-decoration: none;
                   8387:   font-size:90%;
1.693     droeschl 8388: }
1.795     www      8389: 
1.969     droeschl 8390: ol#LC_MenuBreadcrumbs h1 {
                   8391:   display: inline;
                   8392:   font-size: 90%;
                   8393:   line-height: 2.5em;
                   8394:   margin: 0;
                   8395:   padding: 0;
                   8396: }
                   8397: 
1.795     www      8398: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8399:   text-decoration:none;
                   8400:   font-size:100%;
                   8401:   font-weight:bold;
1.693     droeschl 8402: }
1.795     www      8403: 
1.840     bisitz   8404: .LC_Box {
1.911     bisitz   8405:   border: solid 1px $lg_border_color;
                   8406:   padding: 0 10px 10px 10px;
1.746     neumanie 8407: }
1.795     www      8408: 
1.1020    raeburn  8409: .LC_DocsBox {
                   8410:   border: solid 1px $lg_border_color;
                   8411:   padding: 0 0 10px 10px;
                   8412: }
                   8413: 
1.795     www      8414: .LC_AboutMe_Image {
1.911     bisitz   8415:   float:left;
                   8416:   margin-right:10px;
1.747     neumanie 8417: }
1.795     www      8418: 
                   8419: .LC_Clear_AboutMe_Image {
1.911     bisitz   8420:   clear:left;
1.747     neumanie 8421: }
1.795     www      8422: 
1.721     harmsja  8423: dl.LC_ListStyleClean dt {
1.911     bisitz   8424:   padding-right: 5px;
                   8425:   display: table-header-group;
1.693     droeschl 8426: }
                   8427: 
1.721     harmsja  8428: dl.LC_ListStyleClean dd {
1.911     bisitz   8429:   display: table-row;
1.693     droeschl 8430: }
                   8431: 
1.721     harmsja  8432: .LC_ListStyleClean,
                   8433: .LC_ListStyleSimple,
                   8434: .LC_ListStyleNormal,
1.795     www      8435: .LC_ListStyleSpecial {
1.911     bisitz   8436:   /* display:block; */
                   8437:   list-style-position: inside;
                   8438:   list-style-type: none;
                   8439:   overflow: hidden;
                   8440:   padding: 0;
1.693     droeschl 8441: }
                   8442: 
1.721     harmsja  8443: .LC_ListStyleSimple li,
                   8444: .LC_ListStyleSimple dd,
                   8445: .LC_ListStyleNormal li,
                   8446: .LC_ListStyleNormal dd,
                   8447: .LC_ListStyleSpecial li,
1.795     www      8448: .LC_ListStyleSpecial dd {
1.911     bisitz   8449:   margin: 0;
                   8450:   padding: 5px 5px 5px 10px;
                   8451:   clear: both;
1.693     droeschl 8452: }
                   8453: 
1.721     harmsja  8454: .LC_ListStyleClean li,
                   8455: .LC_ListStyleClean dd {
1.911     bisitz   8456:   padding-top: 0;
                   8457:   padding-bottom: 0;
1.693     droeschl 8458: }
                   8459: 
1.721     harmsja  8460: .LC_ListStyleSimple dd,
1.795     www      8461: .LC_ListStyleSimple li {
1.911     bisitz   8462:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8463: }
                   8464: 
1.721     harmsja  8465: .LC_ListStyleSpecial li,
                   8466: .LC_ListStyleSpecial dd {
1.911     bisitz   8467:   list-style-type: none;
                   8468:   background-color: RGB(220, 220, 220);
                   8469:   margin-bottom: 4px;
1.693     droeschl 8470: }
                   8471: 
1.721     harmsja  8472: table.LC_SimpleTable {
1.911     bisitz   8473:   margin:5px;
                   8474:   border:solid 1px $lg_border_color;
1.795     www      8475: }
1.693     droeschl 8476: 
1.721     harmsja  8477: table.LC_SimpleTable tr {
1.911     bisitz   8478:   padding: 0;
                   8479:   border:solid 1px $lg_border_color;
1.693     droeschl 8480: }
1.795     www      8481: 
                   8482: table.LC_SimpleTable thead {
1.911     bisitz   8483:   background:rgb(220,220,220);
1.693     droeschl 8484: }
                   8485: 
1.721     harmsja  8486: div.LC_columnSection {
1.911     bisitz   8487:   display: block;
                   8488:   clear: both;
                   8489:   overflow: hidden;
                   8490:   margin: 0;
1.693     droeschl 8491: }
                   8492: 
1.721     harmsja  8493: div.LC_columnSection>* {
1.911     bisitz   8494:   float: left;
                   8495:   margin: 10px 20px 10px 0;
                   8496:   overflow:hidden;
1.693     droeschl 8497: }
1.721     harmsja  8498: 
1.795     www      8499: table em {
1.911     bisitz   8500:   font-weight: bold;
                   8501:   font-style: normal;
1.748     schulted 8502: }
1.795     www      8503: 
1.779     bisitz   8504: table.LC_tableBrowseRes,
1.795     www      8505: table.LC_tableOfContent {
1.911     bisitz   8506:   border:none;
                   8507:   border-spacing: 1px;
                   8508:   padding: 3px;
                   8509:   background-color: #FFFFFF;
                   8510:   font-size: 90%;
1.753     droeschl 8511: }
1.789     droeschl 8512: 
1.911     bisitz   8513: table.LC_tableOfContent {
                   8514:   border-collapse: collapse;
1.789     droeschl 8515: }
                   8516: 
1.771     droeschl 8517: table.LC_tableBrowseRes a,
1.768     schulted 8518: table.LC_tableOfContent a {
1.911     bisitz   8519:   background-color: transparent;
                   8520:   text-decoration: none;
1.753     droeschl 8521: }
                   8522: 
1.795     www      8523: table.LC_tableOfContent img {
1.911     bisitz   8524:   border: none;
                   8525:   height: 1.3em;
                   8526:   vertical-align: text-bottom;
                   8527:   margin-right: 0.3em;
1.753     droeschl 8528: }
1.757     schulted 8529: 
1.795     www      8530: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8531:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8532: }
                   8533: 
1.795     www      8534: a#LC_content_toolbar_everything {
1.911     bisitz   8535:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8536: }
                   8537: 
1.795     www      8538: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8539:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8540: }
                   8541: 
1.795     www      8542: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8543:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8544: }
                   8545: 
1.795     www      8546: a#LC_content_toolbar_changefolder {
1.911     bisitz   8547:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8548: }
                   8549: 
1.795     www      8550: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8551:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8552: }
                   8553: 
1.1043    raeburn  8554: a#LC_content_toolbar_edittoplevel {
                   8555:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8556: }
                   8557: 
1.1075.2.161.  .12(raeb 8558:-23): a#LC_content_toolbar_printout {
                   8559:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8560:-23): }
                   8561:-23): 
1.795     www      8562: ul#LC_toolbar li a:hover {
1.911     bisitz   8563:   background-position: bottom center;
1.757     schulted 8564: }
                   8565: 
1.795     www      8566: ul#LC_toolbar {
1.911     bisitz   8567:   padding: 0;
                   8568:   margin: 2px;
                   8569:   list-style:none;
                   8570:   position:relative;
                   8571:   background-color:white;
1.1075.2.9  raeburn  8572:   overflow: auto;
1.757     schulted 8573: }
                   8574: 
1.795     www      8575: ul#LC_toolbar li {
1.911     bisitz   8576:   border:1px solid white;
                   8577:   padding: 0;
                   8578:   margin: 0;
                   8579:   float: left;
                   8580:   display:inline;
                   8581:   vertical-align:middle;
1.1075.2.9  raeburn  8582:   white-space: nowrap;
1.911     bisitz   8583: }
1.757     schulted 8584: 
1.783     amueller 8585: 
1.795     www      8586: a.LC_toolbarItem {
1.911     bisitz   8587:   display:block;
                   8588:   padding: 0;
                   8589:   margin: 0;
                   8590:   height: 32px;
                   8591:   width: 32px;
                   8592:   color:white;
                   8593:   border: none;
                   8594:   background-repeat:no-repeat;
                   8595:   background-color:transparent;
1.757     schulted 8596: }
                   8597: 
1.915     droeschl 8598: ul.LC_funclist {
                   8599:     margin: 0;
                   8600:     padding: 0.5em 1em 0.5em 0;
                   8601: }
                   8602: 
1.933     droeschl 8603: ul.LC_funclist > li:first-child {
                   8604:     font-weight:bold; 
                   8605:     margin-left:0.8em;
                   8606: }
                   8607: 
1.915     droeschl 8608: ul.LC_funclist + ul.LC_funclist {
                   8609:     /* 
                   8610:        left border as a seperator if we have more than
                   8611:        one list 
                   8612:     */
                   8613:     border-left: 1px solid $sidebg;
                   8614:     /* 
                   8615:        this hides the left border behind the border of the 
                   8616:        outer box if element is wrapped to the next 'line' 
                   8617:     */
                   8618:     margin-left: -1px;
                   8619: }
                   8620: 
1.843     bisitz   8621: ul.LC_funclist li {
1.915     droeschl 8622:   display: inline;
1.782     bisitz   8623:   white-space: nowrap;
1.915     droeschl 8624:   margin: 0 0 0 25px;
                   8625:   line-height: 150%;
1.782     bisitz   8626: }
                   8627: 
1.974     wenzelju 8628: .LC_hidden {
                   8629:   display: none;
                   8630: }
                   8631: 
1.1030    www      8632: .LCmodal-overlay {
                   8633: 		position:fixed;
                   8634: 		top:0;
                   8635: 		right:0;
                   8636: 		bottom:0;
                   8637: 		left:0;
                   8638: 		height:100%;
                   8639: 		width:100%;
                   8640: 		margin:0;
                   8641: 		padding:0;
                   8642: 		background:#999;
                   8643: 		opacity:.75;
                   8644: 		filter: alpha(opacity=75);
                   8645: 		-moz-opacity: 0.75;
                   8646: 		z-index:101;
                   8647: }
                   8648: 
                   8649: * html .LCmodal-overlay {   
                   8650: 		position: absolute;
                   8651: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8652: }
                   8653: 
                   8654: .LCmodal-window {
                   8655: 		position:fixed;
                   8656: 		top:50%;
                   8657: 		left:50%;
                   8658: 		margin:0;
                   8659: 		padding:0;
                   8660: 		z-index:102;
                   8661: 	}
                   8662: 
                   8663: * html .LCmodal-window {
                   8664: 		position:absolute;
                   8665: }
                   8666: 
                   8667: .LCclose-window {
                   8668: 		position:absolute;
                   8669: 		width:32px;
                   8670: 		height:32px;
                   8671: 		right:8px;
                   8672: 		top:8px;
                   8673: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8674: 		text-indent:-99999px;
                   8675: 		overflow:hidden;
                   8676: 		cursor:pointer;
                   8677: }
                   8678: 
1.1075.2.158  raeburn  8679: .LCisDisabled {
                   8680:   cursor: not-allowed;
                   8681:   opacity: 0.5;
                   8682: }
                   8683: 
                   8684: a[aria-disabled="true"] {
                   8685:   color: currentColor;
                   8686:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8687:   pointer-events: none;
                   8688:   text-decoration: none;
                   8689: }
                   8690: 
1.1075.2.141  raeburn  8691: pre.LC_wordwrap {
                   8692:   white-space: pre-wrap;
                   8693:   white-space: -moz-pre-wrap;
                   8694:   white-space: -pre-wrap;
                   8695:   white-space: -o-pre-wrap;
                   8696:   word-wrap: break-word;
                   8697: }
                   8698: 
1.1075.2.17  raeburn  8699: /*
1.1075.2.161.  .21(raeb 8700:-24):   styles used for response display
                   8701:-24): */
                   8702:-24): div.LC_radiofoil, div.LC_rankfoil {
                   8703:-24):   margin: .5em 0em .5em 0em;
                   8704:-24): }
                   8705:-24): table.LC_itemgroup {
                   8706:-24):   margin-top: 1em;
                   8707:-24): }
                   8708:-24): 
                   8709:-24): /*
1.1075.2.17  raeburn  8710:   styles used by TTH when "Default set of options to pass to tth/m
                   8711:   when converting TeX" in course settings has been set
                   8712: 
                   8713:   option passed: -t
                   8714: 
                   8715: */
                   8716: 
                   8717: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8718: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8719: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8720: td div.norm {line-height:normal;}
                   8721: 
                   8722: /*
                   8723:   option passed -y3
                   8724: */
                   8725: 
                   8726: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8727: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8728: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8729: 
1.1075.2.161.  .21(raeb 8730:-24): /*
                   8731:-24):   sections with roles, for content only
                   8732:-24): */
                   8733:-24): section[class^="role-"] {
                   8734:-24):   padding-left: 10px;
                   8735:-24):   padding-right: 5px;
                   8736:-24):   margin-top: 8px;
                   8737:-24):   margin-bottom: 8px;
                   8738:-24):   border: 1px solid #2A4;
                   8739:-24):   border-radius: 5px;
                   8740:-24):   box-shadow: 0px 1px 1px #BBB;
                   8741:-24): }
                   8742:-24): section[class^="role-"]>h1 {
                   8743:-24):   position: relative;
                   8744:-24):   margin: 0px;
                   8745:-24):   padding-top: 10px;
                   8746:-24):   padding-left: 40px;
                   8747:-24): }
                   8748:-24): section[class^="role-"]>h1:before {
                   8749:-24):   position: absolute;
                   8750:-24):   left: -5px;
                   8751:-24):   top: 5px;
                   8752:-24): }
                   8753:-24): section.role-activity>h1:before {
                   8754:-24):   content:url('/adm/daxe/images/section_icons/activity.png');
                   8755:-24): }
                   8756:-24): section.role-advice>h1:before {
                   8757:-24):   content:url('/adm/daxe/images/section_icons/advice.png');
                   8758:-24): }
                   8759:-24): section.role-bibliography>h1:before {
                   8760:-24):   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8761:-24): }
                   8762:-24): section.role-citation>h1:before {
                   8763:-24):   content:url('/adm/daxe/images/section_icons/citation.png');
                   8764:-24): }
                   8765:-24): section.role-conclusion>h1:before {
                   8766:-24):   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8767:-24): }
                   8768:-24): section.role-definition>h1:before {
                   8769:-24):   content:url('/adm/daxe/images/section_icons/definition.png');
                   8770:-24): }
                   8771:-24): section.role-demonstration>h1:before {
                   8772:-24):   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8773:-24): }
                   8774:-24): section.role-example>h1:before {
                   8775:-24):   content:url('/adm/daxe/images/section_icons/example.png');
                   8776:-24): }
                   8777:-24): section.role-explanation>h1:before {
                   8778:-24):   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8779:-24): }
                   8780:-24): section.role-introduction>h1:before {
                   8781:-24):   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8782:-24): }
                   8783:-24): section.role-method>h1:before {
                   8784:-24):   content:url('/adm/daxe/images/section_icons/method.png');
                   8785:-24): }
                   8786:-24): section.role-more_information>h1:before {
                   8787:-24):   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8788:-24): }
                   8789:-24): section.role-objectives>h1:before {
                   8790:-24):   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8791:-24): }
                   8792:-24): section.role-prerequisites>h1:before {
                   8793:-24):   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8794:-24): }
                   8795:-24): section.role-remark>h1:before {
                   8796:-24):   content:url('/adm/daxe/images/section_icons/remark.png');
                   8797:-24): }
                   8798:-24): section.role-reminder>h1:before {
                   8799:-24):   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8800:-24): }
                   8801:-24): section.role-summary>h1:before {
                   8802:-24):   content:url('/adm/daxe/images/section_icons/summary.png');
                   8803:-24): }
                   8804:-24): section.role-syntax>h1:before {
                   8805:-24):   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8806:-24): }
                   8807:-24): section.role-warning>h1:before {
                   8808:-24):   content:url('/adm/daxe/images/section_icons/warning.png');
                   8809:-24): }
                   8810:-24): 
1.1075.2.121  raeburn  8811: #LC_minitab_header {
                   8812:   float:left;
                   8813:   width:100%;
                   8814:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8815:   font-size:93%;
                   8816:   line-height:normal;
                   8817:   margin: 0.5em 0 0.5em 0;
                   8818: }
                   8819: #LC_minitab_header ul {
                   8820:   margin:0;
                   8821:   padding:10px 10px 0;
                   8822:   list-style:none;
                   8823: }
                   8824: #LC_minitab_header li {
                   8825:   float:left;
                   8826:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8827:   margin:0;
                   8828:   padding:0 0 0 9px;
                   8829: }
                   8830: #LC_minitab_header a {
                   8831:   display:block;
                   8832:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8833:   padding:5px 15px 4px 6px;
                   8834: }
                   8835: #LC_minitab_header #LC_current_minitab {
                   8836:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8837: }
                   8838: #LC_minitab_header #LC_current_minitab a {
                   8839:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8840:   padding-bottom:5px;
                   8841: }
                   8842: 
                   8843: 
1.343     albertel 8844: END
                   8845: }
                   8846: 
1.306     albertel 8847: =pod
                   8848: 
                   8849: =item * &headtag()
                   8850: 
                   8851: Returns a uniform footer for LON-CAPA web pages.
                   8852: 
1.307     albertel 8853: Inputs: $title - optional title for the head
                   8854:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8855:         $args - optional arguments
1.319     albertel 8856:             force_register - if is true call registerurl so the remote is 
                   8857:                              informed
1.415     albertel 8858:             redirect       -> array ref of
                   8859:                                    1- seconds before redirect occurs
                   8860:                                    2- url to redirect to
                   8861:                                    3- whether the side effect should occur
1.315     albertel 8862:                            (side effect of setting 
                   8863:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8864:22):                                redirected to)
                   8865:22):                                    4- whether the redirect target should be
                   8866:22):                                       the opener of the current (pop-up)
                   8867:22):                                       window (side effect of setting
                   8868:22):                                       $env{'internal.head.to_opener'} to
                   8869:22):                                       1, if true.
          .10(raeb 8870:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8871:             domain         -> force to color decorate a page for a specific
                   8872:                                domain
                   8873:             function       -> force usage of a specific rolish color scheme
                   8874:             bgcolor        -> override the default page bgcolor
1.460     albertel 8875:             no_auto_mt_title
                   8876:                            -> prevent &mt()ing the title arg
1.464     albertel 8877: 
1.306     albertel 8878: =cut
                   8879: 
                   8880: sub headtag {
1.313     albertel 8881:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8882:     
1.363     albertel 8883:     my $function = $args->{'function'} || &get_users_function();
                   8884:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8885:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8886:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8887:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8888: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8889: 		   #time(),
1.418     albertel 8890: 		   $env{'environment.color.timestamp'},
1.363     albertel 8891: 		   $function,$domain,$bgcolor);
                   8892: 
1.369     www      8893:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8894: 
1.308     albertel 8895:     my $result =
                   8896: 	'<head>'.
1.1075.2.56  raeburn  8897: 	&font_settings($args);
1.319     albertel 8898: 
1.1075.2.72  raeburn  8899:     my $inhibitprint;
                   8900:     if ($args->{'print_suppress'}) {
                   8901:         $inhibitprint = &print_suppression();
                   8902:     }
1.1064    raeburn  8903: 
1.461     albertel 8904:     if (!$args->{'frameset'}) {
                   8905: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8906:     }
1.1075.2.12  raeburn  8907:     if ($args->{'force_register'}) {
                   8908:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8909:     }
1.436     albertel 8910:     if (!$args->{'no_nav_bar'} 
                   8911: 	&& !$args->{'only_body'}
                   8912: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8913: 	$result .= &help_menu_js($httphost);
1.1032    www      8914:         $result.=&modal_window();
1.1038    www      8915:         $result.=&togglebox_script();
1.1034    www      8916:         $result.=&wishlist_window();
1.1041    www      8917:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8918:     } else {
                   8919:         if ($args->{'add_modal'}) {
                   8920:            $result.=&modal_window();
                   8921:         }
                   8922:         if ($args->{'add_wishlist'}) {
                   8923:            $result.=&wishlist_window();
                   8924:         }
1.1038    www      8925:         if ($args->{'add_togglebox'}) {
                   8926:            $result.=&togglebox_script();
                   8927:         }
1.1041    www      8928:         if ($args->{'add_progressbar'}) {
                   8929:            $result.=&LCprogressbarUpdate_script();
                   8930:         }
1.436     albertel 8931:     }
1.314     albertel 8932:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8933:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8934:-22):         if (!$skip_enc_check) {
                   8935:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8936:-22):         }
1.414     albertel 8937: 	if (!$inhibit_continue) {
                   8938: 	    $env{'internal.head.redirect'} = $url;
                   8939: 	}
1.1075.2.161.  .9(raebu 8940:22):         $result.=<<"ADDMETA";
1.313     albertel 8941: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8942:22): ADDMETA
                   8943:22):         if ($to_opener) {
                   8944:22):             $env{'internal.head.to_opener'} = 1;
                   8945:22):             my $dest = &js_escape($url);
                   8946:22):             my $timeout = int($time * 1000);
                   8947:22):             $result .=<<"ENDJS";
                   8948:22): <script type="text/javascript">
                   8949:22): // <![CDATA[
                   8950:22): function LC_To_Opener() {
                   8951:22):     var dest = '$dest';
                   8952:22):     if (dest != '') {
                   8953:22):         if (window.opener != null && !window.opener.closed) {
                   8954:22):             window.opener.location.href=dest;
                   8955:22):             window.close();
                   8956:22):         } else {
                   8957:22):             window.location.href=dest;
                   8958:22):         }
                   8959:22):     }
                   8960:22): }
                   8961:22): \$(document).ready(function () {
                   8962:22):     setTimeout('LC_To_Opener()',$timeout);
                   8963:22): });
                   8964:22): // ]]>
                   8965:22): </script>
                   8966:22): ENDJS
                   8967:22):         } else {
                   8968:22):             $result.=<<"ADDMETA";
1.344     albertel 8969: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8970: ADDMETA
1.1075.2.161.  .9(raebu 8971:22):         }
1.1075.2.89  raeburn  8972:     } else {
                   8973:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8974:             my $requrl = $env{'request.uri'};
                   8975:             if ($requrl eq '') {
                   8976:                 $requrl = $ENV{'REQUEST_URI'};
                   8977:                 $requrl =~ s/\?.+$//;
                   8978:             }
                   8979:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8980:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8981:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8982:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8983:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8984:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8985:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8986:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8987:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8988:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8989:                             $offload = 1;
1.1075.2.151  raeburn  8990:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8991:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8992:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8993:                                     $offloadoth = 1;
                   8994:                                     $dom_in_use = $env{'user.domain'};
                   8995:                                 }
                   8996:                             }
1.1075.2.145  raeburn  8997:                         }
                   8998:                     }
                   8999:                     unless ($offload) {
                   9000:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9001:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9002:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9003:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9004:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9005:                                         $offload = 1;
1.1075.2.151  raeburn  9006:                                         $offloadoth = 1;
1.1075.2.145  raeburn  9007:                                         $dom_in_use = $env{'user.domain'};
                   9008:                                     }
1.1075.2.89  raeburn  9009:                                 }
1.1075.2.145  raeburn  9010:                             }
                   9011:                         }
                   9012:                     }
                   9013:                     if ($offload) {
1.1075.2.158  raeburn  9014:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  9015:                         if (($newserver eq '') && ($offloadoth)) {
                   9016:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 9017:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  9018:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9019:                             }
                   9020:                         }
1.1075.2.145  raeburn  9021:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9022:                             my $numsec = 5;
                   9023:                             my $timeout = $numsec * 1000;
                   9024:                             my ($newurl,$locknum,%locks,$msg);
                   9025:                             if ($env{'request.role.adv'}) {
                   9026:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9027:                             }
                   9028:                             my $disable_submit = 0;
                   9029:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9030:                                 $disable_submit = 1;
                   9031:                             }
                   9032:                             if ($locknum) {
                   9033:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  9034:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  9035:                                        join(", ",sort(values(%locks)))."\n";
                   9036:                                 if (&show_course()) {
                   9037:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  9038:                                 } else {
1.1075.2.145  raeburn  9039:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   9040:                                 }
                   9041:                             } else {
                   9042:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9043:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9044:                                 }
                   9045:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9046:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9047:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9048:                                     $newurl .= '&role='.$env{'request.role'};
                   9049:                                 }
                   9050:                                 if ($env{'request.symb'}) {
                   9051:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9052:                                     if ($shownsymb =~ m{^/enc/}) {
                   9053:                                         my $reqdmajor = 2;
                   9054:                                         my $reqdminor = 11;
                   9055:                                         my $reqdsubminor = 3;
                   9056:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9057:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9058:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9059:                                         if (($major eq '' && $minor eq '') ||
                   9060:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9061:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9062:                                              ($reqdsubminor > $subminor))))) {
                   9063:                                             undef($shownsymb);
                   9064:                                         }
1.1075.2.89  raeburn  9065:                                     }
1.1075.2.145  raeburn  9066:                                     if ($shownsymb) {
                   9067:                                         &js_escape(\$shownsymb);
                   9068:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  9069:                                     }
1.1075.2.145  raeburn  9070:                                 } else {
                   9071:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9072:                                     &js_escape(\$shownurl);
                   9073:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  9074:                                 }
1.1075.2.145  raeburn  9075:                             }
                   9076:                             &js_escape(\$msg);
                   9077:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  9078: <meta http-equiv="pragma" content="no-cache" />
                   9079: <script type="text/javascript">
1.1075.2.92  raeburn  9080: // <![CDATA[
1.1075.2.89  raeburn  9081: function LC_Offload_Now() {
                   9082:     var dest = "$newurl";
                   9083:     if (dest != '') {
                   9084:         window.location.href="$newurl";
                   9085:     }
                   9086: }
1.1075.2.92  raeburn  9087: \$(document).ready(function () {
                   9088:     window.alert('$msg');
                   9089:     if ($disable_submit) {
1.1075.2.89  raeburn  9090:         \$(".LC_hwk_submit").prop("disabled", true);
                   9091:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  9092:     }
                   9093:     setTimeout('LC_Offload_Now()', $timeout);
                   9094: });
                   9095: // ]]>
1.1075.2.89  raeburn  9096: </script>
                   9097: OFFLOAD
                   9098:                         }
                   9099:                     }
                   9100:                 }
                   9101:             }
                   9102:         }
1.313     albertel 9103:     }
1.306     albertel 9104:     if (!defined($title)) {
                   9105: 	$title = 'The LearningOnline Network with CAPA';
                   9106:     }
1.460     albertel 9107:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.161.  .25(raeb 9108:-24):     if ($title =~ /^LON-CAPA\s+/) {
                   9109:-24):         $result .= '<title> '.$title.'</title>';
                   9110:-24):     } else {
                   9111:-24):         $result .= '<title> LON-CAPA '.$title.'</title>';  
                   9112:-24):     }
                   9113:-24):     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1075.2.61  raeburn  9114:     if (!$args->{'frameset'}) {
                   9115:         $result .= ' /';
                   9116:     }
                   9117:     $result .= '>'
1.1064    raeburn  9118:         .$inhibitprint
1.414     albertel 9119: 	.$head_extra;
1.1075.2.108  raeburn  9120:     my $clientmobile;
                   9121:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9122:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9123:     } else {
                   9124:         $clientmobile = $env{'browser.mobile'};
                   9125:     }
                   9126:     if ($clientmobile) {
1.1075.2.42  raeburn  9127:         $result .= '
                   9128: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9129: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9130:     }
1.1075.2.126  raeburn  9131:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9132:     return $result.'</head>';
1.306     albertel 9133: }
                   9134: 
                   9135: =pod
                   9136: 
1.340     albertel 9137: =item * &font_settings()
                   9138: 
                   9139: Returns neccessary <meta> to set the proper encoding
                   9140: 
1.1075.2.56  raeburn  9141: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9142: 
                   9143: =cut
                   9144: 
                   9145: sub font_settings {
1.1075.2.56  raeburn  9146:     my ($args) = @_;
1.340     albertel 9147:     my $headerstring='';
1.1075.2.56  raeburn  9148:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9149:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 9150: 	$headerstring.=
1.1075.2.61  raeburn  9151: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9152:         if (!$args->{'frameset'}) {
                   9153:             $headerstring.= ' /';
                   9154:         }
                   9155:         $headerstring .= '>'."\n";
1.340     albertel 9156:     }
                   9157:     return $headerstring;
                   9158: }
                   9159: 
1.341     albertel 9160: =pod
                   9161: 
1.1064    raeburn  9162: =item * &print_suppression()
                   9163: 
                   9164: In course context returns css which causes the body to be blank when media="print",
                   9165: if printout generation is unavailable for the current resource.
                   9166: 
                   9167: This could be because:
                   9168: 
                   9169: (a) printstartdate is in the future
                   9170: 
                   9171: (b) printenddate is in the past
                   9172: 
                   9173: (c) there is an active exam block with "printout"
                   9174: functionality blocked
                   9175: 
                   9176: Users with pav, pfo or evb privileges are exempt.
                   9177: 
                   9178: Inputs: none
                   9179: 
                   9180: =cut
                   9181: 
                   9182: 
                   9183: sub print_suppression {
                   9184:     my $noprint;
                   9185:     if ($env{'request.course.id'}) {
                   9186:         my $scope = $env{'request.course.id'};
                   9187:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9188:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9189:             return;
                   9190:         }
                   9191:         if ($env{'request.course.sec'} ne '') {
                   9192:             $scope .= "/$env{'request.course.sec'}";
                   9193:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9194:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9195:                 return;
1.1064    raeburn  9196:             }
                   9197:         }
                   9198:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9199:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  9200:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9201:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9202:         if ($blocked) {
                   9203:             my $checkrole = "cm./$cdom/$cnum";
                   9204:             if ($env{'request.course.sec'} ne '') {
                   9205:                 $checkrole .= "/$env{'request.course.sec'}";
                   9206:             }
                   9207:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9208:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9209:                 $noprint = 1;
                   9210:             }
                   9211:         }
                   9212:         unless ($noprint) {
                   9213:             my $symb = &Apache::lonnet::symbread();
                   9214:             if ($symb ne '') {
                   9215:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9216:                 if (ref($navmap)) {
                   9217:                     my $res = $navmap->getBySymb($symb);
                   9218:                     if (ref($res)) {
                   9219:                         if (!$res->resprintable()) {
                   9220:                             $noprint = 1;
                   9221:                         }
                   9222:                     }
                   9223:                 }
                   9224:             }
                   9225:         }
                   9226:         if ($noprint) {
                   9227:             return <<"ENDSTYLE";
                   9228: <style type="text/css" media="print">
                   9229:     body { display:none }
                   9230: </style>
                   9231: ENDSTYLE
                   9232:         }
                   9233:     }
                   9234:     return;
                   9235: }
                   9236: 
                   9237: =pod
                   9238: 
1.341     albertel 9239: =item * &xml_begin()
                   9240: 
                   9241: Returns the needed doctype and <html>
                   9242: 
                   9243: Inputs: none
                   9244: 
                   9245: =cut
                   9246: 
                   9247: sub xml_begin {
1.1075.2.61  raeburn  9248:     my ($is_frameset) = @_;
1.341     albertel 9249:     my $output='';
                   9250: 
                   9251:     if ($env{'browser.mathml'}) {
                   9252: 	$output='<?xml version="1.0"?>'
                   9253:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9254: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9255:             
                   9256: #	    .'<!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">] >'
                   9257: 	    .'<!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">'
                   9258:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9259: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  9260:     } elsif ($is_frameset) {
                   9261:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9262:                 '<html>'."\n";
1.341     albertel 9263:     } else {
1.1075.2.61  raeburn  9264: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9265:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9266:     }
                   9267:     return $output;
                   9268: }
1.340     albertel 9269: 
                   9270: =pod
                   9271: 
1.306     albertel 9272: =item * &start_page()
                   9273: 
                   9274: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9275: 
1.648     raeburn  9276: Inputs:
                   9277: 
                   9278: =over 4
                   9279: 
                   9280: $title - optional title for the page
                   9281: 
                   9282: $head_extra - optional extra HTML to incude inside the <head>
                   9283: 
                   9284: $args - additional optional args supported are:
                   9285: 
                   9286: =over 8
                   9287: 
                   9288:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9289:                                     arg on
1.814     bisitz   9290:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9291:              add_entries    -> additional attributes to add to the  <body>
                   9292:              domain         -> force to color decorate a page for a 
1.317     albertel 9293:                                     specific domain
1.648     raeburn  9294:              function       -> force usage of a specific rolish color
1.317     albertel 9295:                                     scheme
1.648     raeburn  9296:              redirect       -> see &headtag()
                   9297:              bgcolor        -> override the default page bg color
                   9298:              js_ready       -> return a string ready for being used in 
1.317     albertel 9299:                                     a javascript writeln
1.648     raeburn  9300:              html_encode    -> return a string ready for being used in 
1.320     albertel 9301:                                     a html attribute
1.648     raeburn  9302:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9303:                                     $forcereg arg
1.648     raeburn  9304:              frameset       -> if true will start with a <frameset>
1.330     albertel 9305:                                     rather than <body>
1.648     raeburn  9306:              skip_phases    -> hash ref of 
1.338     albertel 9307:                                     head -> skip the <html><head> generation
                   9308:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  9309:              no_inline_link -> if true and in remote mode, don't show the
                   9310:                                     'Switch To Inline Menu' link
1.648     raeburn  9311:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9312:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9313:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  9314:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9315:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  9316:              group          -> includes the current group, if page is for a
                   9317:                                specific group
1.1075.2.133  raeburn  9318:              use_absolute   -> for request for external resource or syllabus, this
                   9319:                                will contain https://<hostname> if server uses
                   9320:                                https (as per hosts.tab), but request is for http
                   9321:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  9322:              links_disabled -> Links in primary and secondary menus are disabled
                   9323:                                (Can enable them once page has loaded - see lonroles.pm
                   9324:                                for an example).
1.1075.2.161.  .6(raebu 9325:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9326: 
1.648     raeburn  9327: =back
1.460     albertel 9328: 
1.648     raeburn  9329: =back
1.562     albertel 9330: 
1.306     albertel 9331: =cut
                   9332: 
                   9333: sub start_page {
1.309     albertel 9334:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9335:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9336: 
1.315     albertel 9337:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 9338:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9339: 
1.338     albertel 9340:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  9341:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9342:     }
1.1075.2.161.  .1(raebu 9343:21): 
                   9344:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   9345:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9346:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9347:21):                 $args->{'no_primary_menu'} = 1;
                   9348:21):             }
                   9349:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9350:21):                 $args->{'no_inline_menu'} = 1;
                   9351:21):             }
                   9352:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9353:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9354:21):             }
                   9355:21):         } else {
                   9356:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9357:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9358:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9359:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9360:21):                     $args->{'no_primary_menu'} = 1;
                   9361:21):                 }
                   9362:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9363:21):                     $args->{'no_inline_menu'} = 1;
                   9364:21):                 }
                   9365:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9366:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9367:21):                 }
                   9368:21):             }
                   9369:21):         }
                   9370:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9371:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9372:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   9373:21):     } elsif ($env{'request.course.id'}) {
                   9374:21):         my $expiretime=600;
                   9375:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9376:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9377:21):         }
                   9378:21):         my ($deeplinkmenu,$menuref);
                   9379:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9380:21):         if ($menucoll) {
                   9381:21):             if (ref($menuref) eq 'HASH') {
                   9382:21):                 %menu = %{$menuref};
                   9383:21):             }
                   9384:21):             if ($menu{'top'} eq 'n') {
                   9385:21):                 $args->{'no_primary_menu'} = 1;
                   9386:21):             }
                   9387:21):             if ($menu{'inline'} eq 'n') {
                   9388:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   9389:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9390:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9391:21):                     my $crstype = &course_type();
                   9392:21):                     my $now = time;
                   9393:21):                     my $ccrole;
                   9394:21):                     if ($crstype eq 'Community') {
                   9395:21):                         $ccrole = 'co';
                   9396:21):                     } else {
                   9397:21):                         $ccrole = 'cc';
                   9398:21):                     }
                   9399:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9400:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9401:21):                         if ((($start) && ($start<0)) ||
                   9402:21):                             (($end) && ($end<$now))  ||
                   9403:21):                             (($start) && ($now<$start))) {
                   9404:21):                             $args->{'no_inline_menu'} = 1;
                   9405:21):                         }
                   9406:21):                     } else {
                   9407:21):                         $args->{'no_inline_menu'} = 1;
                   9408:21):                     }
                   9409:21):                 }
                   9410:21):             }
                   9411:21):         }
                   9412:21):     }
          .4(raebu 9413:22): 
          .8(raebu 9414:22):     my $showncrumbs;
1.338     albertel 9415:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9416: 	if ($args->{'frameset'}) {
                   9417: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9418: 						$args->{'add_entries'});
                   9419: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9420:         } else {
                   9421:             $result .=
                   9422:                 &bodytag($title, 
                   9423:                          $args->{'function'},       $args->{'add_entries'},
                   9424:                          $args->{'only_body'},      $args->{'domain'},
                   9425:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  9426:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 9427:21):                          $args,                     \@advtools,
          .8(raebu 9428:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   9429:         }
1.330     albertel 9430:     }
1.338     albertel 9431: 
1.315     albertel 9432:     if ($args->{'js_ready'}) {
1.713     kaisler  9433: 		$result = &js_ready($result);
1.315     albertel 9434:     }
1.320     albertel 9435:     if ($args->{'html_encode'}) {
1.713     kaisler  9436: 		$result = &html_encode($result);
                   9437:     }
                   9438: 
1.813     bisitz   9439:     # Preparation for new and consistent functionlist at top of screen
                   9440:     # if ($args->{'functionlist'}) {
                   9441:     #            $result .= &build_functionlist();
                   9442:     #}
                   9443: 
1.964     droeschl 9444:     # Don't add anything more if only_body wanted or in const space
                   9445:     return $result if    $args->{'only_body'} 
                   9446:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9447: 
                   9448:     #Breadcrumbs
1.758     kaisler  9449:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 9450:22):         unless ($showncrumbs) {
1.758     kaisler  9451: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9452: 		#if any br links exists, add them to the breadcrumbs
                   9453: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9454: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9455: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9456: 			}
                   9457: 		}
1.1075.2.19  raeburn  9458:                 # if @advtools array contains items add then to the breadcrumbs
                   9459:                 if (@advtools > 0) {
                   9460:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9461:                 }
1.1075.2.123  raeburn  9462:                 my $menulink;
                   9463:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 9464:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   9465:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  9466:                     $menulink = 0;
                   9467:                 } else {
                   9468:                     undef($menulink);
                   9469:                 }
1.1075.2.161.  .8(raebu 9470:22):                 my $linkprotout;
                   9471:22):                 if ($env{'request.deeplink.login'}) {
                   9472:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9473:22):                     if ($linkprotout) {
                   9474:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9475:22):                     }
                   9476:22):                 }
1.758     kaisler  9477: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9478: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  9479: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 9480:21): 		} else {
1.1075.2.123  raeburn  9481: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9482: 		}
1.1075.2.161.  .8(raebu 9483:22):         }
1.1075.2.24  raeburn  9484:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9485:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9486:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9487:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9488:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9489:     }
1.315     albertel 9490:     return $result;
1.306     albertel 9491: }
                   9492: 
                   9493: sub end_page {
1.315     albertel 9494:     my ($args) = @_;
                   9495:     $env{'internal.end_page'}++;
1.330     albertel 9496:     my $result;
1.335     albertel 9497:     if ($args->{'discussion'}) {
                   9498: 	my ($target,$parser);
                   9499: 	if (ref($args->{'discussion'})) {
                   9500: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9501: 				$args->{'discussion'}{'parser'});
                   9502: 	}
                   9503: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9504:     }
1.330     albertel 9505:     if ($args->{'frameset'}) {
                   9506: 	$result .= '</frameset>';
                   9507:     } else {
1.635     raeburn  9508: 	$result .= &endbodytag($args);
1.330     albertel 9509:     }
1.1075.2.6  raeburn  9510:     unless ($args->{'notbody'}) {
                   9511:         $result .= "\n</html>";
                   9512:     }
1.330     albertel 9513: 
1.315     albertel 9514:     if ($args->{'js_ready'}) {
1.317     albertel 9515: 	$result = &js_ready($result);
1.315     albertel 9516:     }
1.335     albertel 9517: 
1.320     albertel 9518:     if ($args->{'html_encode'}) {
                   9519: 	$result = &html_encode($result);
                   9520:     }
1.335     albertel 9521: 
1.315     albertel 9522:     return $result;
                   9523: }
                   9524: 
1.1075.2.161.  .1(raebu 9525:21): sub menucoll_in_effect {
                   9526:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9527:21):     if ($env{'request.course.id'}) {
                   9528:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9529:21):         if ($env{'request.deeplink.login'}) {
                   9530:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9531:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9532:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9533:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9534:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9535:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9536:21):                     if (ref($navmap)) {
                   9537:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9538:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9539:21):                                                           '0.deeplink');
                   9540:21):                     } else {
                   9541:21):                         $check_login_symb = 1;
                   9542:21):                     }
                   9543:21):                 } else {
                   9544:21):                     my $symb=&Apache::lonnet::symbread();
                   9545:21):                     if ($symb) {
                   9546:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9547:21):                     } else {
                   9548:21):                         $check_login_symb = 1;
                   9549:21):                     }
                   9550:21):                 }
                   9551:21):             } else {
                   9552:21):                 $check_login_symb = 1;
                   9553:21):             }
                   9554:21):             if ($check_login_symb) {
                   9555:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9556:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9557:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9558:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9559:21):                     if (ref($navmap)) {
                   9560:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9561:21):                     }
                   9562:21):                 } else {
                   9563:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9564:21):                 }
                   9565:21):             }
                   9566:21):             if ($deeplink ne '') {
          .6(raebu 9567:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9568:21):                 if ($display =~ /^\d+$/) {
                   9569:21):                     $deeplinkmenu = 1;
                   9570:21):                     $menucoll = $display;
                   9571:21):                 }
                   9572:21):             }
                   9573:21):         }
                   9574:21):         if ($menucoll) {
                   9575:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9576:21):         }
                   9577:21):     }
                   9578:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9579:21): }
                   9580:21): 
                   9581:21): sub deeplink_login_symb {
                   9582:21):     my ($cnum,$cdom) = @_;
                   9583:21):     my $login_symb;
                   9584:21):     if ($env{'request.deeplink.login'}) {
                   9585:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9586:21):     }
                   9587:21):     return $login_symb;
                   9588:21): }
                   9589:21): 
                   9590:21): sub symb_from_tinyurl {
                   9591:21):     my ($url,$cnum,$cdom) = @_;
                   9592:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9593:21):         my $key = $1;
                   9594:21):         my ($tinyurl,$login);
                   9595:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9596:21):         if (defined($cached)) {
                   9597:21):             $tinyurl = $result;
                   9598:21):         } else {
                   9599:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9600:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9601:21):             if ($currtiny{$key} ne '') {
                   9602:21):                 $tinyurl = $currtiny{$key};
                   9603:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9604:21):             }
                   9605:21):         }
                   9606:21):         if ($tinyurl ne '') {
                   9607:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9608:21):             if (wantarray) {
                   9609:21):                 return ($cnumreq,$symb);
                   9610:21):             } elsif ($cnumreq eq $cnum) {
                   9611:21):                 return $symb;
                   9612:21):             }
                   9613:21):         }
                   9614:21):     }
                   9615:21):     if (wantarray) {
                   9616:21):         return ();
                   9617:21):     } else {
                   9618:21):         return;
                   9619:21):     }
                   9620:21): }
                   9621:21): 
          .17(raeb 9622:-23): sub usable_exttools {
                   9623:-23):     my %tooltypes;
                   9624:-23):     if ($env{'request.course.id'}) {
                   9625:-23):         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9626:-23):            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9627:-23):                %tooltypes = (
                   9628:-23):                              crs => 1,
                   9629:-23):                              dom => 1,
                   9630:-23):                             );
                   9631:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9632:-23):                $tooltypes{'crs'} = 1;
                   9633:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9634:-23):                $tooltypes{'dom'} = 1;
                   9635:-23):            }
                   9636:-23):         } else {
                   9637:-23):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9638:-23):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9639:-23):             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9640:-23):             if ($crstype eq '') {
                   9641:-23):                 $crstype = 'course';
                   9642:-23):             }
                   9643:-23):             if ($crstype eq 'course') {
                   9644:-23):                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9645:-23):                     $crstype = 'official';
                   9646:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9647:-23):                     $crstype = 'textbook';
                   9648:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9649:-23):                     $crstype = 'lti';
                   9650:-23):                 } else {
                   9651:-23):                     $crstype = 'unofficial';
                   9652:-23):                 }
                   9653:-23):             }
                   9654:-23):             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9655:-23):             if ($domdefaults{$crstype.'domexttool'}) {
                   9656:-23):                 $tooltypes{'dom'} = 1;
                   9657:-23):             }
                   9658:-23):             if ($domdefaults{$crstype.'exttool'}) {
                   9659:-23):                 $tooltypes{'crs'} = 1;
                   9660:-23):             }
                   9661:-23):         }
                   9662:-23):     }
                   9663:-23):     return %tooltypes;
                   9664:-23): }
                   9665:-23): 
1.1034    www      9666: sub wishlist_window {
                   9667:     return(<<'ENDWISHLIST');
1.1046    raeburn  9668: <script type="text/javascript">
1.1034    www      9669: // <![CDATA[
                   9670: // <!-- BEGIN LON-CAPA Internal
                   9671: function set_wishlistlink(title, path) {
                   9672:     if (!title) {
                   9673:         title = document.title;
                   9674:         title = title.replace(/^LON-CAPA /,'');
                   9675:     }
1.1075.2.65  raeburn  9676:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9677:     title = title.replace("'","\\\'");
1.1034    www      9678:     if (!path) {
                   9679:         path = location.pathname;
                   9680:     }
1.1075.2.65  raeburn  9681:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9682:     path = path.replace("'","\\\'");
1.1034    www      9683:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9684:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9685: }
                   9686: // END LON-CAPA Internal -->
                   9687: // ]]>
                   9688: </script>
                   9689: ENDWISHLIST
                   9690: }
                   9691: 
1.1030    www      9692: sub modal_window {
                   9693:     return(<<'ENDMODAL');
1.1046    raeburn  9694: <script type="text/javascript">
1.1030    www      9695: // <![CDATA[
                   9696: // <!-- BEGIN LON-CAPA Internal
                   9697: var modalWindow = {
                   9698: 	parent:"body",
                   9699: 	windowId:null,
                   9700: 	content:null,
                   9701: 	width:null,
                   9702: 	height:null,
                   9703: 	close:function()
                   9704: 	{
                   9705: 	        $(".LCmodal-window").remove();
                   9706: 	        $(".LCmodal-overlay").remove();
                   9707: 	},
                   9708: 	open:function()
                   9709: 	{
                   9710: 		var modal = "";
                   9711: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9712: 		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;\">";
                   9713: 		modal += this.content;
                   9714: 		modal += "</div>";	
                   9715: 
                   9716: 		$(this.parent).append(modal);
                   9717: 
                   9718: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9719: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9720: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9721: 	}
                   9722: };
1.1075.2.42  raeburn  9723: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9724: 	{
1.1075.2.119  raeburn  9725:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9726: 		modalWindow.windowId = "myModal";
                   9727: 		modalWindow.width = width;
                   9728: 		modalWindow.height = height;
1.1075.2.80  raeburn  9729: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9730: 		modalWindow.open();
1.1075.2.87  raeburn  9731: 	};
1.1030    www      9732: // END LON-CAPA Internal -->
                   9733: // ]]>
                   9734: </script>
                   9735: ENDMODAL
                   9736: }
                   9737: 
                   9738: sub modal_link {
1.1075.2.42  raeburn  9739:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9740:     unless ($width) { $width=480; }
                   9741:     unless ($height) { $height=400; }
1.1031    www      9742:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9743:     unless ($transparency) { $transparency='true'; }
                   9744: 
1.1074    raeburn  9745:     my $target_attr;
                   9746:     if (defined($target)) {
                   9747:         $target_attr = 'target="'.$target.'"';
                   9748:     }
                   9749:     return <<"ENDLINK";
1.1075.2.143  raeburn  9750: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9751: ENDLINK
1.1030    www      9752: }
                   9753: 
1.1032    www      9754: sub modal_adhoc_script {
1.1075.2.155  raeburn  9755:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9756:     my $mathjax;
                   9757:     if ($possmathjax) {
                   9758:         $mathjax = <<'ENDJAX';
                   9759:                if (typeof MathJax == 'object') {
                   9760:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9761:                }
                   9762: ENDJAX
                   9763:     }
1.1032    www      9764:     return (<<ENDADHOC);
1.1046    raeburn  9765: <script type="text/javascript">
1.1032    www      9766: // <![CDATA[
                   9767:         var $funcname = function()
                   9768:         {
                   9769:                 modalWindow.windowId = "myModal";
                   9770:                 modalWindow.width = $width;
                   9771:                 modalWindow.height = $height;
                   9772:                 modalWindow.content = '$content';
                   9773:                 modalWindow.open();
1.1075.2.155  raeburn  9774:                 $mathjax
1.1032    www      9775:         };  
                   9776: // ]]>
                   9777: </script>
                   9778: ENDADHOC
                   9779: }
                   9780: 
1.1041    www      9781: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9782:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9783:     my $innerwidth=$width-20;
                   9784:     $content=&js_ready(
1.1042    www      9785:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9786:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9787:                  $content.
1.1041    www      9788:                  &end_scrollbox().
1.1075.2.42  raeburn  9789:                  &end_page()
1.1041    www      9790:              );
1.1075.2.155  raeburn  9791:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9792: }
                   9793: 
                   9794: sub modal_adhoc_window {
1.1075.2.155  raeburn  9795:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9796:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9797:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9798: }
                   9799: 
                   9800: sub modal_adhoc_launch {
                   9801:     my ($funcname,$width,$height,$content)=@_;
                   9802:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9803: <script type="text/javascript">
                   9804: // <![CDATA[
                   9805: $funcname();
                   9806: // ]]>
                   9807: </script>
                   9808: ENDLAUNCH
                   9809: }
                   9810: 
                   9811: sub modal_adhoc_close {
                   9812:     return (<<ENDCLOSE);
                   9813: <script type="text/javascript">
                   9814: // <![CDATA[
                   9815: modalWindow.close();
                   9816: // ]]>
                   9817: </script>
                   9818: ENDCLOSE
                   9819: }
                   9820: 
1.1038    www      9821: sub togglebox_script {
                   9822:    return(<<ENDTOGGLE);
                   9823: <script type="text/javascript"> 
                   9824: // <![CDATA[
                   9825: function LCtoggleDisplay(id,hidetext,showtext) {
                   9826:    link = document.getElementById(id + "link").childNodes[0];
                   9827:    with (document.getElementById(id).style) {
                   9828:       if (display == "none" ) {
                   9829:           display = "inline";
                   9830:           link.nodeValue = hidetext;
                   9831:         } else {
                   9832:           display = "none";
                   9833:           link.nodeValue = showtext;
                   9834:        }
                   9835:    }
                   9836: }
                   9837: // ]]>
                   9838: </script>
                   9839: ENDTOGGLE
                   9840: }
                   9841: 
1.1039    www      9842: sub start_togglebox {
                   9843:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9844:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9845:     unless ($showtext) { $showtext=&mt('show'); }
                   9846:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9847:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9848:     return &start_data_table().
                   9849:            &start_data_table_header_row().
                   9850:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9851:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9852:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9853:            &end_data_table_header_row().
                   9854:            '<tr id="'.$id.'" style="display:none""><td>';
                   9855: }
                   9856: 
                   9857: sub end_togglebox {
                   9858:     return '</td></tr>'.&end_data_table();
                   9859: }
                   9860: 
1.1041    www      9861: sub LCprogressbar_script {
1.1075.2.130  raeburn  9862:    my ($id,$number_to_do)=@_;
                   9863:    if ($number_to_do) {
                   9864:        return(<<ENDPROGRESS);
1.1041    www      9865: <script type="text/javascript">
                   9866: // <![CDATA[
1.1045    www      9867: \$('#progressbar$id').progressbar({
1.1041    www      9868:   value: 0,
                   9869:   change: function(event, ui) {
                   9870:     var newVal = \$(this).progressbar('option', 'value');
                   9871:     \$('.pblabel', this).text(LCprogressTxt);
                   9872:   }
                   9873: });
                   9874: // ]]>
                   9875: </script>
                   9876: ENDPROGRESS
1.1075.2.130  raeburn  9877:    } else {
                   9878:        return(<<ENDPROGRESS);
                   9879: <script type="text/javascript">
                   9880: // <![CDATA[
                   9881: \$('#progressbar$id').progressbar({
                   9882:   value: false,
                   9883:   create: function(event, ui) {
                   9884:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9885:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9886:   }
                   9887: });
                   9888: // ]]>
                   9889: </script>
                   9890: ENDPROGRESS
                   9891:    }
1.1041    www      9892: }
                   9893: 
                   9894: sub LCprogressbarUpdate_script {
                   9895:    return(<<ENDPROGRESSUPDATE);
                   9896: <style type="text/css">
                   9897: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9898: .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      9899: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9900: </style>
                   9901: <script type="text/javascript">
                   9902: // <![CDATA[
1.1045    www      9903: var LCprogressTxt='---';
                   9904: 
1.1075.2.130  raeburn  9905: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9906:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9907:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9908:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9909:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9910:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9911:    } else {
                   9912:        \$('#progressbar'+id).progressbar('value',percent);
                   9913:    }
1.1041    www      9914: }
                   9915: // ]]>
                   9916: </script>
                   9917: ENDPROGRESSUPDATE
                   9918: }
                   9919: 
1.1042    www      9920: my $LClastpercent;
1.1045    www      9921: my $LCidcnt;
                   9922: my $LCcurrentid;
1.1042    www      9923: 
1.1041    www      9924: sub LCprogressbar {
1.1075.2.130  raeburn  9925:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9926:     $LClastpercent=0;
1.1045    www      9927:     $LCidcnt++;
                   9928:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9929:     my ($starting,$content);
                   9930:     if ($number_to_do) {
                   9931:         $starting=&mt('Starting');
                   9932:         $content=(<<ENDPROGBAR);
                   9933: $preamble
1.1045    www      9934:   <div id="progressbar$LCcurrentid">
1.1041    www      9935:     <span class="pblabel">$starting</span>
                   9936:   </div>
                   9937: ENDPROGBAR
1.1075.2.130  raeburn  9938:     } else {
                   9939:         $starting=&mt('Loading...');
                   9940:         $LClastpercent='false';
                   9941:         $content=(<<ENDPROGBAR);
                   9942: $preamble
                   9943:   <div id="progressbar$LCcurrentid">
                   9944:       <div class="progress-label">$starting</div>
                   9945:   </div>
                   9946: ENDPROGBAR
                   9947:     }
                   9948:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9949: }
                   9950: 
                   9951: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9952:     my ($r,$val,$text,$number_to_do)=@_;
                   9953:     if ($number_to_do) {
                   9954:         unless ($val) { 
                   9955:             if ($LClastpercent) {
                   9956:                 $val=$LClastpercent;
                   9957:             } else {
                   9958:                 $val=0;
                   9959:             }
                   9960:         }
                   9961:         if ($val<0) { $val=0; }
                   9962:         if ($val>100) { $val=0; }
                   9963:         $LClastpercent=$val;
                   9964:         unless ($text) { $text=$val.'%'; }
                   9965:     } else {
                   9966:         $val = 'false';
1.1042    www      9967:     }
1.1041    www      9968:     $text=&js_ready($text);
1.1044    www      9969:     &r_print($r,<<ENDUPDATE);
1.1041    www      9970: <script type="text/javascript">
                   9971: // <![CDATA[
1.1075.2.130  raeburn  9972: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9973: // ]]>
                   9974: </script>
                   9975: ENDUPDATE
1.1035    www      9976: }
                   9977: 
1.1042    www      9978: sub LCprogressbarClose {
                   9979:     my ($r)=@_;
                   9980:     $LClastpercent=0;
1.1044    www      9981:     &r_print($r,<<ENDCLOSE);
1.1042    www      9982: <script type="text/javascript">
                   9983: // <![CDATA[
1.1045    www      9984: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9985: // ]]>
                   9986: </script>
                   9987: ENDCLOSE
1.1044    www      9988: }
                   9989: 
                   9990: sub r_print {
                   9991:     my ($r,$to_print)=@_;
                   9992:     if ($r) {
                   9993:       $r->print($to_print);
                   9994:       $r->rflush();
                   9995:     } else {
                   9996:       print($to_print);
                   9997:     }
1.1042    www      9998: }
                   9999: 
1.320     albertel 10000: sub html_encode {
                   10001:     my ($result) = @_;
                   10002: 
1.322     albertel 10003:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10004:     
                   10005:     return $result;
                   10006: }
1.1044    www      10007: 
1.317     albertel 10008: sub js_ready {
                   10009:     my ($result) = @_;
                   10010: 
1.323     albertel 10011:     $result =~ s/[\n\r]/ /xmsg;
                   10012:     $result =~ s/\\/\\\\/xmsg;
                   10013:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10014:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10015:     
                   10016:     return $result;
                   10017: }
                   10018: 
1.315     albertel 10019: sub validate_page {
                   10020:     if (  exists($env{'internal.start_page'})
1.316     albertel 10021: 	  &&     $env{'internal.start_page'} > 1) {
                   10022: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10023: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10024: 				 $ENV{'request.filename'});
1.315     albertel 10025:     }
                   10026:     if (  exists($env{'internal.end_page'})
1.316     albertel 10027: 	  &&     $env{'internal.end_page'} > 1) {
                   10028: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10029: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10030: 				 $env{'request.filename'});
1.315     albertel 10031:     }
                   10032:     if (     exists($env{'internal.start_page'})
                   10033: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10034: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10035: 				 $env{'request.filename'});
1.315     albertel 10036:     }
                   10037:     if (   ! exists($env{'internal.start_page'})
                   10038: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10039: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10040: 				 $env{'request.filename'});
1.315     albertel 10041:     }
1.306     albertel 10042: }
1.315     albertel 10043: 
1.996     www      10044: 
                   10045: sub start_scrollbox {
1.1075.2.56  raeburn  10046:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10047:     unless ($outerwidth) { $outerwidth='520px'; }
                   10048:     unless ($width) { $width='500px'; }
                   10049:     unless ($height) { $height='200px'; }
1.1075    raeburn  10050:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10051:     if ($id ne '') {
1.1075.2.42  raeburn  10052:         $table_id = ' id="table_'.$id.'"';
                   10053:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10054:     }
1.1075    raeburn  10055:     if ($bgcolor ne '') {
                   10056:         $tdcol = "background-color: $bgcolor;";
                   10057:     }
1.1075.2.42  raeburn  10058:     my $nicescroll_js;
                   10059:     if ($env{'browser.mobile'}) {
                   10060:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10061:     }
1.1075    raeburn  10062:     return <<"END";
1.1075.2.42  raeburn  10063: $nicescroll_js
                   10064: 
                   10065: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  10066: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  10067: END
1.996     www      10068: }
                   10069: 
                   10070: sub end_scrollbox {
1.1036    www      10071:     return '</div></td></tr></table>';
1.996     www      10072: }
                   10073: 
1.1075.2.42  raeburn  10074: sub nicescroll_javascript {
                   10075:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10076:     my %options;
                   10077:     if (ref($cursor) eq 'HASH') {
                   10078:         %options = %{$cursor};
                   10079:     }
                   10080:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10081:         $options{'railalign'} = 'left';
                   10082:     }
                   10083:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10084:         my $function  = &get_users_function();
                   10085:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   10086:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10087:             $options{'cursorcolor'} = '#00F';
                   10088:         }
                   10089:     }
                   10090:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10091:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   10092:             $options{'cursoropacity'}='1.0';
                   10093:         }
                   10094:     } else {
                   10095:         $options{'cursoropacity'}='1.0';
                   10096:     }
                   10097:     if ($options{'cursorfixedheight'} eq 'none') {
                   10098:         delete($options{'cursorfixedheight'});
                   10099:     } else {
                   10100:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10101:     }
                   10102:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10103:         delete($options{'railoffset'});
                   10104:     }
                   10105:     my @niceoptions;
                   10106:     while (my($key,$value) = each(%options)) {
                   10107:         if ($value =~ /^\{.+\}$/) {
                   10108:             push(@niceoptions,$key.':'.$value);
                   10109:         } else {
                   10110:             push(@niceoptions,$key.':"'.$value.'"');
                   10111:         }
                   10112:     }
                   10113:     my $nicescroll_js = '
                   10114: $(document).ready(
                   10115:       function() {
                   10116:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10117:       }
                   10118: );
                   10119: ';
                   10120:     if ($framecheck) {
                   10121:         $nicescroll_js .= '
                   10122: function expand_div(caller) {
                   10123:     if (top === self) {
                   10124:         document.getElementById("'.$id.'").style.width = "auto";
                   10125:         document.getElementById("'.$id.'").style.height = "auto";
                   10126:     } else {
                   10127:         try {
                   10128:             if (parent.frames) {
                   10129:                 if (parent.frames.length > 1) {
                   10130:                     var framesrc = parent.frames[1].location.href;
                   10131:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10132:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10133:                         document.getElementById("'.$id.'").style.width = "auto";
                   10134:                         document.getElementById("'.$id.'").style.height = "auto";
                   10135:                     }
                   10136:                 }
                   10137:             }
                   10138:         } catch (e) {
                   10139:             return;
                   10140:         }
                   10141:     }
                   10142:     return;
                   10143: }
                   10144: ';
                   10145:     }
                   10146:     if ($needjsready) {
                   10147:         $nicescroll_js = '
                   10148: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10149:     } else {
                   10150:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10151:     }
                   10152:     return $nicescroll_js;
                   10153: }
                   10154: 
1.318     albertel 10155: sub simple_error_page {
1.1075.2.49  raeburn  10156:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 10157:22):     my %displayargs;
1.1075.2.49  raeburn  10158:     if (ref($args) eq 'HASH') {
                   10159:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 10160:22):         if ($args->{'only_body'}) {
                   10161:22):             $displayargs{'only_body'} = 1;
                   10162:22):         }
                   10163:22):         if ($args->{'no_nav_bar'}) {
                   10164:22):             $displayargs{'no_nav_bar'} = 1;
                   10165:22):         }
1.1075.2.49  raeburn  10166:     } else {
                   10167:         $msg = &mt($msg);
                   10168:     }
                   10169: 
1.318     albertel 10170:     my $page =
1.1075.2.161.  .4(raebu 10171:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  10172: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10173: 	&Apache::loncommon::end_page();
                   10174:     if (ref($r)) {
                   10175: 	$r->print($page);
1.327     albertel 10176: 	return;
1.318     albertel 10177:     }
                   10178:     return $page;
                   10179: }
1.347     albertel 10180: 
                   10181: {
1.610     albertel 10182:     my @row_count;
1.961     onken    10183: 
                   10184:     sub start_data_table_count {
                   10185:         unshift(@row_count, 0);
                   10186:         return;
                   10187:     }
                   10188: 
                   10189:     sub end_data_table_count {
                   10190:         shift(@row_count);
                   10191:         return;
                   10192:     }
                   10193: 
1.347     albertel 10194:     sub start_data_table {
1.1018    raeburn  10195: 	my ($add_class,$id) = @_;
1.422     albertel 10196: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10197:         my $table_id;
                   10198:         if (defined($id)) {
                   10199:             $table_id = ' id="'.$id.'"';
                   10200:         }
1.961     onken    10201: 	&start_data_table_count();
1.1018    raeburn  10202: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10203:     }
                   10204: 
                   10205:     sub end_data_table {
1.961     onken    10206: 	&end_data_table_count();
1.389     albertel 10207: 	return '</table>'."\n";;
1.347     albertel 10208:     }
                   10209: 
                   10210:     sub start_data_table_row {
1.974     wenzelju 10211: 	my ($add_class, $id) = @_;
1.610     albertel 10212: 	$row_count[0]++;
                   10213: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10214: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10215:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10216:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10217:     }
1.471     banghart 10218:     
                   10219:     sub continue_data_table_row {
1.974     wenzelju 10220: 	my ($add_class, $id) = @_;
1.610     albertel 10221: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10222: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10223:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10224:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10225:     }
1.347     albertel 10226: 
                   10227:     sub end_data_table_row {
1.389     albertel 10228: 	return '</tr>'."\n";;
1.347     albertel 10229:     }
1.367     www      10230: 
1.421     albertel 10231:     sub start_data_table_empty_row {
1.707     bisitz   10232: #	$row_count[0]++;
1.421     albertel 10233: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10234:     }
                   10235: 
                   10236:     sub end_data_table_empty_row {
                   10237: 	return '</tr>'."\n";;
                   10238:     }
                   10239: 
1.367     www      10240:     sub start_data_table_header_row {
1.389     albertel 10241: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10242:     }
                   10243: 
                   10244:     sub end_data_table_header_row {
1.389     albertel 10245: 	return '</tr>'."\n";;
1.367     www      10246:     }
1.890     droeschl 10247: 
                   10248:     sub data_table_caption {
                   10249:         my $caption = shift;
                   10250:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10251:     }
1.347     albertel 10252: }
                   10253: 
1.548     albertel 10254: =pod
                   10255: 
                   10256: =item * &inhibit_menu_check($arg)
                   10257: 
                   10258: Checks for a inhibitmenu state and generates output to preserve it
                   10259: 
                   10260: Inputs:         $arg - can be any of
                   10261:                      - undef - in which case the return value is a string 
                   10262:                                to add  into arguments list of a uri
                   10263:                      - 'input' - in which case the return value is a HTML
                   10264:                                  <form> <input> field of type hidden to
                   10265:                                  preserve the value
                   10266:                      - a url - in which case the return value is the url with
                   10267:                                the neccesary cgi args added to preserve the
                   10268:                                inhibitmenu state
                   10269:                      - a ref to a url - no return value, but the string is
                   10270:                                         updated to include the neccessary cgi
                   10271:                                         args to preserve the inhibitmenu state
                   10272: 
                   10273: =cut
                   10274: 
                   10275: sub inhibit_menu_check {
                   10276:     my ($arg) = @_;
                   10277:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10278:     if ($arg eq 'input') {
                   10279: 	if ($env{'form.inhibitmenu'}) {
                   10280: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10281: 	} else {
                   10282: 	    return
                   10283: 	}
                   10284:     }
                   10285:     if ($env{'form.inhibitmenu'}) {
                   10286: 	if (ref($arg)) {
                   10287: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10288: 	} elsif ($arg eq '') {
                   10289: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10290: 	} else {
                   10291: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10292: 	}
                   10293:     }
                   10294:     if (!ref($arg)) {
                   10295: 	return $arg;
                   10296:     }
                   10297: }
                   10298: 
1.251     albertel 10299: ###############################################
1.182     matthew  10300: 
                   10301: =pod
                   10302: 
1.549     albertel 10303: =back
                   10304: 
                   10305: =head1 User Information Routines
                   10306: 
                   10307: =over 4
                   10308: 
1.405     albertel 10309: =item * &get_users_function()
1.182     matthew  10310: 
                   10311: Used by &bodytag to determine the current users primary role.
                   10312: Returns either 'student','coordinator','admin', or 'author'.
                   10313: 
                   10314: =cut
                   10315: 
                   10316: ###############################################
                   10317: sub get_users_function {
1.815     tempelho 10318:     my $function = 'norole';
1.818     tempelho 10319:     if ($env{'request.role'}=~/^(st)/) {
                   10320:         $function='student';
                   10321:     }
1.907     raeburn  10322:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10323:         $function='coordinator';
                   10324:     }
1.258     albertel 10325:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10326:         $function='admin';
                   10327:     }
1.826     bisitz   10328:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10329:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10330:         $function='author';
                   10331:     }
                   10332:     return $function;
1.54      www      10333: }
1.99      www      10334: 
                   10335: ###############################################
                   10336: 
1.233     raeburn  10337: =pod
                   10338: 
1.821     raeburn  10339: =item * &show_course()
                   10340: 
                   10341: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10342: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10343: 
                   10344: Inputs:
                   10345: None
                   10346: 
                   10347: Outputs:
                   10348: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10349: 
                   10350: =cut
                   10351: 
                   10352: ###############################################
                   10353: sub show_course {
                   10354:     my $course = !$env{'user.adv'};
                   10355:     if (!$env{'user.adv'}) {
                   10356:         foreach my $env (keys(%env)) {
                   10357:             next if ($env !~ m/^user\.priv\./);
                   10358:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10359:                 $course = 0;
                   10360:                 last;
                   10361:             }
                   10362:         }
                   10363:     }
                   10364:     return $course;
                   10365: }
                   10366: 
                   10367: ###############################################
                   10368: 
                   10369: =pod
                   10370: 
1.542     raeburn  10371: =item * &check_user_status()
1.274     raeburn  10372: 
                   10373: Determines current status of supplied role for a
                   10374: specific user. Roles can be active, previous or future.
                   10375: 
                   10376: Inputs: 
                   10377: user's domain, user's username, course's domain,
1.375     raeburn  10378: course's number, optional section ID.
1.274     raeburn  10379: 
                   10380: Outputs:
                   10381: role status: active, previous or future. 
                   10382: 
                   10383: =cut
                   10384: 
                   10385: sub check_user_status {
1.412     raeburn  10386:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10387:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  10388:     my @uroles = keys(%userinfo);
1.274     raeburn  10389:     my $srchstr;
                   10390:     my $active_chk = 'none';
1.412     raeburn  10391:     my $now = time;
1.274     raeburn  10392:     if (@uroles > 0) {
1.908     raeburn  10393:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10394:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10395:         } else {
1.412     raeburn  10396:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10397:         }
                   10398:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10399:             my $role_end = 0;
                   10400:             my $role_start = 0;
                   10401:             $active_chk = 'active';
1.412     raeburn  10402:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10403:                 $role_end = $1;
                   10404:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10405:                     $role_start = $1;
1.274     raeburn  10406:                 }
                   10407:             }
                   10408:             if ($role_start > 0) {
1.412     raeburn  10409:                 if ($now < $role_start) {
1.274     raeburn  10410:                     $active_chk = 'future';
                   10411:                 }
                   10412:             }
                   10413:             if ($role_end > 0) {
1.412     raeburn  10414:                 if ($now > $role_end) {
1.274     raeburn  10415:                     $active_chk = 'previous';
                   10416:                 }
                   10417:             }
                   10418:         }
                   10419:     }
                   10420:     return $active_chk;
                   10421: }
                   10422: 
                   10423: ###############################################
                   10424: 
                   10425: =pod
                   10426: 
1.405     albertel 10427: =item * &get_sections()
1.233     raeburn  10428: 
                   10429: Determines all the sections for a course including
                   10430: sections with students and sections containing other roles.
1.419     raeburn  10431: Incoming parameters: 
                   10432: 
                   10433: 1. domain
                   10434: 2. course number 
                   10435: 3. reference to array containing roles for which sections should 
                   10436: be gathered (optional).
                   10437: 4. reference to array containing status types for which sections 
                   10438: should be gathered (optional).
                   10439: 
                   10440: If the third argument is undefined, sections are gathered for any role. 
                   10441: If the fourth argument is undefined, sections are gathered for any status.
                   10442: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10443:  
1.374     raeburn  10444: Returns section hash (keys are section IDs, values are
                   10445: number of users in each section), subject to the
1.419     raeburn  10446: optional roles filter, optional status filter 
1.233     raeburn  10447: 
                   10448: =cut
                   10449: 
                   10450: ###############################################
                   10451: sub get_sections {
1.419     raeburn  10452:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10453:     if (!defined($cdom) || !defined($cnum)) {
                   10454:         my $cid =  $env{'request.course.id'};
                   10455: 
                   10456: 	return if (!defined($cid));
                   10457: 
                   10458:         $cdom = $env{'course.'.$cid.'.domain'};
                   10459:         $cnum = $env{'course.'.$cid.'.num'};
                   10460:     }
                   10461: 
                   10462:     my %sectioncount;
1.419     raeburn  10463:     my $now = time;
1.240     albertel 10464: 
1.1075.2.33  raeburn  10465:     my $check_students = 1;
                   10466:     my $only_students = 0;
                   10467:     if (ref($possible_roles) eq 'ARRAY') {
                   10468:         if (grep(/^st$/,@{$possible_roles})) {
                   10469:             if (@{$possible_roles} == 1) {
                   10470:                 $only_students = 1;
                   10471:             }
                   10472:         } else {
                   10473:             $check_students = 0;
                   10474:         }
                   10475:     }
                   10476: 
                   10477:     if ($check_students) {
1.276     albertel 10478: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10479: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10480: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10481:         my $start_index = &Apache::loncoursedata::CL_START();
                   10482:         my $end_index = &Apache::loncoursedata::CL_END();
                   10483:         my $status;
1.366     albertel 10484: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10485: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10486: 				                     $data->[$status_index],
                   10487:                                                      $data->[$start_index],
                   10488:                                                      $data->[$end_index]);
                   10489:             if ($stu_status eq 'Active') {
                   10490:                 $status = 'active';
                   10491:             } elsif ($end < $now) {
                   10492:                 $status = 'previous';
                   10493:             } elsif ($start > $now) {
                   10494:                 $status = 'future';
                   10495:             } 
                   10496: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10497:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10498:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10499: 		    $sectioncount{$section}++;
                   10500:                 }
1.240     albertel 10501: 	    }
                   10502: 	}
                   10503:     }
1.1075.2.33  raeburn  10504:     if ($only_students) {
                   10505:         return %sectioncount;
                   10506:     }
1.240     albertel 10507:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10508:     foreach my $user (sort(keys(%courseroles))) {
                   10509: 	if ($user !~ /^(\w{2})/) { next; }
                   10510: 	my ($role) = ($user =~ /^(\w{2})/);
                   10511: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10512: 	my ($section,$status);
1.240     albertel 10513: 	if ($role eq 'cr' &&
                   10514: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10515: 	    $section=$1;
                   10516: 	}
                   10517: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10518: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10519:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10520:         if ($end == -1 && $start == -1) {
                   10521:             next; #deleted role
                   10522:         }
                   10523:         if (!defined($possible_status)) { 
                   10524:             $sectioncount{$section}++;
                   10525:         } else {
                   10526:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10527:                 $status = 'active';
                   10528:             } elsif ($end < $now) {
                   10529:                 $status = 'future';
                   10530:             } elsif ($start > $now) {
                   10531:                 $status = 'previous';
                   10532:             }
                   10533:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10534:                 $sectioncount{$section}++;
                   10535:             }
                   10536:         }
1.233     raeburn  10537:     }
1.366     albertel 10538:     return %sectioncount;
1.233     raeburn  10539: }
                   10540: 
1.274     raeburn  10541: ###############################################
1.294     raeburn  10542: 
                   10543: =pod
1.405     albertel 10544: 
                   10545: =item * &get_course_users()
                   10546: 
1.275     raeburn  10547: Retrieves usernames:domains for users in the specified course
                   10548: with specific role(s), and access status. 
                   10549: 
                   10550: Incoming parameters:
1.277     albertel 10551: 1. course domain
                   10552: 2. course number
                   10553: 3. access status: users must have - either active, 
1.275     raeburn  10554: previous, future, or all.
1.277     albertel 10555: 4. reference to array of permissible roles
1.288     raeburn  10556: 5. reference to array of section restrictions (optional)
                   10557: 6. reference to results object (hash of hashes).
                   10558: 7. reference to optional userdata hash
1.609     raeburn  10559: 8. reference to optional statushash
1.630     raeburn  10560: 9. flag if privileged users (except those set to unhide in
                   10561:    course settings) should be excluded    
1.609     raeburn  10562: Keys of top level results hash are roles.
1.275     raeburn  10563: Keys of inner hashes are username:domain, with 
                   10564: values set to access type.
1.288     raeburn  10565: Optional userdata hash returns an array with arguments in the 
                   10566: same order as loncoursedata::get_classlist() for student data.
                   10567: 
1.609     raeburn  10568: Optional statushash returns
                   10569: 
1.288     raeburn  10570: Entries for end, start, section and status are blank because
                   10571: of the possibility of multiple values for non-student roles.
                   10572: 
1.275     raeburn  10573: =cut
1.405     albertel 10574: 
1.275     raeburn  10575: ###############################################
1.405     albertel 10576: 
1.275     raeburn  10577: sub get_course_users {
1.630     raeburn  10578:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10579:     my %idx = ();
1.419     raeburn  10580:     my %seclists;
1.288     raeburn  10581: 
                   10582:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10583:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10584:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10585:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10586:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10587:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10588:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10589:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10590: 
1.290     albertel 10591:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10592:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10593:         my $now = time;
1.277     albertel 10594:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10595:             my $match = 0;
1.412     raeburn  10596:             my $secmatch = 0;
1.419     raeburn  10597:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10598:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10599:             if ($section eq '') {
                   10600:                 $section = 'none';
                   10601:             }
1.291     albertel 10602:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10603:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10604:                     $secmatch = 1;
                   10605:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10606:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10607:                         $secmatch = 1;
                   10608:                     }
                   10609:                 } else {  
1.419     raeburn  10610: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10611: 		        $secmatch = 1;
                   10612:                     }
1.290     albertel 10613: 		}
1.412     raeburn  10614:                 if (!$secmatch) {
                   10615:                     next;
                   10616:                 }
1.419     raeburn  10617:             }
1.275     raeburn  10618:             if (defined($$types{'active'})) {
1.288     raeburn  10619:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10620:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10621:                     $match = 1;
1.275     raeburn  10622:                 }
                   10623:             }
                   10624:             if (defined($$types{'previous'})) {
1.609     raeburn  10625:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10626:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10627:                     $match = 1;
1.275     raeburn  10628:                 }
                   10629:             }
                   10630:             if (defined($$types{'future'})) {
1.609     raeburn  10631:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10632:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10633:                     $match = 1;
1.275     raeburn  10634:                 }
                   10635:             }
1.609     raeburn  10636:             if ($match) {
                   10637:                 push(@{$seclists{$student}},$section);
                   10638:                 if (ref($userdata) eq 'HASH') {
                   10639:                     $$userdata{$student} = $$classlist{$student};
                   10640:                 }
                   10641:                 if (ref($statushash) eq 'HASH') {
                   10642:                     $statushash->{$student}{'st'}{$section} = $status;
                   10643:                 }
1.288     raeburn  10644:             }
1.275     raeburn  10645:         }
                   10646:     }
1.412     raeburn  10647:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10648:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10649:         my $now = time;
1.609     raeburn  10650:         my %displaystatus = ( previous => 'Expired',
                   10651:                               active   => 'Active',
                   10652:                               future   => 'Future',
                   10653:                             );
1.1075.2.36  raeburn  10654:         my (%nothide,@possdoms);
1.630     raeburn  10655:         if ($hidepriv) {
                   10656:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10657:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10658:                 if ($user !~ /:/) {
                   10659:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10660:                 } else {
                   10661:                     $nothide{$user} = 1;
                   10662:                 }
                   10663:             }
1.1075.2.36  raeburn  10664:             my @possdoms = ($cdom);
                   10665:             if ($coursehash{'checkforpriv'}) {
                   10666:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10667:             }
1.630     raeburn  10668:         }
1.439     raeburn  10669:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10670:             my $match = 0;
1.412     raeburn  10671:             my $secmatch = 0;
1.439     raeburn  10672:             my $status;
1.412     raeburn  10673:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10674:             $user =~ s/:$//;
1.439     raeburn  10675:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10676:             if ($end == -1 || $start == -1) {
                   10677:                 next;
                   10678:             }
                   10679:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10680:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10681:                 my ($uname,$udom) = split(/:/,$user);
                   10682:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10683:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10684:                         $secmatch = 1;
                   10685:                     } elsif ($usec eq '') {
1.420     albertel 10686:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10687:                             $secmatch = 1;
                   10688:                         }
                   10689:                     } else {
                   10690:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10691:                             $secmatch = 1;
                   10692:                         }
                   10693:                     }
                   10694:                     if (!$secmatch) {
                   10695:                         next;
                   10696:                     }
1.288     raeburn  10697:                 }
1.419     raeburn  10698:                 if ($usec eq '') {
                   10699:                     $usec = 'none';
                   10700:                 }
1.275     raeburn  10701:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10702:                     if ($hidepriv) {
1.1075.2.36  raeburn  10703:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10704:                             (!$nothide{$uname.':'.$udom})) {
                   10705:                             next;
                   10706:                         }
                   10707:                     }
1.503     raeburn  10708:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10709:                         $status = 'previous';
                   10710:                     } elsif ($start > $now) {
                   10711:                         $status = 'future';
                   10712:                     } else {
                   10713:                         $status = 'active';
                   10714:                     }
1.277     albertel 10715:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10716:                         if ($status eq $type) {
1.420     albertel 10717:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10718:                                 push(@{$$users{$role}{$user}},$type);
                   10719:                             }
1.288     raeburn  10720:                             $match = 1;
                   10721:                         }
                   10722:                     }
1.419     raeburn  10723:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10724:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10725: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10726:                         }
1.420     albertel 10727:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10728:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10729:                         }
1.609     raeburn  10730:                         if (ref($statushash) eq 'HASH') {
                   10731:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10732:                         }
1.275     raeburn  10733:                     }
                   10734:                 }
                   10735:             }
                   10736:         }
1.290     albertel 10737:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10738:             if ((defined($cdom)) && (defined($cnum))) {
                   10739:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10740:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10741:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10742:                     next if ($owner eq '');
                   10743:                     my ($ownername,$ownerdom);
                   10744:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10745:                         $ownername = $1;
                   10746:                         $ownerdom = $2;
                   10747:                     } else {
                   10748:                         $ownername = $owner;
                   10749:                         $ownerdom = $cdom;
                   10750:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10751:                     }
                   10752:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10753:                     if (defined($userdata) && 
1.609     raeburn  10754: 			!exists($$userdata{$owner})) {
                   10755: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10756:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10757:                             push(@{$seclists{$owner}},'none');
                   10758:                         }
                   10759:                         if (ref($statushash) eq 'HASH') {
                   10760:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10761:                         }
1.290     albertel 10762: 		    }
1.279     raeburn  10763:                 }
                   10764:             }
                   10765:         }
1.419     raeburn  10766:         foreach my $user (keys(%seclists)) {
                   10767:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10768:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10769:         }
1.275     raeburn  10770:     }
                   10771:     return;
                   10772: }
                   10773: 
1.288     raeburn  10774: sub get_user_info {
                   10775:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10776:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10777: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10778:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10779:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10780:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10781:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10782:     return;
                   10783: }
1.275     raeburn  10784: 
1.472     raeburn  10785: ###############################################
                   10786: 
                   10787: =pod
                   10788: 
                   10789: =item * &get_user_quota()
                   10790: 
1.1075.2.41  raeburn  10791: Retrieves quota assigned for storage of user files.
                   10792: Default is to report quota for portfolio files.
1.472     raeburn  10793: 
                   10794: Incoming parameters:
                   10795: 1. user's username
                   10796: 2. user's domain
1.1075.2.41  raeburn  10797: 3. quota name - portfolio, author, or course
                   10798:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10799: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10800:    course
1.472     raeburn  10801: 
                   10802: Returns:
1.1075.2.58  raeburn  10803: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10804: 2. (Optional) Type of setting: custom or default
                   10805:    (individually assigned or default for user's 
                   10806:    institutional status).
                   10807: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10808:    or student - types as defined in localenroll::inst_usertypes 
                   10809:    for user's domain, which determines default quota for user.
                   10810: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10811: 
                   10812: If a value has been stored in the user's environment, 
1.536     raeburn  10813: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10814: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10815: 
                   10816: =cut
                   10817: 
                   10818: ###############################################
                   10819: 
                   10820: 
                   10821: sub get_user_quota {
1.1075.2.42  raeburn  10822:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10823:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10824:     if (!defined($udom)) {
                   10825:         $udom = $env{'user.domain'};
                   10826:     }
                   10827:     if (!defined($uname)) {
                   10828:         $uname = $env{'user.name'};
                   10829:     }
                   10830:     if (($udom eq '' || $uname eq '') ||
                   10831:         ($udom eq 'public') && ($uname eq 'public')) {
                   10832:         $quota = 0;
1.536     raeburn  10833:         $quotatype = 'default';
                   10834:         $defquota = 0; 
1.472     raeburn  10835:     } else {
1.536     raeburn  10836:         my $inststatus;
1.1075.2.41  raeburn  10837:         if ($quotaname eq 'course') {
                   10838:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10839:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10840:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10841:             } else {
                   10842:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10843:                 $quota = $cenv{'internal.uploadquota'};
                   10844:             }
1.536     raeburn  10845:         } else {
1.1075.2.41  raeburn  10846:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10847:                 if ($quotaname eq 'author') {
                   10848:                     $quota = $env{'environment.authorquota'};
                   10849:                 } else {
                   10850:                     $quota = $env{'environment.portfolioquota'};
                   10851:                 }
                   10852:                 $inststatus = $env{'environment.inststatus'};
                   10853:             } else {
                   10854:                 my %userenv = 
                   10855:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10856:                                          'authorquota','inststatus'],$udom,$uname);
                   10857:                 my ($tmp) = keys(%userenv);
                   10858:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10859:                     if ($quotaname eq 'author') {
                   10860:                         $quota = $userenv{'authorquota'};
                   10861:                     } else {
                   10862:                         $quota = $userenv{'portfolioquota'};
                   10863:                     }
                   10864:                     $inststatus = $userenv{'inststatus'};
                   10865:                 } else {
                   10866:                     undef(%userenv);
                   10867:                 }
                   10868:             }
                   10869:         }
                   10870:         if ($quota eq '' || wantarray) {
                   10871:             if ($quotaname eq 'course') {
                   10872:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10873:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10874:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10875:                     $defquota = $domdefs{$crstype.'quota'};
                   10876:                 }
                   10877:                 if ($defquota eq '') {
                   10878:                     $defquota = 500;
                   10879:                 }
1.1075.2.41  raeburn  10880:             } else {
                   10881:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10882:             }
                   10883:             if ($quota eq '') {
                   10884:                 $quota = $defquota;
                   10885:                 $quotatype = 'default';
                   10886:             } else {
                   10887:                 $quotatype = 'custom';
                   10888:             }
1.472     raeburn  10889:         }
                   10890:     }
1.536     raeburn  10891:     if (wantarray) {
                   10892:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10893:     } else {
                   10894:         return $quota;
                   10895:     }
1.472     raeburn  10896: }
                   10897: 
                   10898: ###############################################
                   10899: 
                   10900: =pod
                   10901: 
                   10902: =item * &default_quota()
                   10903: 
1.536     raeburn  10904: Retrieves default quota assigned for storage of user portfolio files,
                   10905: given an (optional) user's institutional status.
1.472     raeburn  10906: 
                   10907: Incoming parameters:
1.1075.2.42  raeburn  10908: 
1.472     raeburn  10909: 1. domain
1.536     raeburn  10910: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10911:    status types (e.g., faculty, staff, student etc.)
                   10912:    which apply to the user for whom the default is being retrieved.
                   10913:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10914:    default quota will be returned.
                   10915: 3.  quota name - portfolio, author, or course
                   10916:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10917: 
                   10918: Returns:
1.1075.2.42  raeburn  10919: 
1.1075.2.58  raeburn  10920: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10921: 2. (Optional) institutional type which determined the value of the
                   10922:    default quota.
1.472     raeburn  10923: 
                   10924: If a value has been stored in the domain's configuration db,
                   10925: it will return that, otherwise it returns 20 (for backwards 
                   10926: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10927: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10928: 
1.536     raeburn  10929: If the user's status includes multiple types (e.g., staff and student),
                   10930: the largest default quota which applies to the user determines the
                   10931: default quota returned.
                   10932: 
1.472     raeburn  10933: =cut
                   10934: 
                   10935: ###############################################
                   10936: 
                   10937: 
                   10938: sub default_quota {
1.1075.2.41  raeburn  10939:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10940:     my ($defquota,$settingstatus);
                   10941:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10942:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10943:     my $key = 'defaultquota';
                   10944:     if ($quotaname eq 'author') {
                   10945:         $key = 'authorquota';
                   10946:     }
1.622     raeburn  10947:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10948:         if ($inststatus ne '') {
1.765     raeburn  10949:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10950:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10951:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10952:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10953:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10954:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10955:                             $settingstatus = $item;
1.1075.2.41  raeburn  10956:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10957:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10958:                             $settingstatus = $item;
                   10959:                         }
                   10960:                     }
1.1075.2.41  raeburn  10961:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10962:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10963:                         if ($defquota eq '') {
                   10964:                             $defquota = $quotahash{'quotas'}{$item};
                   10965:                             $settingstatus = $item;
                   10966:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10967:                             $defquota = $quotahash{'quotas'}{$item};
                   10968:                             $settingstatus = $item;
                   10969:                         }
1.536     raeburn  10970:                     }
                   10971:                 }
                   10972:             }
                   10973:         }
                   10974:         if ($defquota eq '') {
1.1075.2.41  raeburn  10975:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10976:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10977:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10978:                 $defquota = $quotahash{'quotas'}{'default'};
                   10979:             }
1.536     raeburn  10980:             $settingstatus = 'default';
1.1075.2.42  raeburn  10981:             if ($defquota eq '') {
                   10982:                 if ($quotaname eq 'author') {
                   10983:                     $defquota = 500;
                   10984:                 }
                   10985:             }
1.536     raeburn  10986:         }
                   10987:     } else {
                   10988:         $settingstatus = 'default';
1.1075.2.41  raeburn  10989:         if ($quotaname eq 'author') {
                   10990:             $defquota = 500;
                   10991:         } else {
                   10992:             $defquota = 20;
                   10993:         }
1.536     raeburn  10994:     }
                   10995:     if (wantarray) {
                   10996:         return ($defquota,$settingstatus);
1.472     raeburn  10997:     } else {
1.536     raeburn  10998:         return $defquota;
1.472     raeburn  10999:     }
                   11000: }
                   11001: 
1.1075.2.41  raeburn  11002: ###############################################
                   11003: 
                   11004: =pod
                   11005: 
1.1075.2.42  raeburn  11006: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  11007: 
                   11008: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  11009: of existing file within authoring space will cause quota for the authoring
                   11010: space to be exceeded.
                   11011: 
                   11012: Same, if upload of a file directly to a course/community via Course Editor
                   11013: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  11014: 
1.1075.2.61  raeburn  11015: Inputs: 7 
1.1075.2.42  raeburn  11016: 1. username or coursenum
1.1075.2.41  raeburn  11017: 2. domain
1.1075.2.42  raeburn  11018: 3. context ('author' or 'course')
1.1075.2.41  raeburn  11019: 4. filename of file for which action is being requested
                   11020: 5. filesize (kB) of file
                   11021: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  11022: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  11023: 
                   11024: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   11025:          otherwise return null.
                   11026: 
1.1075.2.42  raeburn  11027: =back
                   11028: 
1.1075.2.41  raeburn  11029: =cut
                   11030: 
1.1075.2.42  raeburn  11031: sub excess_filesize_warning {
1.1075.2.59  raeburn  11032:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  11033:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  11034:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  11035:     if ($context eq 'author') {
                   11036:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11037:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11038:     } else {
                   11039:         foreach my $subdir ('docs','supplemental') {
                   11040:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11041:         }
                   11042:     }
1.1075.2.41  raeburn  11043:     $disk_quota = int($disk_quota * 1000);
                   11044:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  11045:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  11046:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  11047:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11048:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  11049:                             $disk_quota,$current_disk_usage).
                   11050:                '</p>';
                   11051:     }
                   11052:     return;
                   11053: }
                   11054: 
                   11055: ###############################################
                   11056: 
                   11057: 
1.384     raeburn  11058: sub get_secgrprole_info {
                   11059:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11060:     my %sections_count = &get_sections($cdom,$cnum);
                   11061:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11062:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11063:     my @groups = sort(keys(%curr_groups));
                   11064:     my $allroles = [];
                   11065:     my $rolehash;
                   11066:     my $accesshash = {
                   11067:                      active => 'Currently has access',
                   11068:                      future => 'Will have future access',
                   11069:                      previous => 'Previously had access',
                   11070:                   };
                   11071:     if ($needroles) {
                   11072:         $rolehash = {'all' => 'all'};
1.385     albertel 11073:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11074: 	if (&Apache::lonnet::error(%user_roles)) {
                   11075: 	    undef(%user_roles);
                   11076: 	}
                   11077:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11078:             my ($role)=split(/\:/,$item,2);
                   11079:             if ($role eq 'cr') { next; }
                   11080:             if ($role =~ /^cr/) {
                   11081:                 $$rolehash{$role} = (split('/',$role))[3];
                   11082:             } else {
                   11083:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11084:             }
                   11085:         }
                   11086:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11087:             push(@{$allroles},$key);
                   11088:         }
                   11089:         push (@{$allroles},'st');
                   11090:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11091:     }
                   11092:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11093: }
                   11094: 
1.555     raeburn  11095: sub user_picker {
1.1075.2.127  raeburn  11096:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11097:     my $currdom = $dom;
1.1075.2.114  raeburn  11098:     my @alldoms = &Apache::lonnet::all_domains();
                   11099:     if (@alldoms == 1) {
                   11100:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11101:                                                ['directorysrch'],$alldoms[0]);
                   11102:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11103:         my $showdom = $domdesc;
                   11104:         if ($showdom eq '') {
                   11105:             $showdom = $dom;
                   11106:         }
                   11107:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11108:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11109:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11110:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11111:             }
                   11112:         }
                   11113:     }
1.555     raeburn  11114:     my %curr_selected = (
                   11115:                         srchin => 'dom',
1.580     raeburn  11116:                         srchby => 'lastname',
1.555     raeburn  11117:                       );
                   11118:     my $srchterm;
1.625     raeburn  11119:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11120:         if ($srch->{'srchby'} ne '') {
                   11121:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11122:         }
                   11123:         if ($srch->{'srchin'} ne '') {
                   11124:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11125:         }
                   11126:         if ($srch->{'srchtype'} ne '') {
                   11127:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11128:         }
                   11129:         if ($srch->{'srchdomain'} ne '') {
                   11130:             $currdom = $srch->{'srchdomain'};
                   11131:         }
                   11132:         $srchterm = $srch->{'srchterm'};
                   11133:     }
1.1075.2.98  raeburn  11134:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11135:                     'usr'       => 'Search criteria',
1.563     raeburn  11136:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11137:                     'uname'     => 'username',
                   11138:                     'lastname'  => 'last name',
1.555     raeburn  11139:                     'lastfirst' => 'last name, first name',
1.558     albertel 11140:                     'crs'       => 'in this course',
1.576     raeburn  11141:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11142:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11143:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11144:                     'exact'     => 'is',
                   11145:                     'contains'  => 'contains',
1.569     raeburn  11146:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  11147:                                        );
                   11148:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11149:                     'youm'      => "You must include some text to search for.",
                   11150:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11151:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11152:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11153:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11154:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11155:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11156:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11157:                                        );
1.1075.2.98  raeburn  11158:     &html_escape(\%html_lt);
                   11159:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  11160:     my $domform;
1.1075.2.126  raeburn  11161:     my $allow_blank = 1;
1.1075.2.115  raeburn  11162:     if ($fixeddom) {
1.1075.2.126  raeburn  11163:         $allow_blank = 0;
                   11164:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  11165:     } else {
1.1075.2.126  raeburn  11166:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  11167:     }
1.563     raeburn  11168:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11169: 
                   11170:     my @srchins = ('crs','dom','alc','instd');
                   11171: 
                   11172:     foreach my $option (@srchins) {
                   11173:         # FIXME 'alc' option unavailable until 
                   11174:         #       loncreateuser::print_user_query_page()
                   11175:         #       has been completed.
                   11176:         next if ($option eq 'alc');
1.880     raeburn  11177:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11178:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  11179:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11180:         if ($curr_selected{'srchin'} eq $option) {
                   11181:             $srchinsel .= ' 
1.1075.2.98  raeburn  11182:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11183:         } else {
                   11184:             $srchinsel .= '
1.1075.2.98  raeburn  11185:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11186:         }
1.555     raeburn  11187:     }
1.563     raeburn  11188:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11189: 
                   11190:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11191:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11192:         if ($curr_selected{'srchby'} eq $option) {
                   11193:             $srchbysel .= '
1.1075.2.98  raeburn  11194:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11195:         } else {
                   11196:             $srchbysel .= '
1.1075.2.98  raeburn  11197:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11198:          }
                   11199:     }
                   11200:     $srchbysel .= "\n  </select>\n";
                   11201: 
                   11202:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11203:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11204:         if ($curr_selected{'srchtype'} eq $option) {
                   11205:             $srchtypesel .= '
1.1075.2.98  raeburn  11206:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11207:         } else {
                   11208:             $srchtypesel .= '
1.1075.2.98  raeburn  11209:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11210:         }
                   11211:     }
                   11212:     $srchtypesel .= "\n  </select>\n";
                   11213: 
1.558     albertel 11214:     my ($newuserscript,$new_user_create);
1.994     raeburn  11215:     my $context_dom = $env{'request.role.domain'};
                   11216:     if ($context eq 'requestcrs') {
                   11217:         if ($env{'form.coursedom'} ne '') { 
                   11218:             $context_dom = $env{'form.coursedom'};
                   11219:         }
                   11220:     }
1.556     raeburn  11221:     if ($forcenewuser) {
1.576     raeburn  11222:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11223:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11224:                 if ($cancreate) {
                   11225:                     $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>';
                   11226:                 } else {
1.799     bisitz   11227:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11228:                     my %usertypetext = (
                   11229:                         official   => 'institutional',
                   11230:                         unofficial => 'non-institutional',
                   11231:                     );
1.799     bisitz   11232:                     $new_user_create = '<p class="LC_warning">'
                   11233:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11234:                                       .' '
                   11235:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11236:                                           ,'<a href="'.$helplink.'">','</a>')
                   11237:                                       .'</p><br />';
1.627     raeburn  11238:                 }
1.576     raeburn  11239:             }
                   11240:         }
                   11241: 
1.556     raeburn  11242:         $newuserscript = <<"ENDSCRIPT";
                   11243: 
1.570     raeburn  11244: function setSearch(createnew,callingForm) {
1.556     raeburn  11245:     if (createnew == 1) {
1.570     raeburn  11246:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11247:             if (callingForm.srchby.options[i].value == 'uname') {
                   11248:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11249:             }
                   11250:         }
1.570     raeburn  11251:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11252:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11253: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11254:             }
                   11255:         }
1.570     raeburn  11256:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11257:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11258:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11259:             }
                   11260:         }
1.570     raeburn  11261:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11262:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11263:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11264:             }
                   11265:         }
                   11266:     }
                   11267: }
                   11268: ENDSCRIPT
1.558     albertel 11269: 
1.556     raeburn  11270:     }
                   11271: 
1.555     raeburn  11272:     my $output = <<"END_BLOCK";
1.556     raeburn  11273: <script type="text/javascript">
1.824     bisitz   11274: // <![CDATA[
1.570     raeburn  11275: function validateEntry(callingForm) {
1.558     albertel 11276: 
1.556     raeburn  11277:     var checkok = 1;
1.558     albertel 11278:     var srchin;
1.570     raeburn  11279:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11280: 	if ( callingForm.srchin[i].checked ) {
                   11281: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11282: 	}
                   11283:     }
                   11284: 
1.570     raeburn  11285:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11286:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11287:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11288:     var srchterm =  callingForm.srchterm.value;
                   11289:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11290:     var msg = "";
                   11291: 
                   11292:     if (srchterm == "") {
                   11293:         checkok = 0;
1.1075.2.98  raeburn  11294:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11295:     }
                   11296: 
1.569     raeburn  11297:     if (srchtype== 'begins') {
                   11298:         if (srchterm.length < 2) {
                   11299:             checkok = 0;
1.1075.2.98  raeburn  11300:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11301:         }
                   11302:     }
                   11303: 
1.556     raeburn  11304:     if (srchtype== 'contains') {
                   11305:         if (srchterm.length < 3) {
                   11306:             checkok = 0;
1.1075.2.98  raeburn  11307:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11308:         }
                   11309:     }
                   11310:     if (srchin == 'instd') {
                   11311:         if (srchdomain == '') {
                   11312:             checkok = 0;
1.1075.2.98  raeburn  11313:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11314:         }
                   11315:     }
                   11316:     if (srchin == 'dom') {
                   11317:         if (srchdomain == '') {
                   11318:             checkok = 0;
1.1075.2.98  raeburn  11319:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11320:         }
                   11321:     }
                   11322:     if (srchby == 'lastfirst') {
                   11323:         if (srchterm.indexOf(",") == -1) {
                   11324:             checkok = 0;
1.1075.2.98  raeburn  11325:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11326:         }
                   11327:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11328:             checkok = 0;
1.1075.2.98  raeburn  11329:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11330:         }
                   11331:     }
                   11332:     if (checkok == 0) {
1.1075.2.98  raeburn  11333:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11334:         return;
                   11335:     }
                   11336:     if (checkok == 1) {
1.570     raeburn  11337:         callingForm.submit();
1.556     raeburn  11338:     }
                   11339: }
                   11340: 
                   11341: $newuserscript
                   11342: 
1.824     bisitz   11343: // ]]>
1.556     raeburn  11344: </script>
1.558     albertel 11345: 
                   11346: $new_user_create
                   11347: 
1.555     raeburn  11348: END_BLOCK
1.558     albertel 11349: 
1.876     raeburn  11350:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  11351:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11352:                $domform.
                   11353:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  11354:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11355:                $srchbysel.
                   11356:                $srchtypesel. 
                   11357:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11358:                $srchinsel.
                   11359:                &Apache::lonhtmlcommon::row_closure(1). 
                   11360:                &Apache::lonhtmlcommon::end_pick_box().
                   11361:                '<br />';
1.1075.2.114  raeburn  11362:     return ($output,1);
1.555     raeburn  11363: }
                   11364: 
1.612     raeburn  11365: sub user_rule_check {
1.615     raeburn  11366:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  11367:     my ($response,%inst_response);
1.612     raeburn  11368:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  11369:         if (keys(%{$usershash}) > 1) {
                   11370:             my (%by_username,%by_id,%userdoms);
                   11371:             my $checkid;
1.612     raeburn  11372:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  11373:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11374:                     $checkid = 1;
                   11375:                 }
                   11376:             }
                   11377:             foreach my $user (keys(%{$usershash})) {
                   11378:                 my ($uname,$udom) = split(/:/,$user);
                   11379:                 if ($checkid) {
                   11380:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11381:                         if ($usershash->{$user}->{'id'} ne '') {
                   11382:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   11383:                             $userdoms{$udom} = 1;
                   11384:                             if (ref($inst_results) eq 'HASH') {
                   11385:                                 $inst_results->{$uname.':'.$udom} = {};
                   11386:                             }
                   11387:                         }
                   11388:                     }
                   11389:                 } else {
                   11390:                     $by_username{$udom}{$uname} = 1;
                   11391:                     $userdoms{$udom} = 1;
                   11392:                     if (ref($inst_results) eq 'HASH') {
                   11393:                         $inst_results->{$uname.':'.$udom} = {};
                   11394:                     }
                   11395:                 }
                   11396:             }
                   11397:             foreach my $udom (keys(%userdoms)) {
                   11398:                 if (!$got_rules->{$udom}) {
                   11399:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11400:                                                              ['usercreation'],$udom);
                   11401:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11402:                         foreach my $item ('username','id') {
                   11403:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11404:                                 $$curr_rules{$udom}{$item} =
                   11405:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   11406:                             }
                   11407:                         }
                   11408:                     }
                   11409:                     $got_rules->{$udom} = 1;
                   11410:                 }
                   11411:             }
                   11412:             if ($checkid) {
                   11413:                 foreach my $udom (keys(%by_id)) {
                   11414:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11415:                     if ($outcome eq 'ok') {
                   11416:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11417:                             my $uname = $by_id{$udom}{$id};
                   11418:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11419:                         }
                   11420:                         if (ref($results) eq 'HASH') {
                   11421:                             foreach my $uname (keys(%{$results})) {
                   11422:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11423:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11424:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11425:                                 }
                   11426:                             }
                   11427:                         }
                   11428:                     }
1.612     raeburn  11429:                 }
1.615     raeburn  11430:             } else {
1.1075.2.99  raeburn  11431:                 foreach my $udom (keys(%by_username)) {
                   11432:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11433:                     if ($outcome eq 'ok') {
                   11434:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11435:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11436:                         }
                   11437:                         if (ref($results) eq 'HASH') {
                   11438:                             foreach my $uname (keys(%{$results})) {
                   11439:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11440:                             }
                   11441:                         }
                   11442:                     }
                   11443:                 }
1.612     raeburn  11444:             }
1.1075.2.99  raeburn  11445:         } elsif (keys(%{$usershash}) == 1) {
                   11446:             my $user = (keys(%{$usershash}))[0];
                   11447:             my ($uname,$udom) = split(/:/,$user);
                   11448:             if (($udom ne '') && ($uname ne '')) {
                   11449:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11450:                     if (ref($checks) eq 'HASH') {
                   11451:                         if (defined($checks->{'username'})) {
                   11452:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   11453:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11454:                         } elsif (defined($checks->{'id'})) {
                   11455:                             if ($usershash->{$user}->{'id'} ne '') {
                   11456:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11457:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11458:                                                                   $usershash->{$user}->{'id'});
                   11459:                             } else {
                   11460:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11461:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11462:                             }
                   11463:                         }
                   11464:                     } else {
                   11465:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11466:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11467:                        return;
                   11468:                     }
                   11469:                     if (!$got_rules->{$udom}) {
                   11470:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11471:                                                                  ['usercreation'],$udom);
                   11472:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11473:                             foreach my $item ('username','id') {
                   11474:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11475:                                    $$curr_rules{$udom}{$item} =
                   11476:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11477:                                 }
                   11478:                             }
1.585     raeburn  11479:                         }
1.1075.2.99  raeburn  11480:                         $got_rules->{$udom} = 1;
1.585     raeburn  11481:                     }
                   11482:                 }
1.1075.2.99  raeburn  11483:             } else {
                   11484:                 return;
                   11485:             }
                   11486:         } else {
                   11487:             return;
                   11488:         }
                   11489:         foreach my $user (keys(%{$usershash})) {
                   11490:             my ($uname,$udom) = split(/:/,$user);
                   11491:             next if (($udom eq '') || ($uname eq ''));
                   11492:             my $id;
                   11493:             if (ref($inst_results) eq 'HASH') {
                   11494:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11495:                     $id = $inst_results->{$user}->{'id'};
                   11496:                 }
                   11497:             }
                   11498:             if ($id eq '') {
                   11499:                 if (ref($usershash->{$user})) {
                   11500:                     $id = $usershash->{$user}->{'id'};
                   11501:                 }
1.585     raeburn  11502:             }
1.612     raeburn  11503:             foreach my $item (keys(%{$checks})) {
                   11504:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11505:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11506:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  11507:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11508:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11509:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11510:                                 if ($rule_check{$rule}) {
                   11511:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  11512:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11513:                                         if (ref($inst_results) eq 'HASH') {
                   11514:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11515:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11516:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  11517:                                                 } elsif ($item eq 'id') {
                   11518:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11519:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11520:                                                     }
1.615     raeburn  11521:                                                 }
1.612     raeburn  11522:                                             }
                   11523:                                         }
1.615     raeburn  11524:                                     }
                   11525:                                     last;
1.585     raeburn  11526:                                 }
                   11527:                             }
                   11528:                         }
                   11529:                     }
                   11530:                 }
                   11531:             }
                   11532:         }
                   11533:     }
1.612     raeburn  11534:     return;
                   11535: }
                   11536: 
                   11537: sub user_rule_formats {
                   11538:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11539:     my %text = ( 
                   11540:                  'username' => 'Usernames',
                   11541:                  'id'       => 'IDs',
                   11542:                );
                   11543:     my $output;
                   11544:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11545:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11546:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11547:             $output = '<br />'.
                   11548:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11549:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11550:                       ' <ul>';
1.612     raeburn  11551:             foreach my $rule (@{$ruleorder}) {
                   11552:                 if (ref($curr_rules) eq 'ARRAY') {
                   11553:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11554:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11555:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11556:                                         $rules->{$rule}{'desc'}.'</li>';
                   11557:                         }
                   11558:                     }
                   11559:                 }
                   11560:             }
                   11561:             $output .= '</ul>';
                   11562:         }
                   11563:     }
                   11564:     return $output;
                   11565: }
                   11566: 
                   11567: sub instrule_disallow_msg {
1.615     raeburn  11568:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11569:     my $response;
                   11570:     my %text = (
                   11571:                   item   => 'username',
                   11572:                   items  => 'usernames',
                   11573:                   match  => 'matches',
                   11574:                   do     => 'does',
                   11575:                   action => 'a username',
                   11576:                   one    => 'one',
                   11577:                );
                   11578:     if ($count > 1) {
                   11579:         $text{'item'} = 'usernames';
                   11580:         $text{'match'} ='match';
                   11581:         $text{'do'} = 'do';
                   11582:         $text{'action'} = 'usernames',
                   11583:         $text{'one'} = 'ones';
                   11584:     }
                   11585:     if ($checkitem eq 'id') {
                   11586:         $text{'items'} = 'IDs';
                   11587:         $text{'item'} = 'ID';
                   11588:         $text{'action'} = 'an ID';
1.615     raeburn  11589:         if ($count > 1) {
                   11590:             $text{'item'} = 'IDs';
                   11591:             $text{'action'} = 'IDs';
                   11592:         }
1.612     raeburn  11593:     }
1.674     bisitz   11594:     $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  11595:     if ($mode eq 'upload') {
                   11596:         if ($checkitem eq 'username') {
                   11597:             $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'}.");
                   11598:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11599:             $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  11600:         }
1.669     raeburn  11601:     } elsif ($mode eq 'selfcreate') {
                   11602:         if ($checkitem eq 'id') {
                   11603:             $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.");
                   11604:         }
1.615     raeburn  11605:     } else {
                   11606:         if ($checkitem eq 'username') {
                   11607:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11608:         } elsif ($checkitem eq 'id') {
                   11609:             $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.");
                   11610:         }
1.612     raeburn  11611:     }
                   11612:     return $response;
1.585     raeburn  11613: }
                   11614: 
1.624     raeburn  11615: sub personal_data_fieldtitles {
                   11616:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11617:                         id => 'Student/Employee ID',
                   11618:                         permanentemail => 'E-mail address',
                   11619:                         lastname => 'Last Name',
                   11620:                         firstname => 'First Name',
                   11621:                         middlename => 'Middle Name',
                   11622:                         generation => 'Generation',
                   11623:                         gen => 'Generation',
1.765     raeburn  11624:                         inststatus => 'Affiliation',
1.624     raeburn  11625:                    );
                   11626:     return %fieldtitles;
                   11627: }
                   11628: 
1.642     raeburn  11629: sub sorted_inst_types {
                   11630:     my ($dom) = @_;
1.1075.2.70  raeburn  11631:     my ($usertypes,$order);
                   11632:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11633:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11634:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11635:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11636:     } else {
                   11637:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11638:     }
1.642     raeburn  11639:     my $othertitle = &mt('All users');
                   11640:     if ($env{'request.course.id'}) {
1.668     raeburn  11641:         $othertitle  = &mt('Any users');
1.642     raeburn  11642:     }
                   11643:     my @types;
                   11644:     if (ref($order) eq 'ARRAY') {
                   11645:         @types = @{$order};
                   11646:     }
                   11647:     if (@types == 0) {
                   11648:         if (ref($usertypes) eq 'HASH') {
                   11649:             @types = sort(keys(%{$usertypes}));
                   11650:         }
                   11651:     }
                   11652:     if (keys(%{$usertypes}) > 0) {
                   11653:         $othertitle = &mt('Other users');
                   11654:     }
                   11655:     return ($othertitle,$usertypes,\@types);
                   11656: }
                   11657: 
1.645     raeburn  11658: sub get_institutional_codes {
1.1075.2.157  raeburn  11659:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11660: # Get complete list of course sections to update
                   11661:     my @currsections = ();
                   11662:     my @currxlists = ();
1.1075.2.157  raeburn  11663:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11664:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11665:     my $crskey = $crs.':'.$coursecode;
                   11666:     @{$unclutteredsec{$crskey}} = ();
                   11667:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11668: 
                   11669:     if ($$settings{'internal.sectionnums'} ne '') {
                   11670:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11671:     }
                   11672: 
                   11673:     if ($$settings{'internal.crosslistings'} ne '') {
                   11674:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11675:     }
                   11676: 
                   11677:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11678:         foreach my $xl (@currxlists) {
                   11679:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11680:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11681:                     push(@{$allcourses},$1);
1.645     raeburn  11682:                     $$LC_code{$1} = $2;
                   11683:                 }
                   11684:             }
                   11685:         }
                   11686:     }
1.1075.2.157  raeburn  11687: 
1.645     raeburn  11688:     if (@currsections > 0) {
1.1075.2.157  raeburn  11689:         foreach my $sec (@currsections) {
                   11690:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11691:                 my $instsec = $1;
1.645     raeburn  11692:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11693:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11694:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11695:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11696:                 }
                   11697:             }
                   11698:         }
                   11699:     }
                   11700: 
                   11701:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11702:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11703:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11704:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11705:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11706:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11707:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11708:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11709:                 }
                   11710:             }
                   11711:         }
                   11712:     }
                   11713:     return;
                   11714: }
                   11715: 
1.971     raeburn  11716: sub get_standard_codeitems {
                   11717:     return ('Year','Semester','Department','Number','Section');
                   11718: }
                   11719: 
1.112     bowersj2 11720: =pod
                   11721: 
1.780     raeburn  11722: =head1 Slot Helpers
                   11723: 
                   11724: =over 4
                   11725: 
                   11726: =item * sorted_slots()
                   11727: 
1.1040    raeburn  11728: Sorts an array of slot names in order of an optional sort key,
                   11729: default sort is by slot start time (earliest first). 
1.780     raeburn  11730: 
                   11731: Inputs:
                   11732: 
                   11733: =over 4
                   11734: 
                   11735: slotsarr  - Reference to array of unsorted slot names.
                   11736: 
                   11737: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11738: 
1.1040    raeburn  11739: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11740: 
1.549     albertel 11741: =back
                   11742: 
1.780     raeburn  11743: Returns:
                   11744: 
                   11745: =over 4
                   11746: 
1.1040    raeburn  11747: sorted   - An array of slot names sorted by a specified sort key 
                   11748:            (default sort key is start time of the slot).
1.780     raeburn  11749: 
                   11750: =back
                   11751: 
                   11752: =cut
                   11753: 
                   11754: 
                   11755: sub sorted_slots {
1.1040    raeburn  11756:     my ($slotsarr,$slots,$sortkey) = @_;
                   11757:     if ($sortkey eq '') {
                   11758:         $sortkey = 'starttime';
                   11759:     }
1.780     raeburn  11760:     my @sorted;
                   11761:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11762:         @sorted =
                   11763:             sort {
                   11764:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11765:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11766:                      }
                   11767:                      if (ref($slots->{$a})) { return -1;}
                   11768:                      if (ref($slots->{$b})) { return 1;}
                   11769:                      return 0;
                   11770:                  } @{$slotsarr};
                   11771:     }
                   11772:     return @sorted;
                   11773: }
                   11774: 
1.1040    raeburn  11775: =pod
                   11776: 
                   11777: =item * get_future_slots()
                   11778: 
                   11779: Inputs:
                   11780: 
                   11781: =over 4
                   11782: 
                   11783: cnum - course number
                   11784: 
                   11785: cdom - course domain
                   11786: 
                   11787: now - current UNIX time
                   11788: 
                   11789: symb - optional symb
                   11790: 
                   11791: =back
                   11792: 
                   11793: Returns:
                   11794: 
                   11795: =over 4
                   11796: 
                   11797: sorted_reservable - ref to array of student_schedulable slots currently 
                   11798:                     reservable, ordered by end date of reservation period.
                   11799: 
                   11800: reservable_now - ref to hash of student_schedulable slots currently
                   11801:                  reservable.
                   11802: 
                   11803:     Keys in inner hash are:
                   11804:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11805:     (b) endreserve: end date of reservation period.
                   11806:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11807:         selected.
1.1040    raeburn  11808: 
                   11809: sorted_future - ref to array of student_schedulable slots reservable in
                   11810:                 the future, ordered by start date of reservation period.
                   11811: 
                   11812: future_reservable - ref to hash of student_schedulable slots reservable
                   11813:                     in the future.
                   11814: 
                   11815:     Keys in inner hash are:
                   11816:     (a) symb: either blank or symb to which slot use is restricted.
                   11817:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11818:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11819:         selected.
1.1040    raeburn  11820: 
                   11821: =back
                   11822: 
                   11823: =cut
                   11824: 
                   11825: sub get_future_slots {
                   11826:     my ($cnum,$cdom,$now,$symb) = @_;
                   11827:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11828:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11829:     foreach my $slot (keys(%slots)) {
                   11830:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11831:         if ($symb) {
                   11832:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11833:                      ($slots{$slot}->{'symb'} ne $symb));
                   11834:         }
                   11835:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11836:             ($slots{$slot}->{'endtime'} > $now)) {
                   11837:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11838:                 my $userallowed = 0;
                   11839:                 if ($slots{$slot}->{'allowedsections'}) {
                   11840:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11841:                     if (!defined($env{'request.role.sec'})
                   11842:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11843:                         $userallowed=1;
                   11844:                     } else {
                   11845:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11846:                             $userallowed=1;
                   11847:                         }
                   11848:                     }
                   11849:                     unless ($userallowed) {
                   11850:                         if (defined($env{'request.course.groups'})) {
                   11851:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11852:                             foreach my $group (@groups) {
                   11853:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11854:                                     $userallowed=1;
                   11855:                                     last;
                   11856:                                 }
                   11857:                             }
                   11858:                         }
                   11859:                     }
                   11860:                 }
                   11861:                 if ($slots{$slot}->{'allowedusers'}) {
                   11862:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11863:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11864:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11865:                         $userallowed = 1;
                   11866:                     }
                   11867:                 }
                   11868:                 next unless($userallowed);
                   11869:             }
                   11870:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11871:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11872:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11873:             my $uniqueperiod;
                   11874:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11875:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11876:             }
1.1040    raeburn  11877:             if (($startreserve < $now) &&
                   11878:                 (!$endreserve || $endreserve > $now)) {
                   11879:                 my $lastres = $endreserve;
                   11880:                 if (!$lastres) {
                   11881:                     $lastres = $slots{$slot}->{'starttime'};
                   11882:                 }
                   11883:                 $reservable_now{$slot} = {
                   11884:                                            symb       => $symb,
1.1075.2.104  raeburn  11885:                                            endreserve => $lastres,
                   11886:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11887:                                          };
                   11888:             } elsif (($startreserve > $now) &&
                   11889:                      (!$endreserve || $endreserve > $startreserve)) {
                   11890:                 $future_reservable{$slot} = {
                   11891:                                               symb         => $symb,
1.1075.2.104  raeburn  11892:                                               startreserve => $startreserve,
                   11893:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11894:                                             };
                   11895:             }
                   11896:         }
                   11897:     }
                   11898:     my @unsorted_reservable = keys(%reservable_now);
                   11899:     if (@unsorted_reservable > 0) {
                   11900:         @sorted_reservable = 
                   11901:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11902:     }
                   11903:     my @unsorted_future = keys(%future_reservable);
                   11904:     if (@unsorted_future > 0) {
                   11905:         @sorted_future =
                   11906:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11907:     }
                   11908:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11909: }
1.780     raeburn  11910: 
                   11911: =pod
                   11912: 
1.1057    foxr     11913: =back
                   11914: 
1.549     albertel 11915: =head1 HTTP Helpers
                   11916: 
                   11917: =over 4
                   11918: 
1.648     raeburn  11919: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11920: 
1.258     albertel 11921: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11922: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11923: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11924: 
                   11925: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11926: $possible_names is an ref to an array of form element names.  As an example:
                   11927: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11928: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11929: 
                   11930: =cut
1.1       albertel 11931: 
1.6       albertel 11932: sub get_unprocessed_cgi {
1.25      albertel 11933:   my ($query,$possible_names)= @_;
1.26      matthew  11934:   # $Apache::lonxml::debug=1;
1.356     albertel 11935:   foreach my $pair (split(/&/,$query)) {
                   11936:     my ($name, $value) = split(/=/,$pair);
1.369     www      11937:     $name = &unescape($name);
1.25      albertel 11938:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11939:       $value =~ tr/+/ /;
                   11940:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11941:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11942:     }
1.16      harris41 11943:   }
1.6       albertel 11944: }
                   11945: 
1.112     bowersj2 11946: =pod
                   11947: 
1.648     raeburn  11948: =item * &cacheheader() 
1.112     bowersj2 11949: 
                   11950: returns cache-controlling header code
                   11951: 
                   11952: =cut
                   11953: 
1.7       albertel 11954: sub cacheheader {
1.258     albertel 11955:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11956:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11957:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11958:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11959:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11960:     return $output;
1.7       albertel 11961: }
                   11962: 
1.112     bowersj2 11963: =pod
                   11964: 
1.648     raeburn  11965: =item * &no_cache($r) 
1.112     bowersj2 11966: 
                   11967: specifies header code to not have cache
                   11968: 
                   11969: =cut
                   11970: 
1.9       albertel 11971: sub no_cache {
1.216     albertel 11972:     my ($r) = @_;
                   11973:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11974: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11975:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11976:     $r->no_cache(1);
                   11977:     $r->header_out("Expires" => $date);
                   11978:     $r->header_out("Pragma" => "no-cache");
1.123     www      11979: }
                   11980: 
                   11981: sub content_type {
1.181     albertel 11982:     my ($r,$type,$charset) = @_;
1.299     foxr     11983:     if ($r) {
                   11984: 	#  Note that printout.pl calls this with undef for $r.
                   11985: 	&no_cache($r);
                   11986:     }
1.258     albertel 11987:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11988:     unless ($charset) {
                   11989: 	$charset=&Apache::lonlocal::current_encoding;
                   11990:     }
                   11991:     if ($charset) { $type.='; charset='.$charset; }
                   11992:     if ($r) {
                   11993: 	$r->content_type($type);
                   11994:     } else {
                   11995: 	print("Content-type: $type\n\n");
                   11996:     }
1.9       albertel 11997: }
1.25      albertel 11998: 
1.112     bowersj2 11999: =pod
                   12000: 
1.648     raeburn  12001: =item * &add_to_env($name,$value) 
1.112     bowersj2 12002: 
1.258     albertel 12003: adds $name to the %env hash with value
1.112     bowersj2 12004: $value, if $name already exists, the entry is converted to an array
                   12005: reference and $value is added to the array.
                   12006: 
                   12007: =cut
                   12008: 
1.25      albertel 12009: sub add_to_env {
                   12010:   my ($name,$value)=@_;
1.258     albertel 12011:   if (defined($env{$name})) {
                   12012:     if (ref($env{$name})) {
1.25      albertel 12013:       #already have multiple values
1.258     albertel 12014:       push(@{ $env{$name} },$value);
1.25      albertel 12015:     } else {
                   12016:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12017:       my $first=$env{$name};
                   12018:       undef($env{$name});
                   12019:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12020:     }
                   12021:   } else {
1.258     albertel 12022:     $env{$name}=$value;
1.25      albertel 12023:   }
1.31      albertel 12024: }
1.149     albertel 12025: 
                   12026: =pod
                   12027: 
1.648     raeburn  12028: =item * &get_env_multiple($name) 
1.149     albertel 12029: 
1.258     albertel 12030: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12031: values may be defined and end up as an array ref.
                   12032: 
                   12033: returns an array of values
                   12034: 
                   12035: =cut
                   12036: 
                   12037: sub get_env_multiple {
                   12038:     my ($name) = @_;
                   12039:     my @values;
1.258     albertel 12040:     if (defined($env{$name})) {
1.149     albertel 12041:         # exists is it an array
1.258     albertel 12042:         if (ref($env{$name})) {
                   12043:             @values=@{ $env{$name} };
1.149     albertel 12044:         } else {
1.258     albertel 12045:             $values[0]=$env{$name};
1.149     albertel 12046:         }
                   12047:     }
                   12048:     return(@values);
                   12049: }
                   12050: 
1.660     raeburn  12051: sub ask_for_embedded_content {
                   12052:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12053:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  12054:         %currsubfile,%unused,$rem);
1.1071    raeburn  12055:     my $counter = 0;
                   12056:     my $numnew = 0;
1.987     raeburn  12057:     my $numremref = 0;
                   12058:     my $numinvalid = 0;
                   12059:     my $numpathchg = 0;
                   12060:     my $numexisting = 0;
1.1071    raeburn  12061:     my $numunused = 0;
                   12062:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  12063:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12064:     my $heading = &mt('Upload embedded files');
                   12065:     my $buttontext = &mt('Upload');
                   12066: 
1.1075.2.11  raeburn  12067:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  12068:         if ($actionurl eq '/adm/dependencies') {
                   12069:             $navmap = Apache::lonnavmaps::navmap->new();
                   12070:         }
                   12071:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12072:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  12073:     }
1.1075.2.35  raeburn  12074:     if (($actionurl eq '/adm/portfolio') ||
                   12075:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12076:         my $current_path='/';
                   12077:         if ($env{'form.currentpath'}) {
                   12078:             $current_path = $env{'form.currentpath'};
                   12079:         }
                   12080:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  12081:             $udom = $cdom;
                   12082:             $uname = $cnum;
1.984     raeburn  12083:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12084:         } else {
                   12085:             $udom = $env{'user.domain'};
                   12086:             $uname = $env{'user.name'};
                   12087:             $url = '/userfiles/portfolio';
                   12088:         }
1.987     raeburn  12089:         $toplevel = $url.'/';
1.984     raeburn  12090:         $url .= $current_path;
                   12091:         $getpropath = 1;
1.987     raeburn  12092:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12093:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12094:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12095:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12096:         $toplevel = $url;
1.984     raeburn  12097:         if ($rest ne '') {
1.987     raeburn  12098:             $url .= $rest;
                   12099:         }
                   12100:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12101:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12102:             $url = $args->{'docs_url'};
                   12103:             $toplevel = $url;
1.1075.2.11  raeburn  12104:             if ($args->{'context'} eq 'paste') {
                   12105:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12106:                 ($path) =
                   12107:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12108:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12109:                 $fileloc =~ s{^/}{};
                   12110:             }
1.1071    raeburn  12111:         }
                   12112:     } elsif ($actionurl eq '/adm/dependencies') {
                   12113:         if ($env{'request.course.id'} ne '') {
                   12114:             if (ref($args) eq 'HASH') {
                   12115:                 $url = $args->{'docs_url'};
                   12116:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  12117:                 $toplevel = $url;
                   12118:                 unless ($toplevel =~ m{^/}) {
                   12119:                     $toplevel = "/$url";
                   12120:                 }
1.1075.2.11  raeburn  12121:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  12122:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12123:                     $path = $1;
                   12124:                 } else {
                   12125:                     ($path) =
                   12126:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12127:                 }
1.1075.2.79  raeburn  12128:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12129:                     $fileloc = $toplevel;
                   12130:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12131:                     my ($udom,$uname,$fname) =
                   12132:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12133:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12134:                 } else {
                   12135:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12136:                 }
1.1071    raeburn  12137:                 $fileloc =~ s{^/}{};
                   12138:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12139:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12140:             }
1.987     raeburn  12141:         }
1.1075.2.35  raeburn  12142:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12143:         $udom = $cdom;
                   12144:         $uname = $cnum;
                   12145:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12146:         $toplevel = $url;
                   12147:         $path = $url;
                   12148:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12149:         $fileloc =~ s{^/}{};
                   12150:     }
                   12151:     foreach my $file (keys(%{$allfiles})) {
                   12152:         my $embed_file;
                   12153:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12154:             $embed_file = $1;
                   12155:         } else {
                   12156:             $embed_file = $file;
                   12157:         }
1.1075.2.55  raeburn  12158:         my ($absolutepath,$cleaned_file);
                   12159:         if ($embed_file =~ m{^\w+://}) {
                   12160:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  12161:             $newfiles{$cleaned_file} = 1;
                   12162:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12163:         } else {
1.1075.2.55  raeburn  12164:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12165:             if ($embed_file =~ m{^/}) {
                   12166:                 $absolutepath = $embed_file;
                   12167:             }
1.1075.2.47  raeburn  12168:             if ($cleaned_file =~ m{/}) {
                   12169:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12170:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12171:                 my $item = $fname;
                   12172:                 if ($path ne '') {
                   12173:                     $item = $path.'/'.$fname;
                   12174:                     $subdependencies{$path}{$fname} = 1;
                   12175:                 } else {
                   12176:                     $dependencies{$item} = 1;
                   12177:                 }
                   12178:                 if ($absolutepath) {
                   12179:                     $mapping{$item} = $absolutepath;
                   12180:                 } else {
                   12181:                     $mapping{$item} = $embed_file;
                   12182:                 }
                   12183:             } else {
                   12184:                 $dependencies{$embed_file} = 1;
                   12185:                 if ($absolutepath) {
1.1075.2.47  raeburn  12186:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12187:                 } else {
1.1075.2.47  raeburn  12188:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12189:                 }
                   12190:             }
1.984     raeburn  12191:         }
                   12192:     }
1.1071    raeburn  12193:     my $dirptr = 16384;
1.984     raeburn  12194:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12195:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  12196:         if (($actionurl eq '/adm/portfolio') ||
                   12197:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  12198:             my ($sublistref,$listerror) =
                   12199:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12200:             if (ref($sublistref) eq 'ARRAY') {
                   12201:                 foreach my $line (@{$sublistref}) {
                   12202:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12203:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12204:                 }
1.984     raeburn  12205:             }
1.987     raeburn  12206:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12207:             if (opendir(my $dir,$url.'/'.$path)) {
                   12208:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12209:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12210:             }
1.1075.2.11  raeburn  12211:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12212:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12213:                   ($args->{'context'} eq 'paste')) ||
                   12214:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12215:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  12216:                 my $dir;
                   12217:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12218:                     $dir = $fileloc;
                   12219:                 } else {
                   12220:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12221:                 }
1.1071    raeburn  12222:                 if ($dir ne '') {
                   12223:                     my ($sublistref,$listerror) =
                   12224:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12225:                     if (ref($sublistref) eq 'ARRAY') {
                   12226:                         foreach my $line (@{$sublistref}) {
                   12227:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12228:                                 undef,$mtime)=split(/\&/,$line,12);
                   12229:                             unless (($testdir&$dirptr) ||
                   12230:                                     ($file_name =~ /^\.\.?$/)) {
                   12231:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12232:                             }
                   12233:                         }
                   12234:                     }
                   12235:                 }
1.984     raeburn  12236:             }
                   12237:         }
                   12238:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12239:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12240:                 my $item = $path.'/'.$file;
                   12241:                 unless ($mapping{$item} eq $item) {
                   12242:                     $pathchanges{$item} = 1;
                   12243:                 }
                   12244:                 $existing{$item} = 1;
                   12245:                 $numexisting ++;
                   12246:             } else {
                   12247:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12248:             }
                   12249:         }
1.1071    raeburn  12250:         if ($actionurl eq '/adm/dependencies') {
                   12251:             foreach my $path (keys(%currsubfile)) {
                   12252:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12253:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12254:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  12255:                              next if (($rem ne '') &&
                   12256:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12257:                                        (ref($navmap) &&
                   12258:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12259:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12260:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12261:                              $unused{$path.'/'.$file} = 1; 
                   12262:                          }
                   12263:                     }
                   12264:                 }
                   12265:             }
                   12266:         }
1.984     raeburn  12267:     }
1.987     raeburn  12268:     my %currfile;
1.1075.2.35  raeburn  12269:     if (($actionurl eq '/adm/portfolio') ||
                   12270:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12271:         my ($dirlistref,$listerror) =
                   12272:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12273:         if (ref($dirlistref) eq 'ARRAY') {
                   12274:             foreach my $line (@{$dirlistref}) {
                   12275:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12276:                 $currfile{$file_name} = 1;
                   12277:             }
1.984     raeburn  12278:         }
1.987     raeburn  12279:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12280:         if (opendir(my $dir,$url)) {
1.987     raeburn  12281:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12282:             map {$currfile{$_} = 1;} @dir_list;
                   12283:         }
1.1075.2.11  raeburn  12284:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12285:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12286:               ($args->{'context'} eq 'paste')) ||
                   12287:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12288:         if ($env{'request.course.id'} ne '') {
                   12289:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12290:             if ($dir ne '') {
                   12291:                 my ($dirlistref,$listerror) =
                   12292:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12293:                 if (ref($dirlistref) eq 'ARRAY') {
                   12294:                     foreach my $line (@{$dirlistref}) {
                   12295:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12296:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12297:                         unless (($testdir&$dirptr) ||
                   12298:                                 ($file_name =~ /^\.\.?$/)) {
                   12299:                             $currfile{$file_name} = [$size,$mtime];
                   12300:                         }
                   12301:                     }
                   12302:                 }
                   12303:             }
                   12304:         }
1.984     raeburn  12305:     }
                   12306:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12307:         if (exists($currfile{$file})) {
1.987     raeburn  12308:             unless ($mapping{$file} eq $file) {
                   12309:                 $pathchanges{$file} = 1;
                   12310:             }
                   12311:             $existing{$file} = 1;
                   12312:             $numexisting ++;
                   12313:         } else {
1.984     raeburn  12314:             $newfiles{$file} = 1;
                   12315:         }
                   12316:     }
1.1071    raeburn  12317:     foreach my $file (keys(%currfile)) {
                   12318:         unless (($file eq $filename) ||
                   12319:                 ($file eq $filename.'.bak') ||
                   12320:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  12321:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  12322:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12323:                     next if (($rem ne '') &&
                   12324:                              (($env{"httpref.$rem".$file} ne '') ||
                   12325:                               (ref($navmap) &&
                   12326:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12327:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12328:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12329:                 }
1.1075.2.11  raeburn  12330:             }
1.1071    raeburn  12331:             $unused{$file} = 1;
                   12332:         }
                   12333:     }
1.1075.2.11  raeburn  12334:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12335:         ($args->{'context'} eq 'paste')) {
                   12336:         $counter = scalar(keys(%existing));
                   12337:         $numpathchg = scalar(keys(%pathchanges));
                   12338:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  12339:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   12340:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12341:         $counter = scalar(keys(%existing));
                   12342:         $numpathchg = scalar(keys(%pathchanges));
                   12343:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  12344:     }
1.984     raeburn  12345:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12346:         if ($actionurl eq '/adm/dependencies') {
                   12347:             next if ($embed_file =~ m{^\w+://});
                   12348:         }
1.660     raeburn  12349:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12350:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12351:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12352:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  12353:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12354:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12355:         }
1.1075.2.35  raeburn  12356:         $upload_output .= '</td>';
1.1071    raeburn  12357:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  12358:             $upload_output.='<td align="right">'.
                   12359:                             '<span class="LC_info LC_fontsize_medium">'.
                   12360:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12361:             $numremref++;
1.660     raeburn  12362:         } elsif ($args->{'error_on_invalid_names'}
                   12363:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  12364:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12365:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12366:             $numinvalid++;
1.660     raeburn  12367:         } else {
1.1075.2.35  raeburn  12368:             $upload_output .= '<td>'.
                   12369:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12370:                                                      $embed_file,\%mapping,
1.1071    raeburn  12371:                                                      $allfiles,$codebase,'upload');
                   12372:             $counter ++;
                   12373:             $numnew ++;
1.987     raeburn  12374:         }
                   12375:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12376:     }
                   12377:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12378:         if ($actionurl eq '/adm/dependencies') {
                   12379:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12380:             $modify_output .= &start_data_table_row().
                   12381:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12382:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12383:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12384:                               '<td>'.$size.'</td>'.
                   12385:                               '<td>'.$mtime.'</td>'.
                   12386:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12387:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12388:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12389:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12390:                               &embedded_file_element('upload_embedded',$counter,
                   12391:                                                      $embed_file,\%mapping,
                   12392:                                                      $allfiles,$codebase,'modify').
                   12393:                               '</div></td>'.
                   12394:                               &end_data_table_row()."\n";
                   12395:             $counter ++;
                   12396:         } else {
                   12397:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12398:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12399:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12400:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12401:                               &Apache::loncommon::end_data_table_row()."\n";
                   12402:         }
                   12403:     }
                   12404:     my $delidx = $counter;
                   12405:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12406:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12407:         $delete_output .= &start_data_table_row().
                   12408:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12409:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12410:                           '<td>'.$size.'</td>'.
                   12411:                           '<td>'.$mtime.'</td>'.
                   12412:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12413:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12414:                           &embedded_file_element('upload_embedded',$delidx,
                   12415:                                                  $oldfile,\%mapping,$allfiles,
                   12416:                                                  $codebase,'delete').'</td>'.
                   12417:                           &end_data_table_row()."\n"; 
                   12418:         $numunused ++;
                   12419:         $delidx ++;
1.987     raeburn  12420:     }
                   12421:     if ($upload_output) {
                   12422:         $upload_output = &start_data_table().
                   12423:                          $upload_output.
                   12424:                          &end_data_table()."\n";
                   12425:     }
1.1071    raeburn  12426:     if ($modify_output) {
                   12427:         $modify_output = &start_data_table().
                   12428:                          &start_data_table_header_row().
                   12429:                          '<th>'.&mt('File').'</th>'.
                   12430:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12431:                          '<th>'.&mt('Modified').'</th>'.
                   12432:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12433:                          &end_data_table_header_row().
                   12434:                          $modify_output.
                   12435:                          &end_data_table()."\n";
                   12436:     }
                   12437:     if ($delete_output) {
                   12438:         $delete_output = &start_data_table().
                   12439:                          &start_data_table_header_row().
                   12440:                          '<th>'.&mt('File').'</th>'.
                   12441:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12442:                          '<th>'.&mt('Modified').'</th>'.
                   12443:                          '<th>'.&mt('Delete?').'</th>'.
                   12444:                          &end_data_table_header_row().
                   12445:                          $delete_output.
                   12446:                          &end_data_table()."\n";
                   12447:     }
1.987     raeburn  12448:     my $applies = 0;
                   12449:     if ($numremref) {
                   12450:         $applies ++;
                   12451:     }
                   12452:     if ($numinvalid) {
                   12453:         $applies ++;
                   12454:     }
                   12455:     if ($numexisting) {
                   12456:         $applies ++;
                   12457:     }
1.1071    raeburn  12458:     if ($counter || $numunused) {
1.987     raeburn  12459:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12460:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12461:                   $state.'<h3>'.$heading.'</h3>'; 
                   12462:         if ($actionurl eq '/adm/dependencies') {
                   12463:             if ($numnew) {
                   12464:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12465:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12466:                            $upload_output.'<br />'."\n";
                   12467:             }
                   12468:             if ($numexisting) {
                   12469:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12470:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12471:                            $modify_output.'<br />'."\n";
                   12472:                            $buttontext = &mt('Save changes');
                   12473:             }
                   12474:             if ($numunused) {
                   12475:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12476:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12477:                            $delete_output.'<br />'."\n";
                   12478:                            $buttontext = &mt('Save changes');
                   12479:             }
                   12480:         } else {
                   12481:             $output .= $upload_output.'<br />'."\n";
                   12482:         }
                   12483:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12484:                    $counter.'" />'."\n";
                   12485:         if ($actionurl eq '/adm/dependencies') { 
                   12486:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12487:                        $numnew.'" />'."\n";
                   12488:         } elsif ($actionurl eq '') {
1.987     raeburn  12489:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12490:         }
                   12491:     } elsif ($applies) {
                   12492:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12493:         if ($applies > 1) {
                   12494:             $output .=  
1.1075.2.35  raeburn  12495:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12496:             if ($numremref) {
                   12497:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12498:             }
                   12499:             if ($numinvalid) {
                   12500:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12501:             }
                   12502:             if ($numexisting) {
                   12503:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12504:             }
                   12505:             $output .= '</ul><br />';
                   12506:         } elsif ($numremref) {
                   12507:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12508:         } elsif ($numinvalid) {
                   12509:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12510:         } elsif ($numexisting) {
                   12511:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12512:         }
                   12513:         $output .= $upload_output.'<br />';
                   12514:     }
                   12515:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12516:     $chgcount = $counter;
1.987     raeburn  12517:     if (keys(%pathchanges) > 0) {
                   12518:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12519:             if ($counter) {
1.987     raeburn  12520:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12521:                                                   $embed_file,\%mapping,
1.1071    raeburn  12522:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12523:             } else {
                   12524:                 $pathchange_output .= 
                   12525:                     &start_data_table_row().
                   12526:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12527:                     $chgcount.'" checked="checked" /></td>'.
                   12528:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12529:                     '<td>'.$embed_file.
                   12530:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12531:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12532:                     '</td>'.&end_data_table_row();
1.660     raeburn  12533:             }
1.987     raeburn  12534:             $numpathchg ++;
                   12535:             $chgcount ++;
1.660     raeburn  12536:         }
                   12537:     }
1.1075.2.35  raeburn  12538:     if (($counter) || ($numunused)) {
1.987     raeburn  12539:         if ($numpathchg) {
                   12540:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12541:                        $numpathchg.'" />'."\n";
                   12542:         }
                   12543:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12544:             ($actionurl eq '/adm/imsimport')) {
                   12545:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12546:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12547:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12548:         } elsif ($actionurl eq '/adm/dependencies') {
                   12549:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12550:         }
1.1075.2.35  raeburn  12551:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12552:     } elsif ($numpathchg) {
                   12553:         my %pathchange = ();
                   12554:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12555:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12556:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12557:         }
1.987     raeburn  12558:     }
1.1071    raeburn  12559:     return ($output,$counter,$numpathchg);
1.987     raeburn  12560: }
                   12561: 
1.1075.2.47  raeburn  12562: =pod
                   12563: 
                   12564: =item * clean_path($name)
                   12565: 
                   12566: Performs clean-up of directories, subdirectories and filename in an
                   12567: embedded object, referenced in an HTML file which is being uploaded
                   12568: to a course or portfolio, where
                   12569: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12570: checked.
                   12571: 
                   12572: Clean-up is similar to replacements in lonnet::clean_filename()
                   12573: except each / between sub-directory and next level is preserved.
                   12574: 
                   12575: =cut
                   12576: 
                   12577: sub clean_path {
                   12578:     my ($embed_file) = @_;
                   12579:     $embed_file =~s{^/+}{};
                   12580:     my @contents;
                   12581:     if ($embed_file =~ m{/}) {
                   12582:         @contents = split(/\//,$embed_file);
                   12583:     } else {
                   12584:         @contents = ($embed_file);
                   12585:     }
                   12586:     my $lastidx = scalar(@contents)-1;
                   12587:     for (my $i=0; $i<=$lastidx; $i++) {
                   12588:         $contents[$i]=~s{\\}{/}g;
                   12589:         $contents[$i]=~s/\s+/\_/g;
                   12590:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12591:         if ($i == $lastidx) {
                   12592:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12593:         }
                   12594:     }
                   12595:     if ($lastidx > 0) {
                   12596:         return join('/',@contents);
                   12597:     } else {
                   12598:         return $contents[0];
                   12599:     }
                   12600: }
                   12601: 
1.987     raeburn  12602: sub embedded_file_element {
1.1071    raeburn  12603:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12604:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12605:                    (ref($codebase) eq 'HASH'));
                   12606:     my $output;
1.1071    raeburn  12607:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12608:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12609:     }
                   12610:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12611:                &escape($embed_file).'" />';
                   12612:     unless (($context eq 'upload_embedded') && 
                   12613:             ($mapping->{$embed_file} eq $embed_file)) {
                   12614:         $output .='
                   12615:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12616:     }
                   12617:     my $attrib;
                   12618:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12619:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12620:     }
                   12621:     $output .=
                   12622:         "\n\t\t".
                   12623:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12624:         $attrib.'" />';
                   12625:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12626:         $output .=
                   12627:             "\n\t\t".
                   12628:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12629:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12630:     }
1.987     raeburn  12631:     return $output;
1.660     raeburn  12632: }
                   12633: 
1.1071    raeburn  12634: sub get_dependency_details {
                   12635:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12636:     my ($size,$mtime,$showsize,$showmtime);
                   12637:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12638:         if ($embed_file =~ m{/}) {
                   12639:             my ($path,$fname) = split(/\//,$embed_file);
                   12640:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12641:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12642:             }
                   12643:         } else {
                   12644:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12645:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12646:             }
                   12647:         }
                   12648:         $showsize = $size/1024.0;
                   12649:         $showsize = sprintf("%.1f",$showsize);
                   12650:         if ($mtime > 0) {
                   12651:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12652:         }
                   12653:     }
                   12654:     return ($showsize,$showmtime);
                   12655: }
                   12656: 
                   12657: sub ask_embedded_js {
                   12658:     return <<"END";
                   12659: <script type="text/javascript"">
                   12660: // <![CDATA[
                   12661: function toggleBrowse(counter) {
                   12662:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12663:     var fileid = document.getElementById('embedded_item_'+counter);
                   12664:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12665:     if (chkboxid.checked == true) {
                   12666:         uploaddivid.style.display='block';
                   12667:     } else {
                   12668:         uploaddivid.style.display='none';
                   12669:         fileid.value = '';
                   12670:     }
                   12671: }
                   12672: // ]]>
                   12673: </script>
                   12674: 
                   12675: END
                   12676: }
                   12677: 
1.661     raeburn  12678: sub upload_embedded {
                   12679:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12680:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12681:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12682:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12683:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12684:         my $orig_uploaded_filename =
                   12685:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12686:         foreach my $type ('orig','ref','attrib','codebase') {
                   12687:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12688:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12689:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12690:             }
                   12691:         }
1.661     raeburn  12692:         my ($path,$fname) =
                   12693:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12694:         # no path, whole string is fname
                   12695:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12696:         $fname = &Apache::lonnet::clean_filename($fname);
                   12697:         # See if there is anything left
                   12698:         next if ($fname eq '');
                   12699: 
                   12700:         # Check if file already exists as a file or directory.
                   12701:         my ($state,$msg);
                   12702:         if ($context eq 'portfolio') {
                   12703:             my $port_path = $dirpath;
                   12704:             if ($group ne '') {
                   12705:                 $port_path = "groups/$group/$port_path";
                   12706:             }
1.987     raeburn  12707:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12708:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12709:                                               $dir_root,$port_path,$disk_quota,
                   12710:                                               $current_disk_usage,$uname,$udom);
                   12711:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12712:                 || $state eq 'file_locked') {
1.661     raeburn  12713:                 $output .= $msg;
                   12714:                 next;
                   12715:             }
                   12716:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12717:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12718:             if ($state eq 'exists') {
                   12719:                 $output .= $msg;
                   12720:                 next;
                   12721:             }
                   12722:         }
                   12723:         # Check if extension is valid
                   12724:         if (($fname =~ /\.(\w+)$/) &&
                   12725:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12726:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12727:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12728:             next;
                   12729:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12730:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12731:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12732:             next;
                   12733:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12734:             $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  12735:             next;
                   12736:         }
                   12737:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12738:         my $subdir = $path;
                   12739:         $subdir =~ s{/+$}{};
1.661     raeburn  12740:         if ($context eq 'portfolio') {
1.984     raeburn  12741:             my $result;
                   12742:             if ($state eq 'existingfile') {
                   12743:                 $result=
                   12744:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12745:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12746:             } else {
1.984     raeburn  12747:                 $result=
                   12748:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12749:                                                     $dirpath.
1.1075.2.35  raeburn  12750:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12751:                 if ($result !~ m|^/uploaded/|) {
                   12752:                     $output .= '<span class="LC_error">'
                   12753:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12754:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12755:                                .'</span><br />';
                   12756:                     next;
                   12757:                 } else {
1.987     raeburn  12758:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12759:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12760:                 }
1.661     raeburn  12761:             }
1.1075.2.35  raeburn  12762:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12763:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12764:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12765:             my $result =
1.1075.2.35  raeburn  12766:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12767:             if ($result !~ m|^/uploaded/|) {
                   12768:                 $output .= '<span class="LC_error">'
                   12769:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12770:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12771:                            .'</span><br />';
                   12772:                     next;
                   12773:             } else {
                   12774:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12775:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12776:                 if ($context eq 'syllabus') {
                   12777:                     &Apache::lonnet::make_public_indefinitely($result);
                   12778:                 }
1.987     raeburn  12779:             }
1.661     raeburn  12780:         } else {
                   12781: # Save the file
                   12782:             my $target = $env{'form.embedded_item_'.$i};
                   12783:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12784:             my $dest = $fullpath.$fname;
                   12785:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12786:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12787:             my $count;
                   12788:             my $filepath = $dir_root;
1.1027    raeburn  12789:             foreach my $subdir (@parts) {
                   12790:                 $filepath .= "/$subdir";
                   12791:                 if (!-e $filepath) {
1.661     raeburn  12792:                     mkdir($filepath,0770);
                   12793:                 }
                   12794:             }
                   12795:             my $fh;
                   12796:             if (!open($fh,'>'.$dest)) {
                   12797:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12798:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12799:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12800:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12801:                            '</span><br />';
                   12802:             } else {
                   12803:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12804:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12805:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12806:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12807:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12808:                               '</span><br />';
                   12809:                 } else {
1.987     raeburn  12810:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12811:                                $url.'</span>').'<br />';
                   12812:                     unless ($context eq 'testbank') {
                   12813:                         $footer .= &mt('View embedded file: [_1]',
                   12814:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12815:                     }
                   12816:                 }
                   12817:                 close($fh);
                   12818:             }
                   12819:         }
                   12820:         if ($env{'form.embedded_ref_'.$i}) {
                   12821:             $pathchange{$i} = 1;
                   12822:         }
                   12823:     }
                   12824:     if ($output) {
                   12825:         $output = '<p>'.$output.'</p>';
                   12826:     }
                   12827:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12828:     $returnflag = 'ok';
1.1071    raeburn  12829:     my $numpathchgs = scalar(keys(%pathchange));
                   12830:     if ($numpathchgs > 0) {
1.987     raeburn  12831:         if ($context eq 'portfolio') {
                   12832:             $output .= '<p>'.&mt('or').'</p>';
                   12833:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12834:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12835:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12836:             $returnflag = 'modify_orightml';
                   12837:         }
                   12838:     }
1.1071    raeburn  12839:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12840: }
                   12841: 
                   12842: sub modify_html_form {
                   12843:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12844:     my $end = 0;
                   12845:     my $modifyform;
                   12846:     if ($context eq 'upload_embedded') {
                   12847:         return unless (ref($pathchange) eq 'HASH');
                   12848:         if ($env{'form.number_embedded_items'}) {
                   12849:             $end += $env{'form.number_embedded_items'};
                   12850:         }
                   12851:         if ($env{'form.number_pathchange_items'}) {
                   12852:             $end += $env{'form.number_pathchange_items'};
                   12853:         }
                   12854:         if ($end) {
                   12855:             for (my $i=0; $i<$end; $i++) {
                   12856:                 if ($i < $env{'form.number_embedded_items'}) {
                   12857:                     next unless($pathchange->{$i});
                   12858:                 }
                   12859:                 $modifyform .=
                   12860:                     &start_data_table_row().
                   12861:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12862:                     'checked="checked" /></td>'.
                   12863:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12864:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12865:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12866:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12867:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12868:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12869:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12870:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12871:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12872:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12873:                     &end_data_table_row();
1.1071    raeburn  12874:             }
1.987     raeburn  12875:         }
                   12876:     } else {
                   12877:         $modifyform = $pathchgtable;
                   12878:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12879:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12880:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12881:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12882:         }
                   12883:     }
                   12884:     if ($modifyform) {
1.1071    raeburn  12885:         if ($actionurl eq '/adm/dependencies') {
                   12886:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12887:         }
1.987     raeburn  12888:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12889:                '<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".
                   12890:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12891:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12892:                '</ol></p>'."\n".'<p>'.
                   12893:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12894:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12895:                &start_data_table()."\n".
                   12896:                &start_data_table_header_row().
                   12897:                '<th>'.&mt('Change?').'</th>'.
                   12898:                '<th>'.&mt('Current reference').'</th>'.
                   12899:                '<th>'.&mt('Required reference').'</th>'.
                   12900:                &end_data_table_header_row()."\n".
                   12901:                $modifyform.
                   12902:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12903:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12904:                '</form>'."\n";
                   12905:     }
                   12906:     return;
                   12907: }
                   12908: 
                   12909: sub modify_html_refs {
1.1075.2.35  raeburn  12910:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12911:     my $container;
                   12912:     if ($context eq 'portfolio') {
                   12913:         $container = $env{'form.container'};
                   12914:     } elsif ($context eq 'coursedoc') {
                   12915:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12916:     } elsif ($context eq 'manage_dependencies') {
                   12917:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12918:         $container = "/$container";
1.1075.2.35  raeburn  12919:     } elsif ($context eq 'syllabus') {
                   12920:         $container = $url;
1.987     raeburn  12921:     } else {
1.1027    raeburn  12922:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12923:     }
                   12924:     my (%allfiles,%codebase,$output,$content);
                   12925:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12926:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12927:         if (wantarray) {
                   12928:             return ('',0,0); 
                   12929:         } else {
                   12930:             return;
                   12931:         }
                   12932:     }
                   12933:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12934:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12935:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12936:             if (wantarray) {
                   12937:                 return ('',0,0);
                   12938:             } else {
                   12939:                 return;
                   12940:             }
                   12941:         } 
1.987     raeburn  12942:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12943:         if ($content eq '-1') {
                   12944:             if (wantarray) {
                   12945:                 return ('',0,0);
                   12946:             } else {
                   12947:                 return;
                   12948:             }
                   12949:         }
1.987     raeburn  12950:     } else {
1.1071    raeburn  12951:         unless ($container =~ /^\Q$dir_root\E/) {
                   12952:             if (wantarray) {
                   12953:                 return ('',0,0);
                   12954:             } else {
                   12955:                 return;
                   12956:             }
                   12957:         } 
1.1075.2.128  raeburn  12958:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12959:             $content = join('', <$fh>);
                   12960:             close($fh);
                   12961:         } else {
1.1071    raeburn  12962:             if (wantarray) {
                   12963:                 return ('',0,0);
                   12964:             } else {
                   12965:                 return;
                   12966:             }
1.987     raeburn  12967:         }
                   12968:     }
                   12969:     my ($count,$codebasecount) = (0,0);
                   12970:     my $mm = new File::MMagic;
                   12971:     my $mime_type = $mm->checktype_contents($content);
                   12972:     if ($mime_type eq 'text/html') {
                   12973:         my $parse_result = 
                   12974:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12975:                                                     \%codebase,\$content);
                   12976:         if ($parse_result eq 'ok') {
                   12977:             foreach my $i (@changes) {
                   12978:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12979:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12980:                 if ($allfiles{$ref}) {
                   12981:                     my $newname =  $orig;
                   12982:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12983:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12984:                     if ($attrib_regexp =~ /:/) {
                   12985:                         $attrib_regexp =~ s/\:/|/g;
                   12986:                     }
                   12987:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12988:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12989:                         $count += $numchg;
1.1075.2.35  raeburn  12990:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12991:                         delete($allfiles{$ref});
1.987     raeburn  12992:                     }
                   12993:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12994:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12995:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12996:                         $codebasecount ++;
                   12997:                     }
                   12998:                 }
                   12999:             }
1.1075.2.35  raeburn  13000:             my $skiprewrites;
1.987     raeburn  13001:             if ($count || $codebasecount) {
                   13002:                 my $saveresult;
1.1071    raeburn  13003:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  13004:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13005:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13006:                     if ($url eq $container) {
                   13007:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13008:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13009:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13010:                                             $fname.'</span>').'</p>';
1.987     raeburn  13011:                     } else {
                   13012:                          $output = '<p class="LC_error">'.
                   13013:                                    &mt('Error: update failed for: [_1].',
                   13014:                                    '<span class="LC_filename">'.
                   13015:                                    $container.'</span>').'</p>';
                   13016:                     }
1.1075.2.35  raeburn  13017:                     if ($context eq 'syllabus') {
                   13018:                         unless ($saveresult eq 'ok') {
                   13019:                             $skiprewrites = 1;
                   13020:                         }
                   13021:                     }
1.987     raeburn  13022:                 } else {
1.1075.2.128  raeburn  13023:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13024:                         print $fh $content;
                   13025:                         close($fh);
                   13026:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13027:                                   $count,'<span class="LC_filename">'.
                   13028:                                   $container.'</span>').'</p>';
1.661     raeburn  13029:                     } else {
1.987     raeburn  13030:                          $output = '<p class="LC_error">'.
                   13031:                                    &mt('Error: could not update [_1].',
                   13032:                                    '<span class="LC_filename">'.
                   13033:                                    $container.'</span>').'</p>';
1.661     raeburn  13034:                     }
                   13035:                 }
                   13036:             }
1.1075.2.35  raeburn  13037:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13038:                 my ($actionurl,$state);
                   13039:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13040:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13041:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13042:                                               \%codebase,
                   13043:                                               {'context' => 'rewrites',
                   13044:                                                'ignore_remote_references' => 1,});
                   13045:                 if (ref($mapping) eq 'HASH') {
                   13046:                     my $rewrites = 0;
                   13047:                     foreach my $key (keys(%{$mapping})) {
                   13048:                         next if ($key =~ m{^https?://});
                   13049:                         my $ref = $mapping->{$key};
                   13050:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13051:                         my $attrib;
                   13052:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13053:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13054:                         }
                   13055:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13056:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13057:                             $rewrites += $numchg;
                   13058:                         }
                   13059:                     }
                   13060:                     if ($rewrites) {
                   13061:                         my $saveresult;
                   13062:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13063:                         if ($url eq $container) {
                   13064:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13065:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13066:                                             $count,'<span class="LC_filename">'.
                   13067:                                             $fname.'</span>').'</p>';
                   13068:                         } else {
                   13069:                             $output .= '<p class="LC_error">'.
                   13070:                                        &mt('Error: could not update links in [_1].',
                   13071:                                        '<span class="LC_filename">'.
                   13072:                                        $container.'</span>').'</p>';
                   13073: 
                   13074:                         }
                   13075:                     }
                   13076:                 }
                   13077:             }
1.987     raeburn  13078:         } else {
                   13079:             &logthis('Failed to parse '.$container.
                   13080:                      ' to modify references: '.$parse_result);
1.661     raeburn  13081:         }
                   13082:     }
1.1071    raeburn  13083:     if (wantarray) {
                   13084:         return ($output,$count,$codebasecount);
                   13085:     } else {
                   13086:         return $output;
                   13087:     }
1.661     raeburn  13088: }
                   13089: 
                   13090: sub check_for_existing {
                   13091:     my ($path,$fname,$element) = @_;
                   13092:     my ($state,$msg);
                   13093:     if (-d $path.'/'.$fname) {
                   13094:         $state = 'exists';
                   13095:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13096:     } elsif (-e $path.'/'.$fname) {
                   13097:         $state = 'exists';
                   13098:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13099:     }
                   13100:     if ($state eq 'exists') {
                   13101:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13102:     }
                   13103:     return ($state,$msg);
                   13104: }
                   13105: 
                   13106: sub check_for_upload {
                   13107:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13108:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13109:     my $filesize = length($env{'form.'.$element});
                   13110:     if (!$filesize) {
                   13111:         my $msg = '<span class="LC_error">'.
                   13112:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13113:                       '<span class="LC_filename">'.$fname.'</span>',
                   13114:                       $filesize).'<br />'.
1.1007    raeburn  13115:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13116:                   '</span>';
                   13117:         return ('zero_bytes',$msg);
                   13118:     }
                   13119:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13120:     my $getpropath = 1;
1.1021    raeburn  13121:     my ($dirlistref,$listerror) =
                   13122:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13123:     my $found_file = 0;
                   13124:     my $locked_file = 0;
1.991     raeburn  13125:     my @lockers;
                   13126:     my $navmap;
                   13127:     if ($env{'request.course.id'}) {
                   13128:         $navmap = Apache::lonnavmaps::navmap->new();
                   13129:     }
1.1021    raeburn  13130:     if (ref($dirlistref) eq 'ARRAY') {
                   13131:         foreach my $line (@{$dirlistref}) {
                   13132:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13133:             if ($file_name eq $fname){
                   13134:                 $file_name = $path.$file_name;
                   13135:                 if ($group ne '') {
                   13136:                     $file_name = $group.$file_name;
                   13137:                 }
                   13138:                 $found_file = 1;
                   13139:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13140:                     foreach my $lock (@lockers) {
                   13141:                         if (ref($lock) eq 'ARRAY') {
                   13142:                             my ($symb,$crsid) = @{$lock};
                   13143:                             if ($crsid eq $env{'request.course.id'}) {
                   13144:                                 if (ref($navmap)) {
                   13145:                                     my $res = $navmap->getBySymb($symb);
                   13146:                                     foreach my $part (@{$res->parts()}) { 
                   13147:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13148:                                         unless (($slot_status == $res->RESERVED) ||
                   13149:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13150:                                             $locked_file = 1;
                   13151:                                         }
1.991     raeburn  13152:                                     }
1.1021    raeburn  13153:                                 } else {
                   13154:                                     $locked_file = 1;
1.991     raeburn  13155:                                 }
                   13156:                             } else {
                   13157:                                 $locked_file = 1;
                   13158:                             }
                   13159:                         }
1.1021    raeburn  13160:                    }
                   13161:                 } else {
                   13162:                     my @info = split(/\&/,$rest);
                   13163:                     my $currsize = $info[6]/1000;
                   13164:                     if ($currsize < $filesize) {
                   13165:                         my $extra = $filesize - $currsize;
                   13166:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  13167:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13168:                                       &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  13169:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13170:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13171:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13172:                             return ('will_exceed_quota',$msg);
                   13173:                         }
1.984     raeburn  13174:                     }
                   13175:                 }
1.661     raeburn  13176:             }
                   13177:         }
                   13178:     }
                   13179:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  13180:         my $msg = '<p class="LC_warning">'.
                   13181:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   13182:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13183:         return ('will_exceed_quota',$msg);
                   13184:     } elsif ($found_file) {
                   13185:         if ($locked_file) {
1.1075.2.69  raeburn  13186:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13187:             $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  13188:             $msg .= '</p>';
1.661     raeburn  13189:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13190:             return ('file_locked',$msg);
                   13191:         } else {
1.1075.2.69  raeburn  13192:             my $msg = '<p class="LC_error">';
1.984     raeburn  13193:             $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  13194:             $msg .= '</p>';
1.984     raeburn  13195:             return ('existingfile',$msg);
1.661     raeburn  13196:         }
                   13197:     }
                   13198: }
                   13199: 
1.987     raeburn  13200: sub check_for_traversal {
                   13201:     my ($path,$url,$toplevel) = @_;
                   13202:     my @parts=split(/\//,$path);
                   13203:     my $cleanpath;
                   13204:     my $fullpath = $url;
                   13205:     for (my $i=0;$i<@parts;$i++) {
                   13206:         next if ($parts[$i] eq '.');
                   13207:         if ($parts[$i] eq '..') {
                   13208:             $fullpath =~ s{([^/]+/)$}{};
                   13209:         } else {
                   13210:             $fullpath .= $parts[$i].'/';
                   13211:         }
                   13212:     }
                   13213:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13214:         $cleanpath = $1;
                   13215:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13216:         my $curr_toprel = $1;
                   13217:         my @parts = split(/\//,$curr_toprel);
                   13218:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13219:         my @urlparts = split(/\//,$url_toprel);
                   13220:         my $doubledots;
                   13221:         my $startdiff = -1;
                   13222:         for (my $i=0; $i<@urlparts; $i++) {
                   13223:             if ($startdiff == -1) {
                   13224:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13225:                     $startdiff = $i;
                   13226:                     $doubledots .= '../';
                   13227:                 }
                   13228:             } else {
                   13229:                 $doubledots .= '../';
                   13230:             }
                   13231:         }
                   13232:         if ($startdiff > -1) {
                   13233:             $cleanpath = $doubledots;
                   13234:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13235:                 $cleanpath .= $parts[$i].'/';
                   13236:             }
                   13237:         }
                   13238:     }
                   13239:     $cleanpath =~ s{(/)$}{};
                   13240:     return $cleanpath;
                   13241: }
1.31      albertel 13242: 
1.1053    raeburn  13243: sub is_archive_file {
                   13244:     my ($mimetype) = @_;
                   13245:     if (($mimetype eq 'application/octet-stream') ||
                   13246:         ($mimetype eq 'application/x-stuffit') ||
                   13247:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13248:         return 1;
                   13249:     }
                   13250:     return;
                   13251: }
                   13252: 
                   13253: sub decompress_form {
1.1065    raeburn  13254:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13255:     my %lt = &Apache::lonlocal::texthash (
                   13256:         this => 'This file is an archive file.',
1.1067    raeburn  13257:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13258:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13259:         youm => 'You may wish to extract its contents.',
                   13260:         extr => 'Extract contents',
1.1067    raeburn  13261:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13262:         proa => 'Process automatically?',
1.1053    raeburn  13263:         yes  => 'Yes',
                   13264:         no   => 'No',
1.1067    raeburn  13265:         fold => 'Title for folder containing movie',
                   13266:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13267:     );
1.1065    raeburn  13268:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13269:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13270:     my $info = &list_archive_contents($fileloc,\@paths);
                   13271:     if (@paths) {
                   13272:         foreach my $path (@paths) {
                   13273:             $path =~ s{^/}{};
1.1067    raeburn  13274:             if ($path =~ m{^([^/]+)/$}) {
                   13275:                 $topdir = $1;
                   13276:             }
1.1065    raeburn  13277:             if ($path =~ m{^([^/]+)/}) {
                   13278:                 $toplevel{$1} = $path;
                   13279:             } else {
                   13280:                 $toplevel{$path} = $path;
                   13281:             }
                   13282:         }
                   13283:     }
1.1067    raeburn  13284:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  13285:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13286:                         "$topdir/media/",
                   13287:                         "$topdir/media/$topdir.mp4",
                   13288:                         "$topdir/media/FirstFrame.png",
                   13289:                         "$topdir/media/player.swf",
                   13290:                         "$topdir/media/swfobject.js",
                   13291:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  13292:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  13293:                          "$topdir/$topdir.mp4",
                   13294:                          "$topdir/$topdir\_config.xml",
                   13295:                          "$topdir/$topdir\_controller.swf",
                   13296:                          "$topdir/$topdir\_embed.css",
                   13297:                          "$topdir/$topdir\_First_Frame.png",
                   13298:                          "$topdir/$topdir\_player.html",
                   13299:                          "$topdir/$topdir\_Thumbnails.png",
                   13300:                          "$topdir/playerProductInstall.swf",
                   13301:                          "$topdir/scripts/",
                   13302:                          "$topdir/scripts/config_xml.js",
                   13303:                          "$topdir/scripts/handlebars.js",
                   13304:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13305:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13306:                          "$topdir/scripts/modernizr.js",
                   13307:                          "$topdir/scripts/player-min.js",
                   13308:                          "$topdir/scripts/swfobject.js",
                   13309:                          "$topdir/skins/",
                   13310:                          "$topdir/skins/configuration_express.xml",
                   13311:                          "$topdir/skins/express_show/",
                   13312:                          "$topdir/skins/express_show/player-min.css",
                   13313:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  13314:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13315:                          "$topdir/$topdir.mp4",
                   13316:                          "$topdir/$topdir\_config.xml",
                   13317:                          "$topdir/$topdir\_controller.swf",
                   13318:                          "$topdir/$topdir\_embed.css",
                   13319:                          "$topdir/$topdir\_First_Frame.png",
                   13320:                          "$topdir/$topdir\_player.html",
                   13321:                          "$topdir/$topdir\_Thumbnails.png",
                   13322:                          "$topdir/playerProductInstall.swf",
                   13323:                          "$topdir/scripts/",
                   13324:                          "$topdir/scripts/config_xml.js",
                   13325:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13326:                          "$topdir/skins/",
                   13327:                          "$topdir/skins/configuration_express.xml",
                   13328:                          "$topdir/skins/express_show/",
                   13329:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13330:                          "$topdir/skins/express_show/spritesheet.png",
                   13331:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  13332:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13333:         if (@diffs == 0) {
1.1075.2.59  raeburn  13334:             $is_camtasia = 6;
                   13335:         } else {
1.1075.2.81  raeburn  13336:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  13337:             if (@diffs == 0) {
                   13338:                 $is_camtasia = 8;
1.1075.2.81  raeburn  13339:             } else {
                   13340:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13341:                 if (@diffs == 0) {
                   13342:                     $is_camtasia = 8;
                   13343:                 }
1.1075.2.59  raeburn  13344:             }
1.1067    raeburn  13345:         }
                   13346:     }
                   13347:     my $output;
                   13348:     if ($is_camtasia) {
                   13349:         $output = <<"ENDCAM";
                   13350: <script type="text/javascript" language="Javascript">
                   13351: // <![CDATA[
                   13352: 
                   13353: function camtasiaToggle() {
                   13354:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13355:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  13356:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13357:                 document.getElementById('camtasia_titles').style.display='block';
                   13358:             } else {
                   13359:                 document.getElementById('camtasia_titles').style.display='none';
                   13360:             }
                   13361:         }
                   13362:     }
                   13363:     return;
                   13364: }
                   13365: 
                   13366: // ]]>
                   13367: </script>
                   13368: <p>$lt{'camt'}</p>
                   13369: ENDCAM
1.1065    raeburn  13370:     } else {
1.1067    raeburn  13371:         $output = '<p>'.$lt{'this'};
                   13372:         if ($info eq '') {
                   13373:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13374:         } else {
                   13375:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13376:                        '<div><pre>'.$info.'</pre></div>';
                   13377:         }
1.1065    raeburn  13378:     }
1.1067    raeburn  13379:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13380:     my $duplicates;
                   13381:     my $num = 0;
                   13382:     if (ref($dirlist) eq 'ARRAY') {
                   13383:         foreach my $item (@{$dirlist}) {
                   13384:             if (ref($item) eq 'ARRAY') {
                   13385:                 if (exists($toplevel{$item->[0]})) {
                   13386:                     $duplicates .= 
                   13387:                         &start_data_table_row().
                   13388:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13389:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13390:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13391:                         'value="1" />'.&mt('Yes').'</label>'.
                   13392:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13393:                         '<td>'.$item->[0].'</td>';
                   13394:                     if ($item->[2]) {
                   13395:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13396:                     } else {
                   13397:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13398:                     }
                   13399:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13400:                                    '<td>'.
                   13401:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13402:                                    '</td>'.
                   13403:                                    &end_data_table_row();
                   13404:                     $num ++;
                   13405:                 }
                   13406:             }
                   13407:         }
                   13408:     }
                   13409:     my $itemcount;
                   13410:     if (@paths > 0) {
                   13411:         $itemcount = scalar(@paths);
                   13412:     } else {
                   13413:         $itemcount = 1;
                   13414:     }
1.1067    raeburn  13415:     if ($is_camtasia) {
                   13416:         $output .= $lt{'auto'}.'<br />'.
                   13417:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  13418:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13419:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13420:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13421:                    $lt{'no'}.'</label></span><br />'.
                   13422:                    '<div id="camtasia_titles" style="display:block">'.
                   13423:                    &Apache::lonhtmlcommon::start_pick_box().
                   13424:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13425:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13426:                    &Apache::lonhtmlcommon::row_closure().
                   13427:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13428:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13429:                    &Apache::lonhtmlcommon::row_closure(1).
                   13430:                    &Apache::lonhtmlcommon::end_pick_box().
                   13431:                    '</div>';
                   13432:     }
1.1065    raeburn  13433:     $output .= 
                   13434:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13435:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13436:         "\n";
1.1065    raeburn  13437:     if ($duplicates ne '') {
                   13438:         $output .= '<p><span class="LC_warning">'.
                   13439:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13440:                    &start_data_table().
                   13441:                    &start_data_table_header_row().
                   13442:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13443:                    '<th>'.&mt('Name').'</th>'.
                   13444:                    '<th>'.&mt('Type').'</th>'.
                   13445:                    '<th>'.&mt('Size').'</th>'.
                   13446:                    '<th>'.&mt('Last modified').'</th>'.
                   13447:                    &end_data_table_header_row().
                   13448:                    $duplicates.
                   13449:                    &end_data_table().
                   13450:                    '</p>';
                   13451:     }
1.1067    raeburn  13452:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13453:     if (ref($hiddenelements) eq 'HASH') {
                   13454:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13455:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13456:         }
                   13457:     }
                   13458:     $output .= <<"END";
1.1067    raeburn  13459: <br />
1.1053    raeburn  13460: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13461: </form>
                   13462: $noextract
                   13463: END
                   13464:     return $output;
                   13465: }
                   13466: 
1.1065    raeburn  13467: sub decompression_utility {
                   13468:     my ($program) = @_;
                   13469:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13470:     my $location;
                   13471:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13472:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13473:                          '/usr/sbin/') {
                   13474:             if (-x $dir.$program) {
                   13475:                 $location = $dir.$program;
                   13476:                 last;
                   13477:             }
                   13478:         }
                   13479:     }
                   13480:     return $location;
                   13481: }
                   13482: 
                   13483: sub list_archive_contents {
                   13484:     my ($file,$pathsref) = @_;
                   13485:     my (@cmd,$output);
                   13486:     my $needsregexp;
                   13487:     if ($file =~ /\.zip$/) {
                   13488:         @cmd = (&decompression_utility('unzip'),"-l");
                   13489:         $needsregexp = 1;
                   13490:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13491:              ($file =~ /\.tgz$/)) {
                   13492:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13493:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13494:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13495:     } elsif ($file =~ m|\.tar$|) {
                   13496:         @cmd = (&decompression_utility('tar'),"-tf");
                   13497:     }
                   13498:     if (@cmd) {
                   13499:         undef($!);
                   13500:         undef($@);
                   13501:         if (open(my $fh,"-|", @cmd, $file)) {
                   13502:             while (my $line = <$fh>) {
                   13503:                 $output .= $line;
                   13504:                 chomp($line);
                   13505:                 my $item;
                   13506:                 if ($needsregexp) {
                   13507:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13508:                 } else {
                   13509:                     $item = $line;
                   13510:                 }
                   13511:                 if ($item ne '') {
                   13512:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13513:                         push(@{$pathsref},$item);
                   13514:                     } 
                   13515:                 }
                   13516:             }
                   13517:             close($fh);
                   13518:         }
                   13519:     }
                   13520:     return $output;
                   13521: }
                   13522: 
1.1053    raeburn  13523: sub decompress_uploaded_file {
                   13524:     my ($file,$dir) = @_;
                   13525:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13526:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13527:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13528:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13529:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13530:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13531:     my $decompressed = $env{'cgi.decompressed'};
                   13532:     &Apache::lonnet::delenv('cgi.file');
                   13533:     &Apache::lonnet::delenv('cgi.dir');
                   13534:     &Apache::lonnet::delenv('cgi.decompressed');
                   13535:     return ($decompressed,$result);
                   13536: }
                   13537: 
1.1055    raeburn  13538: sub process_decompression {
                   13539:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13540:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13541:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13542:                &mt('Unexpected file path.').'</p>'."\n";
                   13543:     }
                   13544:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13545:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13546:                &mt('Unexpected course context.').'</p>'."\n";
                   13547:     }
                   13548:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13549:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13550:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13551:     }
1.1055    raeburn  13552:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13553:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13554:         $error = &mt('Filename not a supported archive file type.').
                   13555:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13556:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13557:     } else {
                   13558:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13559:         if ($docuhome eq 'no_host') {
                   13560:             $error = &mt('Could not determine home server for course.');
                   13561:         } else {
                   13562:             my @ids=&Apache::lonnet::current_machine_ids();
                   13563:             my $currdir = "$dir_root/$destination";
                   13564:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13565:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13566:                        "$dir_root/$destination";
                   13567:             } else {
                   13568:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13569:                        "$dir_root/$docudom/$docuname/$destination";
                   13570:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13571:                     $error = &mt('Archive file not found.');
                   13572:                 }
                   13573:             }
1.1065    raeburn  13574:             my (@to_overwrite,@to_skip);
                   13575:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13576:                 my $total = $env{'form.archive_overwrite_total'};
                   13577:                 for (my $i=0; $i<$total; $i++) {
                   13578:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13579:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13580:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13581:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13582:                     }
                   13583:                 }
                   13584:             }
                   13585:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13586:             my $numoverwrite = scalar(@to_overwrite);
                   13587:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13588:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13589:             } elsif ($dir eq '') {
1.1055    raeburn  13590:                 $error = &mt('Directory containing archive file unavailable.');
                   13591:             } elsif (!$error) {
1.1065    raeburn  13592:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13593:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13594:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13595:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13596:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13597:                         ($decompressed,$display) =
                   13598:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13599:                         foreach my $item (@to_skip) {
                   13600:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13601:                                 if (-f "$dir/$tempdir/$item") {
                   13602:                                     unlink("$dir/$tempdir/$item");
                   13603:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13604:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13605:                                 }
                   13606:                             }
                   13607:                         }
                   13608:                         foreach my $item (@to_overwrite) {
                   13609:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13610:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13611:                                     if (-f "$dir/$item") {
                   13612:                                         unlink("$dir/$item");
                   13613:                                     } elsif (-d "$dir/$item") {
                   13614:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13615:                                     }
                   13616:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13617:                                 }
1.1065    raeburn  13618:                             }
                   13619:                         }
1.1075.2.128  raeburn  13620:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13621:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13622:                         }
1.1065    raeburn  13623:                     }
                   13624:                 } else {
                   13625:                     ($decompressed,$display) = 
                   13626:                         &decompress_uploaded_file($file,$dir);
                   13627:                 }
1.1055    raeburn  13628:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13629:                     $output = '<p class="LC_info">'.
                   13630:                               &mt('Files extracted successfully from archive.').
                   13631:                               '</p>'."\n";
1.1055    raeburn  13632:                     my ($warning,$result,@contents);
                   13633:                     my ($newdirlistref,$newlisterror) =
                   13634:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13635:                                                  $docuname,1);
                   13636:                     my (%is_dir,%changes,@newitems);
                   13637:                     my $dirptr = 16384;
1.1065    raeburn  13638:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13639:                         foreach my $dir_line (@{$newdirlistref}) {
                   13640:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13641:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13642:                                 push(@newitems,$item);
                   13643:                                 if ($dirptr&$testdir) {
                   13644:                                     $is_dir{$item} = 1;
                   13645:                                 }
                   13646:                                 $changes{$item} = 1;
                   13647:                             }
                   13648:                         }
                   13649:                     }
                   13650:                     if (keys(%changes) > 0) {
                   13651:                         foreach my $item (sort(@newitems)) {
                   13652:                             if ($changes{$item}) {
                   13653:                                 push(@contents,$item);
                   13654:                             }
                   13655:                         }
                   13656:                     }
                   13657:                     if (@contents > 0) {
1.1067    raeburn  13658:                         my $wantform;
                   13659:                         unless ($env{'form.autoextract_camtasia'}) {
                   13660:                             $wantform = 1;
                   13661:                         }
1.1056    raeburn  13662:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13663:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13664:                                                                 $currdir,\%is_dir,
                   13665:                                                                 \%children,\%parent,
1.1056    raeburn  13666:                                                                 \@contents,\%dirorder,
                   13667:                                                                 \%titles,$wantform);
1.1055    raeburn  13668:                         if ($datatable ne '') {
                   13669:                             $output .= &archive_options_form('decompressed',$datatable,
                   13670:                                                              $count,$hiddenelem);
1.1065    raeburn  13671:                             my $startcount = 6;
1.1055    raeburn  13672:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13673:                                                            \%titles,\%children);
1.1055    raeburn  13674:                         }
1.1067    raeburn  13675:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13676:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13677:                             my %displayed;
                   13678:                             my $total = 1;
                   13679:                             $env{'form.archive_directory'} = [];
                   13680:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13681:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13682:                                 $path =~ s{/$}{};
                   13683:                                 my $item;
                   13684:                                 if ($path ne '') {
                   13685:                                     $item = "$path/$titles{$i}";
                   13686:                                 } else {
                   13687:                                     $item = $titles{$i};
                   13688:                                 }
                   13689:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13690:                                 if ($item eq $contents[0]) {
                   13691:                                     push(@{$env{'form.archive_directory'}},$i);
                   13692:                                     $env{'form.archive_'.$i} = 'display';
                   13693:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13694:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13695:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13696:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13697:                                     $env{'form.archive_'.$i} = 'display';
                   13698:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13699:                                     $displayed{'web'} = $i;
                   13700:                                 } else {
1.1075.2.59  raeburn  13701:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13702:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13703:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13704:                                         push(@{$env{'form.archive_directory'}},$i);
                   13705:                                     }
                   13706:                                     $env{'form.archive_'.$i} = 'dependency';
                   13707:                                 }
                   13708:                                 $total ++;
                   13709:                             }
                   13710:                             for (my $i=1; $i<$total; $i++) {
                   13711:                                 next if ($i == $displayed{'web'});
                   13712:                                 next if ($i == $displayed{'folder'});
                   13713:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13714:                             }
                   13715:                             $env{'form.phase'} = 'decompress_cleanup';
                   13716:                             $env{'form.archivedelete'} = 1;
                   13717:                             $env{'form.archive_count'} = $total-1;
                   13718:                             $output .=
                   13719:                                 &process_extracted_files('coursedocs',$docudom,
                   13720:                                                          $docuname,$destination,
                   13721:                                                          $dir_root,$hiddenelem);
                   13722:                         }
1.1055    raeburn  13723:                     } else {
                   13724:                         $warning = &mt('No new items extracted from archive file.');
                   13725:                     }
                   13726:                 } else {
                   13727:                     $output = $display;
                   13728:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13729:                 }
                   13730:             }
                   13731:         }
                   13732:     }
                   13733:     if ($error) {
                   13734:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13735:                    $error.'</p>'."\n";
                   13736:     }
                   13737:     if ($warning) {
                   13738:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13739:     }
                   13740:     return $output;
                   13741: }
                   13742: 
                   13743: sub get_extracted {
1.1056    raeburn  13744:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13745:         $titles,$wantform) = @_;
1.1055    raeburn  13746:     my $count = 0;
                   13747:     my $depth = 0;
                   13748:     my $datatable;
1.1056    raeburn  13749:     my @hierarchy;
1.1055    raeburn  13750:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13751:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13752:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13753:     foreach my $item (@{$contents}) {
                   13754:         $count ++;
1.1056    raeburn  13755:         @{$dirorder->{$count}} = @hierarchy;
                   13756:         $titles->{$count} = $item;
1.1055    raeburn  13757:         &archive_hierarchy($depth,$count,$parent,$children);
                   13758:         if ($wantform) {
                   13759:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13760:                                        $currdir,$depth,$count);
                   13761:         }
                   13762:         if ($is_dir->{$item}) {
                   13763:             $depth ++;
1.1056    raeburn  13764:             push(@hierarchy,$count);
                   13765:             $parent->{$depth} = $count;
1.1055    raeburn  13766:             $datatable .=
                   13767:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13768:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13769:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13770:             $depth --;
1.1056    raeburn  13771:             pop(@hierarchy);
1.1055    raeburn  13772:         }
                   13773:     }
                   13774:     return ($count,$datatable);
                   13775: }
                   13776: 
                   13777: sub recurse_extracted_archive {
1.1056    raeburn  13778:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13779:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13780:     my $result='';
1.1056    raeburn  13781:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13782:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13783:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13784:         return $result;
                   13785:     }
                   13786:     my $dirptr = 16384;
                   13787:     my ($newdirlistref,$newlisterror) =
                   13788:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13789:     if (ref($newdirlistref) eq 'ARRAY') {
                   13790:         foreach my $dir_line (@{$newdirlistref}) {
                   13791:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13792:             unless ($item =~ /^\.+$/) {
                   13793:                 $$count ++;
1.1056    raeburn  13794:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13795:                 $titles->{$$count} = $item;
1.1055    raeburn  13796:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13797: 
1.1055    raeburn  13798:                 my $is_dir;
                   13799:                 if ($dirptr&$testdir) {
                   13800:                     $is_dir = 1;
                   13801:                 }
                   13802:                 if ($wantform) {
                   13803:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13804:                 }
                   13805:                 if ($is_dir) {
                   13806:                     $$depth ++;
1.1056    raeburn  13807:                     push(@{$hierarchy},$$count);
                   13808:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13809:                     $result .=
                   13810:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13811:                                                    $docuname,$depth,$count,
1.1056    raeburn  13812:                                                    $hierarchy,$dirorder,$children,
                   13813:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13814:                     $$depth --;
1.1056    raeburn  13815:                     pop(@{$hierarchy});
1.1055    raeburn  13816:                 }
                   13817:             }
                   13818:         }
                   13819:     }
                   13820:     return $result;
                   13821: }
                   13822: 
                   13823: sub archive_hierarchy {
                   13824:     my ($depth,$count,$parent,$children) =@_;
                   13825:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13826:         if (exists($parent->{$depth})) {
                   13827:              $children->{$parent->{$depth}} .= $count.':';
                   13828:         }
                   13829:     }
                   13830:     return;
                   13831: }
                   13832: 
                   13833: sub archive_row {
                   13834:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13835:     my ($name) = ($item =~ m{([^/]+)$});
                   13836:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13837:                                        'display'    => 'Add as file',
1.1055    raeburn  13838:                                        'dependency' => 'Include as dependency',
                   13839:                                        'discard'    => 'Discard',
                   13840:                                       );
                   13841:     if ($is_dir) {
1.1059    raeburn  13842:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13843:     }
1.1056    raeburn  13844:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13845:     my $offset = 0;
1.1055    raeburn  13846:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13847:         $offset ++;
1.1065    raeburn  13848:         if ($action ne 'display') {
                   13849:             $offset ++;
                   13850:         }  
1.1055    raeburn  13851:         $output .= '<td><span class="LC_nobreak">'.
                   13852:                    '<label><input type="radio" name="archive_'.$count.
                   13853:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13854:         my $text = $choices{$action};
                   13855:         if ($is_dir) {
                   13856:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13857:             if ($action eq 'display') {
1.1059    raeburn  13858:                 $text = &mt('Add as folder');
1.1055    raeburn  13859:             }
1.1056    raeburn  13860:         } else {
                   13861:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13862: 
                   13863:         }
                   13864:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13865:         if ($action eq 'dependency') {
                   13866:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13867:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13868:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13869:                        '<option value=""></option>'."\n".
                   13870:                        '</select>'."\n".
                   13871:                        '</div>';
1.1059    raeburn  13872:         } elsif ($action eq 'display') {
                   13873:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13874:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13875:                        '</div>';
1.1055    raeburn  13876:         }
1.1056    raeburn  13877:         $output .= '</td>';
1.1055    raeburn  13878:     }
                   13879:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13880:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13881:     for (my $i=0; $i<$depth; $i++) {
                   13882:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13883:     }
                   13884:     if ($is_dir) {
                   13885:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13886:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13887:     } else {
                   13888:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13889:     }
                   13890:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13891:                &end_data_table_row();
                   13892:     return $output;
                   13893: }
                   13894: 
                   13895: sub archive_options_form {
1.1065    raeburn  13896:     my ($form,$display,$count,$hiddenelem) = @_;
                   13897:     my %lt = &Apache::lonlocal::texthash(
                   13898:                perm => 'Permanently remove archive file?',
                   13899:                hows => 'How should each extracted item be incorporated in the course?',
                   13900:                cont => 'Content actions for all',
                   13901:                addf => 'Add as folder/file',
                   13902:                incd => 'Include as dependency for a displayed file',
                   13903:                disc => 'Discard',
                   13904:                no   => 'No',
                   13905:                yes  => 'Yes',
                   13906:                save => 'Save',
                   13907:     );
                   13908:     my $output = <<"END";
                   13909: <form name="$form" method="post" action="">
                   13910: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13911: <label>
                   13912:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13913: </label>
                   13914: &nbsp;
                   13915: <label>
                   13916:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13917: </span>
                   13918: </p>
                   13919: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13920: <br />$lt{'hows'}
                   13921: <div class="LC_columnSection">
                   13922:   <fieldset>
                   13923:     <legend>$lt{'cont'}</legend>
                   13924:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13925:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13926:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13927:   </fieldset>
                   13928: </div>
                   13929: END
                   13930:     return $output.
1.1055    raeburn  13931:            &start_data_table()."\n".
1.1065    raeburn  13932:            $display."\n".
1.1055    raeburn  13933:            &end_data_table()."\n".
                   13934:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13935:            $hiddenelem.
1.1065    raeburn  13936:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13937:            '</form>';
                   13938: }
                   13939: 
                   13940: sub archive_javascript {
1.1056    raeburn  13941:     my ($startcount,$numitems,$titles,$children) = @_;
                   13942:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13943:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13944:     my $scripttag = <<START;
                   13945: <script type="text/javascript">
                   13946: // <![CDATA[
                   13947: 
                   13948: function checkAll(form,prefix) {
                   13949:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13950:     for (var i=0; i < form.elements.length; i++) {
                   13951:         var id = form.elements[i].id;
                   13952:         if ((id != '') && (id != undefined)) {
                   13953:             if (idstr.test(id)) {
                   13954:                 if (form.elements[i].type == 'radio') {
                   13955:                     form.elements[i].checked = true;
1.1056    raeburn  13956:                     var nostart = i-$startcount;
1.1059    raeburn  13957:                     var offset = nostart%7;
                   13958:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13959:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13960:                 }
                   13961:             }
                   13962:         }
                   13963:     }
                   13964: }
                   13965: 
                   13966: function propagateCheck(form,count) {
                   13967:     if (count > 0) {
1.1059    raeburn  13968:         var startelement = $startcount + ((count-1) * 7);
                   13969:         for (var j=1; j<6; j++) {
                   13970:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13971:                 var item = startelement + j; 
                   13972:                 if (form.elements[item].type == 'radio') {
                   13973:                     if (form.elements[item].checked) {
                   13974:                         containerCheck(form,count,j);
                   13975:                         break;
                   13976:                     }
1.1055    raeburn  13977:                 }
                   13978:             }
                   13979:         }
                   13980:     }
                   13981: }
                   13982: 
                   13983: numitems = $numitems
1.1056    raeburn  13984: var titles = new Array(numitems);
                   13985: var parents = new Array(numitems);
1.1055    raeburn  13986: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13987:     parents[i] = new Array;
1.1055    raeburn  13988: }
1.1059    raeburn  13989: var maintitle = '$maintitle';
1.1055    raeburn  13990: 
                   13991: START
                   13992: 
1.1056    raeburn  13993:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13994:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13995:         for (my $i=0; $i<@contents; $i ++) {
                   13996:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13997:         }
                   13998:     }
                   13999: 
1.1056    raeburn  14000:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14001:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14002:     }
                   14003: 
1.1055    raeburn  14004:     $scripttag .= <<END;
                   14005: 
                   14006: function containerCheck(form,count,offset) {
                   14007:     if (count > 0) {
1.1056    raeburn  14008:         dependencyCheck(form,count,offset);
1.1059    raeburn  14009:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14010:         form.elements[item].checked = true;
                   14011:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14012:             if (parents[count].length > 0) {
                   14013:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14014:                     containerCheck(form,parents[count][j],offset);
                   14015:                 }
                   14016:             }
                   14017:         }
                   14018:     }
                   14019: }
                   14020: 
                   14021: function dependencyCheck(form,count,offset) {
                   14022:     if (count > 0) {
1.1059    raeburn  14023:         var chosen = (offset+$startcount)+7*(count-1);
                   14024:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14025:         var currtype = form.elements[depitem].type;
                   14026:         if (form.elements[chosen].value == 'dependency') {
                   14027:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14028:             form.elements[depitem].options.length = 0;
                   14029:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  14030:             for (var i=1; i<=numitems; i++) {
                   14031:                 if (i == count) {
                   14032:                     continue;
                   14033:                 }
1.1059    raeburn  14034:                 var startelement = $startcount + (i-1) * 7;
                   14035:                 for (var j=1; j<6; j++) {
                   14036:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14037:                         var item = startelement + j;
                   14038:                         if (form.elements[item].type == 'radio') {
                   14039:                             if (form.elements[item].checked) {
                   14040:                                 if (form.elements[item].value == 'display') {
                   14041:                                     var n = form.elements[depitem].options.length;
                   14042:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14043:                                 }
                   14044:                             }
                   14045:                         }
                   14046:                     }
                   14047:                 }
                   14048:             }
                   14049:         } else {
                   14050:             document.getElementById('arc_depon_'+count).style.display='none';
                   14051:             form.elements[depitem].options.length = 0;
                   14052:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14053:         }
1.1059    raeburn  14054:         titleCheck(form,count,offset);
1.1056    raeburn  14055:     }
                   14056: }
                   14057: 
                   14058: function propagateSelect(form,count,offset) {
                   14059:     if (count > 0) {
1.1065    raeburn  14060:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14061:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14062:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14063:             if (parents[count].length > 0) {
                   14064:                 for (var j=0; j<parents[count].length; j++) {
                   14065:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14066:                 }
                   14067:             }
                   14068:         }
                   14069:     }
                   14070: }
1.1056    raeburn  14071: 
                   14072: function containerSelect(form,count,offset,picked) {
                   14073:     if (count > 0) {
1.1065    raeburn  14074:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14075:         if (form.elements[item].type == 'radio') {
                   14076:             if (form.elements[item].value == 'dependency') {
                   14077:                 if (form.elements[item+1].type == 'select-one') {
                   14078:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14079:                         if (form.elements[item+1].options[i].value == picked) {
                   14080:                             form.elements[item+1].selectedIndex = i;
                   14081:                             break;
                   14082:                         }
                   14083:                     }
                   14084:                 }
                   14085:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14086:                     if (parents[count].length > 0) {
                   14087:                         for (var j=0; j<parents[count].length; j++) {
                   14088:                             containerSelect(form,parents[count][j],offset,picked);
                   14089:                         }
                   14090:                     }
                   14091:                 }
                   14092:             }
                   14093:         }
                   14094:     }
                   14095: }
                   14096: 
1.1059    raeburn  14097: function titleCheck(form,count,offset) {
                   14098:     if (count > 0) {
                   14099:         var chosen = (offset+$startcount)+7*(count-1);
                   14100:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14101:         var currtype = form.elements[depitem].type;
                   14102:         if (form.elements[chosen].value == 'display') {
                   14103:             document.getElementById('arc_title_'+count).style.display='block';
                   14104:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14105:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14106:             }
                   14107:         } else {
                   14108:             document.getElementById('arc_title_'+count).style.display='none';
                   14109:             if (currtype == 'text') { 
                   14110:                 document.getElementById('archive_title_'+count).value='';
                   14111:             }
                   14112:         }
                   14113:     }
                   14114:     return;
                   14115: }
                   14116: 
1.1055    raeburn  14117: // ]]>
                   14118: </script>
                   14119: END
                   14120:     return $scripttag;
                   14121: }
                   14122: 
                   14123: sub process_extracted_files {
1.1067    raeburn  14124:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14125:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  14126:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14127:     my @ids=&Apache::lonnet::current_machine_ids();
                   14128:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14129:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14130:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14131:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14132:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14133:         $pathtocheck = "$dir_root/$destination";
                   14134:         $dir = $dir_root;
                   14135:         $ishome = 1;
                   14136:     } else {
                   14137:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14138:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  14139:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14140:     }
                   14141:     my $currdir = "$dir_root/$destination";
                   14142:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14143:     if ($env{'form.folderpath'}) {
                   14144:         my @items = split('&',$env{'form.folderpath'});
                   14145:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  14146:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14147:             $containers{'0'}='page';
                   14148:         } else {
                   14149:             $containers{'0'}='sequence';
                   14150:         }
1.1055    raeburn  14151:     }
                   14152:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14153:     if ($numitems) {
                   14154:         for (my $i=1; $i<=$numitems; $i++) {
                   14155:             my $path = $env{'form.archive_content_'.$i};
                   14156:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14157:                 my $item = $1;
                   14158:                 $toplevelitems{$item} = $i;
                   14159:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14160:                     $is_dir{$item} = 1;
                   14161:                 }
                   14162:             }
                   14163:         }
                   14164:     }
1.1067    raeburn  14165:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14166:     if (keys(%toplevelitems) > 0) {
                   14167:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14168:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14169:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14170:     }
1.1066    raeburn  14171:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14172:     if ($numitems) {
                   14173:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  14174:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14175:             my $path = $env{'form.archive_content_'.$i};
                   14176:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14177:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14178:                     if ($prefix ne '' && $path ne '') {
                   14179:                         if (-e $prefix.$path) {
1.1066    raeburn  14180:                             if ((@archdirs > 0) && 
                   14181:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14182:                                 $todeletedir{$prefix.$path} = 1;
                   14183:                             } else {
                   14184:                                 $todelete{$prefix.$path} = 1;
                   14185:                             }
1.1055    raeburn  14186:                         }
                   14187:                     }
                   14188:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14189:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14190:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14191:                     $docstitle = $env{'form.archive_title_'.$i};
                   14192:                     if ($docstitle eq '') {
                   14193:                         $docstitle = $title;
                   14194:                     }
1.1055    raeburn  14195:                     $outer = 0;
1.1056    raeburn  14196:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14197:                         if (@{$dirorder{$i}} > 0) {
                   14198:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14199:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14200:                                     $outer = $item;
                   14201:                                     last;
                   14202:                                 }
                   14203:                             }
                   14204:                         }
                   14205:                     }
                   14206:                     my ($errtext,$fatal) = 
                   14207:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14208:                                                '/'.$folders{$outer}.'.'.
                   14209:                                                $containers{$outer});
                   14210:                     next if ($fatal);
                   14211:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14212:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14213:                             $mapinner{$i} = time;
1.1055    raeburn  14214:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14215:                             $containers{$i} = 'sequence';
                   14216:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14217:                                       $folders{$i}.'.'.$containers{$i};
                   14218:                             my $newidx = &LONCAPA::map::getresidx();
                   14219:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14220:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14221:                             push(@LONCAPA::map::order,$newidx);
                   14222:                             my ($outtext,$errtext) =
                   14223:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14224:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  14225:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14226:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14227:                             unless ($errtext) {
1.1075.2.128  raeburn  14228:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14229:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   14230:                                             '</li>'."\n";
1.1067    raeburn  14231:                             }
1.1055    raeburn  14232:                         }
                   14233:                     } else {
                   14234:                         if ($context eq 'coursedocs') {
                   14235:                             my $newidx=&LONCAPA::map::getresidx();
                   14236:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14237:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14238:                                       $title;
1.1075.2.161.  .13(raeb 14239:-23):                             if (($outer !~ /\D/) &&
                   14240:-23):                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14241:-23):                                 ($newidx !~ /\D/)) {
1.1075.2.128  raeburn  14242:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14243:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  14244:                                 }
1.1075.2.128  raeburn  14245:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14246:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14247:                                 }
                   14248:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14249:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14250:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14251:                                         unless ($ishome) {
                   14252:                                             my $fetch = "$newdest{$i}/$title";
                   14253:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14254:                                             $prompttofetch{$fetch} = 1;
                   14255:                                         }
                   14256:                                    }
                   14257:                                 }
                   14258:                                 $LONCAPA::map::resources[$newidx]=
                   14259:                                     $docstitle.':'.$url.':false:normal:res';
                   14260:                                 push(@LONCAPA::map::order, $newidx);
                   14261:                                 my ($outtext,$errtext)=
                   14262:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14263:                                                             $docuname.'/'.$folders{$outer}.
                   14264:                                                             '.'.$containers{$outer},1,1);
                   14265:                                 unless ($errtext) {
                   14266:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14267:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14268:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14269:                                                    '</li>'."\n";
                   14270:                                     }
1.1067    raeburn  14271:                                 }
1.1075.2.128  raeburn  14272:                             } else {
                   14273:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14274:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  14275:                             }
1.1055    raeburn  14276:                         }
                   14277:                     }
1.1075.2.11  raeburn  14278:                 }
                   14279:             } else {
1.1075.2.128  raeburn  14280:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14281:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  14282:             }
                   14283:         }
                   14284:         for (my $i=1; $i<=$numitems; $i++) {
                   14285:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14286:             my $path = $env{'form.archive_content_'.$i};
                   14287:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14288:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14289:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14290:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14291:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14292:                         my ($itemidx,$fullpath,$relpath);
                   14293:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14294:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14295:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  14296:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14297:                                     $itemidx = $j;
1.1056    raeburn  14298:                                 }
                   14299:                             }
1.1075.2.11  raeburn  14300:                         }
                   14301:                         if ($itemidx eq '') {
                   14302:                             $itemidx =  0;
                   14303:                         }
                   14304:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14305:                             if ($mapinner{$referrer{$i}}) {
                   14306:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14307:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14308:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14309:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14310:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14311:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14312:                                             if (!-e $fullpath) {
                   14313:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14314:                                             }
                   14315:                                         }
1.1075.2.11  raeburn  14316:                                     } else {
                   14317:                                         last;
1.1056    raeburn  14318:                                     }
1.1075.2.11  raeburn  14319:                                 }
                   14320:                             }
                   14321:                         } elsif ($newdest{$referrer{$i}}) {
                   14322:                             $fullpath = $newdest{$referrer{$i}};
                   14323:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14324:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14325:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14326:                                     last;
                   14327:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14328:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14329:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14330:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14331:                                         if (!-e $fullpath) {
                   14332:                                             mkdir($fullpath,0755);
1.1056    raeburn  14333:                                         }
                   14334:                                     }
1.1075.2.11  raeburn  14335:                                 } else {
                   14336:                                     last;
1.1056    raeburn  14337:                                 }
1.1075.2.11  raeburn  14338:                             }
                   14339:                         }
                   14340:                         if ($fullpath ne '') {
                   14341:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  14342:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14343:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14344:                                 }
1.1075.2.11  raeburn  14345:                             }
                   14346:                             if (-e "$fullpath/$title") {
                   14347:                                 my $showpath;
                   14348:                                 if ($relpath ne '') {
                   14349:                                     $showpath = "$relpath/$title";
                   14350:                                 } else {
                   14351:                                     $showpath = "/$title";
1.1056    raeburn  14352:                                 }
1.1075.2.128  raeburn  14353:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14354:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14355:                                            '</li>'."\n";
                   14356:                                 unless ($ishome) {
                   14357:                                     my $fetch = "$fullpath/$title";
                   14358:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   14359:                                     $prompttofetch{$fetch} = 1;
                   14360:                                 }
1.1055    raeburn  14361:                             }
                   14362:                         }
                   14363:                     }
1.1075.2.11  raeburn  14364:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14365:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  14366:                                     &HTML::Entities::encode($path,'<>&"'),
                   14367:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14368:                                 '<br />';
1.1055    raeburn  14369:                 }
                   14370:             } else {
1.1075.2.128  raeburn  14371:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14372:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14373:             }
                   14374:         }
                   14375:         if (keys(%todelete)) {
                   14376:             foreach my $key (keys(%todelete)) {
                   14377:                 unlink($key);
1.1066    raeburn  14378:             }
                   14379:         }
                   14380:         if (keys(%todeletedir)) {
                   14381:             foreach my $key (keys(%todeletedir)) {
                   14382:                 rmdir($key);
                   14383:             }
                   14384:         }
                   14385:         foreach my $dir (sort(keys(%is_dir))) {
                   14386:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14387:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14388:             }
                   14389:         }
1.1067    raeburn  14390:         if ($result ne '') {
                   14391:             $output .= '<ul>'."\n".
                   14392:                        $result."\n".
                   14393:                        '</ul>';
                   14394:         }
                   14395:         unless ($ishome) {
                   14396:             my $replicationfail;
                   14397:             foreach my $item (keys(%prompttofetch)) {
                   14398:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14399:                 unless ($fetchresult eq 'ok') {
                   14400:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14401:                 }
                   14402:             }
                   14403:             if ($replicationfail) {
                   14404:                 $output .= '<p class="LC_error">'.
                   14405:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14406:                            $replicationfail.
                   14407:                            '</ul></p>';
                   14408:             }
                   14409:         }
1.1055    raeburn  14410:     } else {
                   14411:         $warning = &mt('No items found in archive.');
                   14412:     }
                   14413:     if ($error) {
                   14414:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14415:                    $error.'</p>'."\n";
                   14416:     }
                   14417:     if ($warning) {
                   14418:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14419:     }
                   14420:     return $output;
                   14421: }
                   14422: 
1.1066    raeburn  14423: sub cleanup_empty_dirs {
                   14424:     my ($path) = @_;
                   14425:     if (($path ne '') && (-d $path)) {
                   14426:         if (opendir(my $dirh,$path)) {
                   14427:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14428:             my $numitems = 0;
                   14429:             foreach my $item (@dircontents) {
                   14430:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  14431:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14432:                     if (-e "$path/$item") {
                   14433:                         $numitems ++;
                   14434:                     }
                   14435:                 } else {
                   14436:                     $numitems ++;
                   14437:                 }
                   14438:             }
                   14439:             if ($numitems == 0) {
                   14440:                 rmdir($path);
                   14441:             }
                   14442:             closedir($dirh);
                   14443:         }
                   14444:     }
                   14445:     return;
                   14446: }
                   14447: 
1.41      ng       14448: =pod
1.45      matthew  14449: 
1.1075.2.56  raeburn  14450: =item * &get_folder_hierarchy()
1.1068    raeburn  14451: 
                   14452: Provides hierarchy of names of folders/sub-folders containing the current
                   14453: item,
                   14454: 
                   14455: Inputs: 3
                   14456:      - $navmap - navmaps object
                   14457: 
                   14458:      - $map - url for map (either the trigger itself, or map containing
                   14459:                            the resource, which is the trigger).
                   14460: 
                   14461:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14462: 
                   14463: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14464: 
                   14465: =cut
                   14466: 
                   14467: sub get_folder_hierarchy {
                   14468:     my ($navmap,$map,$showitem) = @_;
                   14469:     my @pathitems;
                   14470:     if (ref($navmap)) {
                   14471:         my $mapres = $navmap->getResourceByUrl($map);
                   14472:         if (ref($mapres)) {
                   14473:             my $pcslist = $mapres->map_hierarchy();
                   14474:             if ($pcslist ne '') {
                   14475:                 my @pcs = split(/,/,$pcslist);
                   14476:                 foreach my $pc (@pcs) {
                   14477:                     if ($pc == 1) {
1.1075.2.38  raeburn  14478:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14479:                     } else {
                   14480:                         my $res = $navmap->getByMapPc($pc);
                   14481:                         if (ref($res)) {
                   14482:                             my $title = $res->compTitle();
                   14483:                             $title =~ s/\W+/_/g;
                   14484:                             if ($title ne '') {
                   14485:                                 push(@pathitems,$title);
                   14486:                             }
                   14487:                         }
                   14488:                     }
                   14489:                 }
                   14490:             }
1.1071    raeburn  14491:             if ($showitem) {
                   14492:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  14493:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14494:                 } else {
                   14495:                     my $maptitle = $mapres->compTitle();
                   14496:                     $maptitle =~ s/\W+/_/g;
                   14497:                     if ($maptitle ne '') {
                   14498:                         push(@pathitems,$maptitle);
                   14499:                     }
1.1068    raeburn  14500:                 }
                   14501:             }
                   14502:         }
                   14503:     }
                   14504:     return @pathitems;
                   14505: }
                   14506: 
                   14507: =pod
                   14508: 
1.1015    raeburn  14509: =item * &get_turnedin_filepath()
                   14510: 
                   14511: Determines path in a user's portfolio file for storage of files uploaded
                   14512: to a specific essayresponse or dropbox item.
                   14513: 
                   14514: Inputs: 3 required + 1 optional.
                   14515: $symb is symb for resource, $uname and $udom are for current user (required).
                   14516: $caller is optional (can be "submission", if routine is called when storing
                   14517: an upoaded file when "Submit Answer" button was pressed).
                   14518: 
                   14519: Returns array containing $path and $multiresp. 
                   14520: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14521: than one file upload item.  Callers of routine should append partid as a 
                   14522: subdirectory to $path in cases where $multiresp is 1.
                   14523: 
                   14524: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14525: 
                   14526: =cut
                   14527: 
                   14528: sub get_turnedin_filepath {
                   14529:     my ($symb,$uname,$udom,$caller) = @_;
                   14530:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14531:     my $turnindir;
                   14532:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14533:     $turnindir = $userhash{'turnindir'};
                   14534:     my ($path,$multiresp);
                   14535:     if ($turnindir eq '') {
                   14536:         if ($caller eq 'submission') {
                   14537:             $turnindir = &mt('turned in');
                   14538:             $turnindir =~ s/\W+/_/g;
                   14539:             my %newhash = (
                   14540:                             'turnindir' => $turnindir,
                   14541:                           );
                   14542:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14543:         }
                   14544:     }
                   14545:     if ($turnindir ne '') {
                   14546:         $path = '/'.$turnindir.'/';
                   14547:         my ($multipart,$turnin,@pathitems);
                   14548:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14549:         if (defined($navmap)) {
                   14550:             my $mapres = $navmap->getResourceByUrl($map);
                   14551:             if (ref($mapres)) {
                   14552:                 my $pcslist = $mapres->map_hierarchy();
                   14553:                 if ($pcslist ne '') {
                   14554:                     foreach my $pc (split(/,/,$pcslist)) {
                   14555:                         my $res = $navmap->getByMapPc($pc);
                   14556:                         if (ref($res)) {
                   14557:                             my $title = $res->compTitle();
                   14558:                             $title =~ s/\W+/_/g;
                   14559:                             if ($title ne '') {
1.1075.2.48  raeburn  14560:                                 if (($pc > 1) && (length($title) > 12)) {
                   14561:                                     $title = substr($title,0,12);
                   14562:                                 }
1.1015    raeburn  14563:                                 push(@pathitems,$title);
                   14564:                             }
                   14565:                         }
                   14566:                     }
                   14567:                 }
                   14568:                 my $maptitle = $mapres->compTitle();
                   14569:                 $maptitle =~ s/\W+/_/g;
                   14570:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14571:                     if (length($maptitle) > 12) {
                   14572:                         $maptitle = substr($maptitle,0,12);
                   14573:                     }
1.1015    raeburn  14574:                     push(@pathitems,$maptitle);
                   14575:                 }
                   14576:                 unless ($env{'request.state'} eq 'construct') {
                   14577:                     my $res = $navmap->getBySymb($symb);
                   14578:                     if (ref($res)) {
                   14579:                         my $partlist = $res->parts();
                   14580:                         my $totaluploads = 0;
                   14581:                         if (ref($partlist) eq 'ARRAY') {
                   14582:                             foreach my $part (@{$partlist}) {
                   14583:                                 my @types = $res->responseType($part);
                   14584:                                 my @ids = $res->responseIds($part);
                   14585:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14586:                                     if ($types[$i] eq 'essay') {
                   14587:                                         my $partid = $part.'_'.$ids[$i];
                   14588:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14589:                                             $totaluploads ++;
                   14590:                                         }
                   14591:                                     }
                   14592:                                 }
                   14593:                             }
                   14594:                             if ($totaluploads > 1) {
                   14595:                                 $multiresp = 1;
                   14596:                             }
                   14597:                         }
                   14598:                     }
                   14599:                 }
                   14600:             } else {
                   14601:                 return;
                   14602:             }
                   14603:         } else {
                   14604:             return;
                   14605:         }
                   14606:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14607:         $restitle =~ s/\W+/_/g;
                   14608:         if ($restitle eq '') {
                   14609:             $restitle = ($resurl =~ m{/[^/]+$});
                   14610:             if ($restitle eq '') {
                   14611:                 $restitle = time;
                   14612:             }
                   14613:         }
1.1075.2.48  raeburn  14614:         if (length($restitle) > 12) {
                   14615:             $restitle = substr($restitle,0,12);
                   14616:         }
1.1015    raeburn  14617:         push(@pathitems,$restitle);
                   14618:         $path .= join('/',@pathitems);
                   14619:     }
                   14620:     return ($path,$multiresp);
                   14621: }
                   14622: 
                   14623: =pod
                   14624: 
1.464     albertel 14625: =back
1.41      ng       14626: 
1.112     bowersj2 14627: =head1 CSV Upload/Handling functions
1.38      albertel 14628: 
1.41      ng       14629: =over 4
                   14630: 
1.648     raeburn  14631: =item * &upfile_store($r)
1.41      ng       14632: 
                   14633: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14634: needs $env{'form.upfile'}
1.41      ng       14635: returns $datatoken to be put into hidden field
                   14636: 
                   14637: =cut
1.31      albertel 14638: 
                   14639: sub upfile_store {
                   14640:     my $r=shift;
1.258     albertel 14641:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14642:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14643:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14644:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14645: 
1.1075.2.128  raeburn  14646:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14647:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14648:                                      time.'_'.$$);
                   14649:     return if ($datatoken eq '');
                   14650: 
1.31      albertel 14651:     {
1.158     raeburn  14652:         my $datafile = $r->dir_config('lonDaemons').
                   14653:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14654:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14655:             print $fh $env{'form.upfile'};
1.158     raeburn  14656:             close($fh);
                   14657:         }
1.31      albertel 14658:     }
                   14659:     return $datatoken;
                   14660: }
                   14661: 
1.56      matthew  14662: =pod
                   14663: 
1.1075.2.128  raeburn  14664: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14665: 
                   14666: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14667: $datatoken is the name to assign to the temporary file.
1.258     albertel 14668: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14669: 
                   14670: =cut
1.31      albertel 14671: 
                   14672: sub load_tmp_file {
1.1075.2.128  raeburn  14673:     my ($r,$datatoken) = @_;
                   14674:     return if ($datatoken eq '');
1.31      albertel 14675:     my @studentdata=();
                   14676:     {
1.158     raeburn  14677:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14678:                               '/tmp/'.$datatoken.'.tmp';
                   14679:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14680:             @studentdata=<$fh>;
                   14681:             close($fh);
                   14682:         }
1.31      albertel 14683:     }
1.258     albertel 14684:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14685: }
                   14686: 
1.1075.2.128  raeburn  14687: sub valid_datatoken {
                   14688:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14689:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14690:         return $datatoken;
                   14691:     }
                   14692:     return;
                   14693: }
                   14694: 
1.56      matthew  14695: =pod
                   14696: 
1.648     raeburn  14697: =item * &upfile_record_sep()
1.41      ng       14698: 
                   14699: Separate uploaded file into records
                   14700: returns array of records,
1.258     albertel 14701: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14702: 
                   14703: =cut
1.31      albertel 14704: 
                   14705: sub upfile_record_sep {
1.258     albertel 14706:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14707:     } else {
1.248     albertel 14708: 	my @records;
1.258     albertel 14709: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14710: 	    if ($line=~/^\s*$/) { next; }
                   14711: 	    push(@records,$line);
                   14712: 	}
                   14713: 	return @records;
1.31      albertel 14714:     }
                   14715: }
                   14716: 
1.56      matthew  14717: =pod
                   14718: 
1.648     raeburn  14719: =item * &record_sep($record)
1.41      ng       14720: 
1.258     albertel 14721: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14722: 
                   14723: =cut
                   14724: 
1.263     www      14725: sub takeleft {
                   14726:     my $index=shift;
                   14727:     return substr('0000'.$index,-4,4);
                   14728: }
                   14729: 
1.31      albertel 14730: sub record_sep {
                   14731:     my $record=shift;
                   14732:     my %components=();
1.258     albertel 14733:     if ($env{'form.upfiletype'} eq 'xml') {
                   14734:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14735:         my $i=0;
1.356     albertel 14736:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14737:             $field=~s/^(\"|\')//;
                   14738:             $field=~s/(\"|\')$//;
1.263     www      14739:             $components{&takeleft($i)}=$field;
1.31      albertel 14740:             $i++;
                   14741:         }
1.258     albertel 14742:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14743:         my $i=0;
1.356     albertel 14744:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14745:             $field=~s/^(\"|\')//;
                   14746:             $field=~s/(\"|\')$//;
1.263     www      14747:             $components{&takeleft($i)}=$field;
1.31      albertel 14748:             $i++;
                   14749:         }
                   14750:     } else {
1.561     www      14751:         my $separator=',';
1.480     banghart 14752:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14753:             $separator=';';
1.480     banghart 14754:         }
1.31      albertel 14755:         my $i=0;
1.561     www      14756: # the character we are looking for to indicate the end of a quote or a record 
                   14757:         my $looking_for=$separator;
                   14758: # do not add the characters to the fields
                   14759:         my $ignore=0;
                   14760: # we just encountered a separator (or the beginning of the record)
                   14761:         my $just_found_separator=1;
                   14762: # store the field we are working on here
                   14763:         my $field='';
                   14764: # work our way through all characters in record
                   14765:         foreach my $character ($record=~/(.)/g) {
                   14766:             if ($character eq $looking_for) {
                   14767:                if ($character ne $separator) {
                   14768: # Found the end of a quote, again looking for separator
                   14769:                   $looking_for=$separator;
                   14770:                   $ignore=1;
                   14771:                } else {
                   14772: # Found a separator, store away what we got
                   14773:                   $components{&takeleft($i)}=$field;
                   14774: 	          $i++;
                   14775:                   $just_found_separator=1;
                   14776:                   $ignore=0;
                   14777:                   $field='';
                   14778:                }
                   14779:                next;
                   14780:             }
                   14781: # single or double quotation marks after a separator indicate beginning of a quote
                   14782: # we are now looking for the end of the quote and need to ignore separators
                   14783:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14784:                $looking_for=$character;
                   14785:                next;
                   14786:             }
                   14787: # ignore would be true after we reached the end of a quote
                   14788:             if ($ignore) { next; }
                   14789:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14790:             $field.=$character;
                   14791:             $just_found_separator=0; 
1.31      albertel 14792:         }
1.561     www      14793: # catch the very last entry, since we never encountered the separator
                   14794:         $components{&takeleft($i)}=$field;
1.31      albertel 14795:     }
                   14796:     return %components;
                   14797: }
                   14798: 
1.144     matthew  14799: ######################################################
                   14800: ######################################################
                   14801: 
1.56      matthew  14802: =pod
                   14803: 
1.648     raeburn  14804: =item * &upfile_select_html()
1.41      ng       14805: 
1.144     matthew  14806: Return HTML code to select a file from the users machine and specify 
                   14807: the file type.
1.41      ng       14808: 
                   14809: =cut
                   14810: 
1.144     matthew  14811: ######################################################
                   14812: ######################################################
1.31      albertel 14813: sub upfile_select_html {
1.144     matthew  14814:     my %Types = (
                   14815:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14816:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14817:                  space => &mt('Space separated'),
                   14818:                  tab   => &mt('Tabulator separated'),
                   14819: #                 xml   => &mt('HTML/XML'),
                   14820:                  );
                   14821:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14822:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14823:     foreach my $type (sort(keys(%Types))) {
                   14824:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14825:     }
                   14826:     $Str .= "</select>\n";
                   14827:     return $Str;
1.31      albertel 14828: }
                   14829: 
1.301     albertel 14830: sub get_samples {
                   14831:     my ($records,$toget) = @_;
                   14832:     my @samples=({});
                   14833:     my $got=0;
                   14834:     foreach my $rec (@$records) {
                   14835: 	my %temp = &record_sep($rec);
                   14836: 	if (! grep(/\S/, values(%temp))) { next; }
                   14837: 	if (%temp) {
                   14838: 	    $samples[$got]=\%temp;
                   14839: 	    $got++;
                   14840: 	    if ($got == $toget) { last; }
                   14841: 	}
                   14842:     }
                   14843:     return \@samples;
                   14844: }
                   14845: 
1.144     matthew  14846: ######################################################
                   14847: ######################################################
                   14848: 
1.56      matthew  14849: =pod
                   14850: 
1.648     raeburn  14851: =item * &csv_print_samples($r,$records)
1.41      ng       14852: 
                   14853: Prints a table of sample values from each column uploaded $r is an
                   14854: Apache Request ref, $records is an arrayref from
                   14855: &Apache::loncommon::upfile_record_sep
                   14856: 
                   14857: =cut
                   14858: 
1.144     matthew  14859: ######################################################
                   14860: ######################################################
1.31      albertel 14861: sub csv_print_samples {
                   14862:     my ($r,$records) = @_;
1.662     bisitz   14863:     my $samples = &get_samples($records,5);
1.301     albertel 14864: 
1.594     raeburn  14865:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14866:               &start_data_table_header_row());
1.356     albertel 14867:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14868:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14869:     $r->print(&end_data_table_header_row());
1.301     albertel 14870:     foreach my $hash (@$samples) {
1.594     raeburn  14871: 	$r->print(&start_data_table_row());
1.356     albertel 14872: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14873: 	    $r->print('<td>');
1.356     albertel 14874: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14875: 	    $r->print('</td>');
                   14876: 	}
1.594     raeburn  14877: 	$r->print(&end_data_table_row());
1.31      albertel 14878:     }
1.594     raeburn  14879:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14880: }
                   14881: 
1.144     matthew  14882: ######################################################
                   14883: ######################################################
                   14884: 
1.56      matthew  14885: =pod
                   14886: 
1.648     raeburn  14887: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14888: 
                   14889: Prints a table to create associations between values and table columns.
1.144     matthew  14890: 
1.41      ng       14891: $r is an Apache Request ref,
                   14892: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14893: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14894: 
                   14895: =cut
                   14896: 
1.144     matthew  14897: ######################################################
                   14898: ######################################################
1.31      albertel 14899: sub csv_print_select_table {
                   14900:     my ($r,$records,$d) = @_;
1.301     albertel 14901:     my $i=0;
                   14902:     my $samples = &get_samples($records,1);
1.144     matthew  14903:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14904: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14905:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14906:               '<th>'.&mt('Column').'</th>'.
                   14907:               &end_data_table_header_row()."\n");
1.356     albertel 14908:     foreach my $array_ref (@$d) {
                   14909: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14910: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14911: 
1.875     bisitz   14912: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14913: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14914: 	$r->print('<option value="none"></option>');
1.356     albertel 14915: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14916: 	    $r->print('<option value="'.$sample.'"'.
                   14917:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14918:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14919: 	}
1.594     raeburn  14920: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14921: 	$i++;
                   14922:     }
1.594     raeburn  14923:     $r->print(&end_data_table());
1.31      albertel 14924:     $i--;
                   14925:     return $i;
                   14926: }
1.56      matthew  14927: 
1.144     matthew  14928: ######################################################
                   14929: ######################################################
                   14930: 
1.56      matthew  14931: =pod
1.31      albertel 14932: 
1.648     raeburn  14933: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14934: 
                   14935: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14936: 
                   14937: $r is an Apache Request ref,
                   14938: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14939: $d is an array of 2 element arrays (internal name, displayed name)
                   14940: 
                   14941: =cut
                   14942: 
1.144     matthew  14943: ######################################################
                   14944: ######################################################
1.31      albertel 14945: sub csv_samples_select_table {
                   14946:     my ($r,$records,$d) = @_;
                   14947:     my $i=0;
1.144     matthew  14948:     #
1.662     bisitz   14949:     my $max_samples = 5;
                   14950:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14951:     $r->print(&start_data_table().
                   14952:               &start_data_table_header_row().'<th>'.
                   14953:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14954:               &end_data_table_header_row());
1.301     albertel 14955: 
                   14956:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14957: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14958: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14959: 	foreach my $option (@$d) {
                   14960: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14961: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14962:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14963:                       $display.'</option>');
1.31      albertel 14964: 	}
                   14965: 	$r->print('</select></td><td>');
1.662     bisitz   14966: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14967: 	    if (defined($samples->[$line]{$key})) { 
                   14968: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14969: 	    }
                   14970: 	}
1.594     raeburn  14971: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14972: 	$i++;
                   14973:     }
1.594     raeburn  14974:     $r->print(&end_data_table());
1.31      albertel 14975:     $i--;
                   14976:     return($i);
1.115     matthew  14977: }
                   14978: 
1.144     matthew  14979: ######################################################
                   14980: ######################################################
                   14981: 
1.115     matthew  14982: =pod
                   14983: 
1.648     raeburn  14984: =item * &clean_excel_name($name)
1.115     matthew  14985: 
                   14986: Returns a replacement for $name which does not contain any illegal characters.
                   14987: 
                   14988: =cut
                   14989: 
1.144     matthew  14990: ######################################################
                   14991: ######################################################
1.115     matthew  14992: sub clean_excel_name {
                   14993:     my ($name) = @_;
                   14994:     $name =~ s/[:\*\?\/\\]//g;
                   14995:     if (length($name) > 31) {
                   14996:         $name = substr($name,0,31);
                   14997:     }
                   14998:     return $name;
1.25      albertel 14999: }
1.84      albertel 15000: 
1.85      albertel 15001: =pod
                   15002: 
1.648     raeburn  15003: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15004: 
                   15005: Returns either 1 or undef
                   15006: 
                   15007: 1 if the part is to be hidden, undef if it is to be shown
                   15008: 
                   15009: Arguments are:
                   15010: 
                   15011: $id the id of the part to be checked
                   15012: $symb, optional the symb of the resource to check
                   15013: $udom, optional the domain of the user to check for
                   15014: $uname, optional the username of the user to check for
                   15015: 
                   15016: =cut
1.84      albertel 15017: 
                   15018: sub check_if_partid_hidden {
                   15019:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15020:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15021: 					 $symb,$udom,$uname);
1.141     albertel 15022:     my $truth=1;
                   15023:     #if the string starts with !, then the list is the list to show not hide
                   15024:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15025:     my @hiddenlist=split(/,/,$hiddenparts);
                   15026:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15027: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15028:     }
1.141     albertel 15029:     return !$truth;
1.84      albertel 15030: }
1.127     matthew  15031: 
1.138     matthew  15032: 
                   15033: ############################################################
                   15034: ############################################################
                   15035: 
                   15036: =pod
                   15037: 
1.157     matthew  15038: =back 
                   15039: 
1.138     matthew  15040: =head1 cgi-bin script and graphing routines
                   15041: 
1.157     matthew  15042: =over 4
                   15043: 
1.648     raeburn  15044: =item * &get_cgi_id()
1.138     matthew  15045: 
                   15046: Inputs: none
                   15047: 
                   15048: Returns an id which can be used to pass environment variables
                   15049: to various cgi-bin scripts.  These environment variables will
                   15050: be removed from the users environment after a given time by
                   15051: the routine &Apache::lonnet::transfer_profile_to_env.
                   15052: 
                   15053: =cut
                   15054: 
                   15055: ############################################################
                   15056: ############################################################
1.152     albertel 15057: my $uniq=0;
1.136     matthew  15058: sub get_cgi_id {
1.154     albertel 15059:     $uniq=($uniq+1)%100000;
1.280     albertel 15060:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15061: }
                   15062: 
1.127     matthew  15063: ############################################################
                   15064: ############################################################
                   15065: 
                   15066: =pod
                   15067: 
1.648     raeburn  15068: =item * &DrawBarGraph()
1.127     matthew  15069: 
1.138     matthew  15070: Facilitates the plotting of data in a (stacked) bar graph.
                   15071: Puts plot definition data into the users environment in order for 
                   15072: graph.png to plot it.  Returns an <img> tag for the plot.
                   15073: The bars on the plot are labeled '1','2',...,'n'.
                   15074: 
                   15075: Inputs:
                   15076: 
                   15077: =over 4
                   15078: 
                   15079: =item $Title: string, the title of the plot
                   15080: 
                   15081: =item $xlabel: string, text describing the X-axis of the plot
                   15082: 
                   15083: =item $ylabel: string, text describing the Y-axis of the plot
                   15084: 
                   15085: =item $Max: scalar, the maximum Y value to use in the plot
                   15086: If $Max is < any data point, the graph will not be rendered.
                   15087: 
1.140     matthew  15088: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15089: they are plotted.  If undefined, default values will be used.
                   15090: 
1.178     matthew  15091: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15092: 
1.138     matthew  15093: =item @Values: An array of array references.  Each array reference holds data
                   15094: to be plotted in a stacked bar chart.
                   15095: 
1.239     matthew  15096: =item If the final element of @Values is a hash reference the key/value
                   15097: pairs will be added to the graph definition.
                   15098: 
1.138     matthew  15099: =back
                   15100: 
                   15101: Returns:
                   15102: 
                   15103: An <img> tag which references graph.png and the appropriate identifying
                   15104: information for the plot.
                   15105: 
1.127     matthew  15106: =cut
                   15107: 
                   15108: ############################################################
                   15109: ############################################################
1.134     matthew  15110: sub DrawBarGraph {
1.178     matthew  15111:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15112:     #
                   15113:     if (! defined($colors)) {
                   15114:         $colors = ['#33ff00', 
                   15115:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15116:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15117:                   ]; 
                   15118:     }
1.228     matthew  15119:     my $extra_settings = {};
                   15120:     if (ref($Values[-1]) eq 'HASH') {
                   15121:         $extra_settings = pop(@Values);
                   15122:     }
1.127     matthew  15123:     #
1.136     matthew  15124:     my $identifier = &get_cgi_id();
                   15125:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15126:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15127:         return '';
                   15128:     }
1.225     matthew  15129:     #
                   15130:     my @Labels;
                   15131:     if (defined($labels)) {
                   15132:         @Labels = @$labels;
                   15133:     } else {
                   15134:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  15135:             push(@Labels,$i+1);
1.225     matthew  15136:         }
                   15137:     }
                   15138:     #
1.129     matthew  15139:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15140:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15141:     my %ValuesHash;
                   15142:     my $NumSets=1;
                   15143:     foreach my $array (@Values) {
                   15144:         next if (! ref($array));
1.136     matthew  15145:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15146:             join(',',@$array);
1.129     matthew  15147:     }
1.127     matthew  15148:     #
1.136     matthew  15149:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15150:     if ($NumBars < 3) {
                   15151:         $width = 120+$NumBars*32;
1.220     matthew  15152:         $xskip = 1;
1.225     matthew  15153:         $bar_width = 30;
                   15154:     } elsif ($NumBars < 5) {
                   15155:         $width = 120+$NumBars*20;
                   15156:         $xskip = 1;
                   15157:         $bar_width = 20;
1.220     matthew  15158:     } elsif ($NumBars < 10) {
1.136     matthew  15159:         $width = 120+$NumBars*15;
                   15160:         $xskip = 1;
                   15161:         $bar_width = 15;
                   15162:     } elsif ($NumBars <= 25) {
                   15163:         $width = 120+$NumBars*11;
                   15164:         $xskip = 5;
                   15165:         $bar_width = 8;
                   15166:     } elsif ($NumBars <= 50) {
                   15167:         $width = 120+$NumBars*8;
                   15168:         $xskip = 5;
                   15169:         $bar_width = 4;
                   15170:     } else {
                   15171:         $width = 120+$NumBars*8;
                   15172:         $xskip = 5;
                   15173:         $bar_width = 4;
                   15174:     }
                   15175:     #
1.137     matthew  15176:     $Max = 1 if ($Max < 1);
                   15177:     if ( int($Max) < $Max ) {
                   15178:         $Max++;
                   15179:         $Max = int($Max);
                   15180:     }
1.127     matthew  15181:     $Title  = '' if (! defined($Title));
                   15182:     $xlabel = '' if (! defined($xlabel));
                   15183:     $ylabel = '' if (! defined($ylabel));
1.369     www      15184:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15185:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15186:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15187:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15188:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15189:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15190:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15191:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15192:     $ValuesHash{$id.'.height'}   = $height;
                   15193:     $ValuesHash{$id.'.width'}    = $width;
                   15194:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15195:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15196:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15197:     #
1.228     matthew  15198:     # Deal with other parameters
                   15199:     while (my ($key,$value) = each(%$extra_settings)) {
                   15200:         $ValuesHash{$id.'.'.$key} = $value;
                   15201:     }
                   15202:     #
1.646     raeburn  15203:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15204:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15205: }
                   15206: 
                   15207: ############################################################
                   15208: ############################################################
                   15209: 
                   15210: =pod
                   15211: 
1.648     raeburn  15212: =item * &DrawXYGraph()
1.137     matthew  15213: 
1.138     matthew  15214: Facilitates the plotting of data in an XY graph.
                   15215: Puts plot definition data into the users environment in order for 
                   15216: graph.png to plot it.  Returns an <img> tag for the plot.
                   15217: 
                   15218: Inputs:
                   15219: 
                   15220: =over 4
                   15221: 
                   15222: =item $Title: string, the title of the plot
                   15223: 
                   15224: =item $xlabel: string, text describing the X-axis of the plot
                   15225: 
                   15226: =item $ylabel: string, text describing the Y-axis of the plot
                   15227: 
                   15228: =item $Max: scalar, the maximum Y value to use in the plot
                   15229: If $Max is < any data point, the graph will not be rendered.
                   15230: 
                   15231: =item $colors: Array ref containing the hex color codes for the data to be 
                   15232: plotted in.  If undefined, default values will be used.
                   15233: 
                   15234: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15235: 
                   15236: =item $Ydata: Array ref containing Array refs.  
1.185     www      15237: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15238: 
                   15239: =item %Values: hash indicating or overriding any default values which are 
                   15240: passed to graph.png.  
                   15241: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15242: 
                   15243: =back
                   15244: 
                   15245: Returns:
                   15246: 
                   15247: An <img> tag which references graph.png and the appropriate identifying
                   15248: information for the plot.
                   15249: 
1.137     matthew  15250: =cut
                   15251: 
                   15252: ############################################################
                   15253: ############################################################
                   15254: sub DrawXYGraph {
                   15255:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15256:     #
                   15257:     # Create the identifier for the graph
                   15258:     my $identifier = &get_cgi_id();
                   15259:     my $id = 'cgi.'.$identifier;
                   15260:     #
                   15261:     $Title  = '' if (! defined($Title));
                   15262:     $xlabel = '' if (! defined($xlabel));
                   15263:     $ylabel = '' if (! defined($ylabel));
                   15264:     my %ValuesHash = 
                   15265:         (
1.369     www      15266:          $id.'.title'  => &escape($Title),
                   15267:          $id.'.xlabel' => &escape($xlabel),
                   15268:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15269:          $id.'.y_max_value'=> $Max,
                   15270:          $id.'.labels'     => join(',',@$Xlabels),
                   15271:          $id.'.PlotType'   => 'XY',
                   15272:          );
                   15273:     #
                   15274:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15275:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15276:     }
                   15277:     #
                   15278:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15279:         return '';
                   15280:     }
                   15281:     my $NumSets=1;
1.138     matthew  15282:     foreach my $array (@{$Ydata}){
1.137     matthew  15283:         next if (! ref($array));
                   15284:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15285:     }
1.138     matthew  15286:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15287:     #
                   15288:     # Deal with other parameters
                   15289:     while (my ($key,$value) = each(%Values)) {
                   15290:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15291:     }
                   15292:     #
1.646     raeburn  15293:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15294:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15295: }
                   15296: 
                   15297: ############################################################
                   15298: ############################################################
                   15299: 
                   15300: =pod
                   15301: 
1.648     raeburn  15302: =item * &DrawXYYGraph()
1.138     matthew  15303: 
                   15304: Facilitates the plotting of data in an XY graph with two Y axes.
                   15305: Puts plot definition data into the users environment in order for 
                   15306: graph.png to plot it.  Returns an <img> tag for the plot.
                   15307: 
                   15308: Inputs:
                   15309: 
                   15310: =over 4
                   15311: 
                   15312: =item $Title: string, the title of the plot
                   15313: 
                   15314: =item $xlabel: string, text describing the X-axis of the plot
                   15315: 
                   15316: =item $ylabel: string, text describing the Y-axis of the plot
                   15317: 
                   15318: =item $colors: Array ref containing the hex color codes for the data to be 
                   15319: plotted in.  If undefined, default values will be used.
                   15320: 
                   15321: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15322: 
                   15323: =item $Ydata1: The first data set
                   15324: 
                   15325: =item $Min1: The minimum value of the left Y-axis
                   15326: 
                   15327: =item $Max1: The maximum value of the left Y-axis
                   15328: 
                   15329: =item $Ydata2: The second data set
                   15330: 
                   15331: =item $Min2: The minimum value of the right Y-axis
                   15332: 
                   15333: =item $Max2: The maximum value of the left Y-axis
                   15334: 
                   15335: =item %Values: hash indicating or overriding any default values which are 
                   15336: passed to graph.png.  
                   15337: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15338: 
                   15339: =back
                   15340: 
                   15341: Returns:
                   15342: 
                   15343: An <img> tag which references graph.png and the appropriate identifying
                   15344: information for the plot.
1.136     matthew  15345: 
                   15346: =cut
                   15347: 
                   15348: ############################################################
                   15349: ############################################################
1.137     matthew  15350: sub DrawXYYGraph {
                   15351:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15352:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15353:     #
                   15354:     # Create the identifier for the graph
                   15355:     my $identifier = &get_cgi_id();
                   15356:     my $id = 'cgi.'.$identifier;
                   15357:     #
                   15358:     $Title  = '' if (! defined($Title));
                   15359:     $xlabel = '' if (! defined($xlabel));
                   15360:     $ylabel = '' if (! defined($ylabel));
                   15361:     my %ValuesHash = 
                   15362:         (
1.369     www      15363:          $id.'.title'  => &escape($Title),
                   15364:          $id.'.xlabel' => &escape($xlabel),
                   15365:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15366:          $id.'.labels' => join(',',@$Xlabels),
                   15367:          $id.'.PlotType' => 'XY',
                   15368:          $id.'.NumSets' => 2,
1.137     matthew  15369:          $id.'.two_axes' => 1,
                   15370:          $id.'.y1_max_value' => $Max1,
                   15371:          $id.'.y1_min_value' => $Min1,
                   15372:          $id.'.y2_max_value' => $Max2,
                   15373:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15374:          );
                   15375:     #
1.137     matthew  15376:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15377:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15378:     }
                   15379:     #
                   15380:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15381:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15382:         return '';
                   15383:     }
                   15384:     my $NumSets=1;
1.137     matthew  15385:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15386:         next if (! ref($array));
                   15387:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15388:     }
                   15389:     #
                   15390:     # Deal with other parameters
                   15391:     while (my ($key,$value) = each(%Values)) {
                   15392:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15393:     }
                   15394:     #
1.646     raeburn  15395:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15396:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15397: }
                   15398: 
                   15399: ############################################################
                   15400: ############################################################
                   15401: 
                   15402: =pod
                   15403: 
1.157     matthew  15404: =back 
                   15405: 
1.139     matthew  15406: =head1 Statistics helper routines?  
                   15407: 
                   15408: Bad place for them but what the hell.
                   15409: 
1.157     matthew  15410: =over 4
                   15411: 
1.648     raeburn  15412: =item * &chartlink()
1.139     matthew  15413: 
                   15414: Returns a link to the chart for a specific student.  
                   15415: 
                   15416: Inputs:
                   15417: 
                   15418: =over 4
                   15419: 
                   15420: =item $linktext: The text of the link
                   15421: 
                   15422: =item $sname: The students username
                   15423: 
                   15424: =item $sdomain: The students domain
                   15425: 
                   15426: =back
                   15427: 
1.157     matthew  15428: =back
                   15429: 
1.139     matthew  15430: =cut
                   15431: 
                   15432: ############################################################
                   15433: ############################################################
                   15434: sub chartlink {
                   15435:     my ($linktext, $sname, $sdomain) = @_;
                   15436:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15437:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15438:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15439:        '">'.$linktext.'</a>';
1.153     matthew  15440: }
                   15441: 
                   15442: #######################################################
                   15443: #######################################################
                   15444: 
                   15445: =pod
                   15446: 
                   15447: =head1 Course Environment Routines
1.157     matthew  15448: 
                   15449: =over 4
1.153     matthew  15450: 
1.648     raeburn  15451: =item * &restore_course_settings()
1.153     matthew  15452: 
1.648     raeburn  15453: =item * &store_course_settings()
1.153     matthew  15454: 
                   15455: Restores/Store indicated form parameters from the course environment.
                   15456: Will not overwrite existing values of the form parameters.
                   15457: 
                   15458: Inputs: 
                   15459: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15460: 
                   15461: a hash ref describing the data to be stored.  For example:
                   15462:    
                   15463: %Save_Parameters = ('Status' => 'scalar',
                   15464:     'chartoutputmode' => 'scalar',
                   15465:     'chartoutputdata' => 'scalar',
                   15466:     'Section' => 'array',
1.373     raeburn  15467:     'Group' => 'array',
1.153     matthew  15468:     'StudentData' => 'array',
                   15469:     'Maps' => 'array');
                   15470: 
                   15471: Returns: both routines return nothing
                   15472: 
1.631     raeburn  15473: =back
                   15474: 
1.153     matthew  15475: =cut
                   15476: 
                   15477: #######################################################
                   15478: #######################################################
                   15479: sub store_course_settings {
1.496     albertel 15480:     return &store_settings($env{'request.course.id'},@_);
                   15481: }
                   15482: 
                   15483: sub store_settings {
1.153     matthew  15484:     # save to the environment
                   15485:     # appenv the same items, just to be safe
1.300     albertel 15486:     my $udom  = $env{'user.domain'};
                   15487:     my $uname = $env{'user.name'};
1.496     albertel 15488:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15489:     my %SaveHash;
                   15490:     my %AppHash;
                   15491:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15492:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15493:         my $envname = 'environment.'.$basename;
1.258     albertel 15494:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15495:             # Save this value away
                   15496:             if ($type eq 'scalar' &&
1.258     albertel 15497:                 (! exists($env{$envname}) || 
                   15498:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15499:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15500:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15501:             } elsif ($type eq 'array') {
                   15502:                 my $stored_form;
1.258     albertel 15503:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15504:                     $stored_form = join(',',
                   15505:                                         map {
1.369     www      15506:                                             &escape($_);
1.258     albertel 15507:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15508:                 } else {
                   15509:                     $stored_form = 
1.369     www      15510:                         &escape($env{'form.'.$setting});
1.153     matthew  15511:                 }
                   15512:                 # Determine if the array contents are the same.
1.258     albertel 15513:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15514:                     $SaveHash{$basename} = $stored_form;
                   15515:                     $AppHash{$envname}   = $stored_form;
                   15516:                 }
                   15517:             }
                   15518:         }
                   15519:     }
                   15520:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15521:                                           $udom,$uname);
1.153     matthew  15522:     if ($put_result !~ /^(ok|delayed)/) {
                   15523:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15524:                                  'got error:'.$put_result);
                   15525:     }
                   15526:     # Make sure these settings stick around in this session, too
1.646     raeburn  15527:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15528:     return;
                   15529: }
                   15530: 
                   15531: sub restore_course_settings {
1.499     albertel 15532:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15533: }
                   15534: 
                   15535: sub restore_settings {
                   15536:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15537:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15538:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15539:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15540:             '.'.$setting;
1.258     albertel 15541:         if (exists($env{$envname})) {
1.153     matthew  15542:             if ($type eq 'scalar') {
1.258     albertel 15543:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15544:             } elsif ($type eq 'array') {
1.258     albertel 15545:                 $env{'form.'.$setting} = [ 
1.153     matthew  15546:                                            map { 
1.369     www      15547:                                                &unescape($_); 
1.258     albertel 15548:                                            } split(',',$env{$envname})
1.153     matthew  15549:                                            ];
                   15550:             }
                   15551:         }
                   15552:     }
1.127     matthew  15553: }
                   15554: 
1.618     raeburn  15555: #######################################################
                   15556: #######################################################
                   15557: 
                   15558: =pod
                   15559: 
                   15560: =head1 Domain E-mail Routines  
                   15561: 
                   15562: =over 4
                   15563: 
1.648     raeburn  15564: =item * &build_recipient_list()
1.618     raeburn  15565: 
1.1075.2.44  raeburn  15566: Build recipient lists for following types of e-mail:
1.766     raeburn  15567: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15568: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15569: module change checking, student/employee ID conflict checks, as
                   15570: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15571: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15572: 
                   15573: Inputs:
1.1075.2.44  raeburn  15574: defmail (scalar - email address of default recipient),
                   15575: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15576: requestsmail, updatesmail, or idconflictsmail).
                   15577: 
1.619     raeburn  15578: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15579: 
                   15580: origmail (scalar - email address of recipient from loncapa.conf,
                   15581: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15582: 
1.1075.2.139  raeburn  15583: $requname username of requester (if mailing type is helpdeskmail)
                   15584: 
                   15585: $requdom domain of requester (if mailing type is helpdeskmail)
                   15586: 
                   15587: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15588: 
1.655     raeburn  15589: Returns: comma separated list of addresses to which to send e-mail.
                   15590: 
                   15591: =back
1.618     raeburn  15592: 
                   15593: =cut
                   15594: 
                   15595: ############################################################
                   15596: ############################################################
                   15597: sub build_recipient_list {
1.1075.2.139  raeburn  15598:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15599:     my @recipients;
1.1075.2.122  raeburn  15600:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15601:     my %domconfig =
1.1075.2.122  raeburn  15602:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15603:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15604:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15605:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15606:                 my @contacts = ('adminemail','supportemail');
                   15607:                 foreach my $item (@contacts) {
                   15608:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15609:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15610:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15611:                             push(@recipients,$addr);
                   15612:                         }
1.619     raeburn  15613:                     }
1.1075.2.122  raeburn  15614:                 }
                   15615:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15616:                 if ($mailing eq 'helpdeskmail') {
                   15617:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15618:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15619:                         my @ok_bccs;
                   15620:                         foreach my $bcc (@bccs) {
                   15621:                             $bcc =~ s/^\s+//g;
                   15622:                             $bcc =~ s/\s+$//g;
                   15623:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15624:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15625:                                     push(@ok_bccs,$bcc);
                   15626:                                 }
                   15627:                             }
                   15628:                         }
                   15629:                         if (@ok_bccs > 0) {
                   15630:                             $allbcc = join(', ',@ok_bccs);
                   15631:                         }
                   15632:                     }
                   15633:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15634:                 }
                   15635:             }
1.766     raeburn  15636:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15637:             $lastresort = $origmail;
1.618     raeburn  15638:         }
1.1075.2.139  raeburn  15639:         if ($mailing eq 'helpdeskmail') {
                   15640:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15641:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15642:                 my ($inststatus,$inststatus_checked);
                   15643:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15644:                     ($env{'user.domain'} ne 'public')) {
                   15645:                     $inststatus_checked = 1;
                   15646:                     $inststatus = $env{'environment.inststatus'};
                   15647:                 }
                   15648:                 unless ($inststatus_checked) {
                   15649:                     if (($requname ne '') && ($requdom ne '')) {
                   15650:                         if (($requname =~ /^$match_username$/) &&
                   15651:                             ($requdom =~ /^$match_domain$/) &&
                   15652:                             (&Apache::lonnet::domain($requdom))) {
                   15653:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15654:                                                                       $requdom);
                   15655:                             unless ($requhome eq 'no_host') {
                   15656:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15657:                                 $inststatus = $userenv{'inststatus'};
                   15658:                                 $inststatus_checked = 1;
                   15659:                             }
                   15660:                         }
                   15661:                     }
                   15662:                 }
                   15663:                 unless ($inststatus_checked) {
                   15664:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15665:                         my %srch = (srchby     => 'email',
                   15666:                                     srchdomain => $defdom,
                   15667:                                     srchterm   => $reqemail,
                   15668:                                     srchtype   => 'exact');
                   15669:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15670:                         foreach my $uname (keys(%srch_results)) {
                   15671:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15672:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15673:                                 $inststatus_checked = 1;
                   15674:                                 last;
                   15675:                             }
                   15676:                         }
                   15677:                         unless ($inststatus_checked) {
                   15678:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15679:                             if ($dirsrchres eq 'ok') {
                   15680:                                 foreach my $uname (keys(%srch_results)) {
                   15681:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15682:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15683:                                         $inststatus_checked = 1;
                   15684:                                         last;
                   15685:                                     }
                   15686:                                 }
                   15687:                             }
                   15688:                         }
                   15689:                     }
                   15690:                 }
                   15691:                 if ($inststatus ne '') {
                   15692:                     foreach my $status (split(/\:/,$inststatus)) {
                   15693:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15694:                             my @contacts = ('adminemail','supportemail');
                   15695:                             foreach my $item (@contacts) {
                   15696:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15697:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15698:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15699:                                         push(@recipients,$addr);
                   15700:                                     }
                   15701:                                 }
                   15702:                             }
                   15703:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15704:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15705:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15706:                                 my @ok_bccs;
                   15707:                                 foreach my $bcc (@bccs) {
                   15708:                                     $bcc =~ s/^\s+//g;
                   15709:                                     $bcc =~ s/\s+$//g;
                   15710:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15711:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15712:                                             push(@ok_bccs,$bcc);
                   15713:                                         }
                   15714:                                     }
                   15715:                                 }
                   15716:                                 if (@ok_bccs > 0) {
                   15717:                                     $allbcc = join(', ',@ok_bccs);
                   15718:                                 }
                   15719:                             }
                   15720:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15721:                             last;
                   15722:                         }
                   15723:                     }
                   15724:                 }
                   15725:             }
                   15726:         }
1.619     raeburn  15727:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15728:         $lastresort = $origmail;
                   15729:     }
1.1075.2.128  raeburn  15730:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15731:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15732:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15733:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15734:             my %what = (
                   15735:                           perlvar => 1,
                   15736:                        );
                   15737:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15738:             if ($primary) {
                   15739:                 my $gotaddr;
                   15740:                 my ($result,$returnhash) =
                   15741:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15742:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15743:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15744:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15745:                         $gotaddr = 1;
                   15746:                     }
                   15747:                 }
                   15748:                 unless ($gotaddr) {
                   15749:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15750:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15751:                     unless ($uintdom eq $intdom) {
                   15752:                         my %domconfig =
                   15753:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15754:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15755:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15756:                                 my @contacts = ('adminemail','supportemail');
                   15757:                                 foreach my $item (@contacts) {
                   15758:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15759:                                         my $addr = $domconfig{'contacts'}{$item};
                   15760:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15761:                                             push(@recipients,$addr);
                   15762:                                         }
                   15763:                                     }
                   15764:                                 }
                   15765:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15766:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15767:                                 }
                   15768:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15769:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15770:                                     my @ok_bccs;
                   15771:                                     foreach my $bcc (@bccs) {
                   15772:                                         $bcc =~ s/^\s+//g;
                   15773:                                         $bcc =~ s/\s+$//g;
                   15774:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15775:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15776:                                                 push(@ok_bccs,$bcc);
                   15777:                                             }
                   15778:                                         }
                   15779:                                     }
                   15780:                                     if (@ok_bccs > 0) {
                   15781:                                         $allbcc = join(', ',@ok_bccs);
                   15782:                                     }
                   15783:                                 }
                   15784:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15785:                             }
                   15786:                         }
                   15787:                     }
                   15788:                 }
                   15789:             }
                   15790:         }
1.618     raeburn  15791:     }
1.688     raeburn  15792:     if (defined($defmail)) {
                   15793:         if ($defmail ne '') {
                   15794:             push(@recipients,$defmail);
                   15795:         }
1.618     raeburn  15796:     }
                   15797:     if ($otheremails) {
1.619     raeburn  15798:         my @others;
                   15799:         if ($otheremails =~ /,/) {
                   15800:             @others = split(/,/,$otheremails);
1.618     raeburn  15801:         } else {
1.619     raeburn  15802:             push(@others,$otheremails);
                   15803:         }
                   15804:         foreach my $addr (@others) {
                   15805:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15806:                 push(@recipients,$addr);
                   15807:             }
1.618     raeburn  15808:         }
                   15809:     }
1.1075.2.128  raeburn  15810:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15811:         if ((!@recipients) && ($lastresort ne '')) {
                   15812:             push(@recipients,$lastresort);
                   15813:         }
                   15814:     } elsif ($lastresort ne '') {
                   15815:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15816:             push(@recipients,$lastresort);
                   15817:         }
                   15818:     }
                   15819:     my $recipientlist = join(',',@recipients);
                   15820:     if (wantarray) {
                   15821:         return ($recipientlist,$allbcc,$addtext);
                   15822:     } else {
                   15823:         return $recipientlist;
                   15824:     }
1.618     raeburn  15825: }
                   15826: 
1.127     matthew  15827: ############################################################
                   15828: ############################################################
1.154     albertel 15829: 
1.655     raeburn  15830: =pod
                   15831: 
                   15832: =head1 Course Catalog Routines
                   15833: 
                   15834: =over 4
                   15835: 
                   15836: =item * &gather_categories()
                   15837: 
                   15838: Converts category definitions - keys of categories hash stored in  
                   15839: coursecategories in configuration.db on the primary library server in a 
                   15840: domain - to an array.  Also generates javascript and idx hash used to 
                   15841: generate Domain Coordinator interface for editing Course Categories.
                   15842: 
                   15843: Inputs:
1.663     raeburn  15844: 
1.655     raeburn  15845: categories (reference to hash of category definitions).
1.663     raeburn  15846: 
1.655     raeburn  15847: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15848:       categories and subcategories).
1.663     raeburn  15849: 
1.655     raeburn  15850: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15851:       editing Course Categories).
1.663     raeburn  15852: 
1.655     raeburn  15853: jsarray (reference to array of categories used to create Javascript arrays for
                   15854:          Domain Coordinator interface for editing Course Categories).
                   15855: 
                   15856: Returns: nothing
                   15857: 
                   15858: Side effects: populates cats, idx and jsarray. 
                   15859: 
                   15860: =cut
                   15861: 
                   15862: sub gather_categories {
                   15863:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15864:     my %counters;
                   15865:     my $num = 0;
                   15866:     foreach my $item (keys(%{$categories})) {
                   15867:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15868:         if ($container eq '' && $depth == 0) {
                   15869:             $cats->[$depth][$categories->{$item}] = $cat;
                   15870:         } else {
                   15871:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15872:         }
                   15873:         my ($escitem,$tail) = split(/:/,$item,2);
                   15874:         if ($counters{$tail} eq '') {
                   15875:             $counters{$tail} = $num;
                   15876:             $num ++;
                   15877:         }
                   15878:         if (ref($idx) eq 'HASH') {
                   15879:             $idx->{$item} = $counters{$tail};
                   15880:         }
                   15881:         if (ref($jsarray) eq 'ARRAY') {
                   15882:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15883:         }
                   15884:     }
                   15885:     return;
                   15886: }
                   15887: 
                   15888: =pod
                   15889: 
                   15890: =item * &extract_categories()
                   15891: 
                   15892: Used to generate breadcrumb trails for course categories.
                   15893: 
                   15894: Inputs:
1.663     raeburn  15895: 
1.655     raeburn  15896: categories (reference to hash of category definitions).
1.663     raeburn  15897: 
1.655     raeburn  15898: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15899:       categories and subcategories).
1.663     raeburn  15900: 
1.655     raeburn  15901: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15902: 
1.655     raeburn  15903: allitems (reference to hash - key is category key 
                   15904:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15905: 
1.655     raeburn  15906: idx (reference to hash of counters used in Domain Coordinator interface for
                   15907:       editing Course Categories).
1.663     raeburn  15908: 
1.655     raeburn  15909: jsarray (reference to array of categories used to create Javascript arrays for
                   15910:          Domain Coordinator interface for editing Course Categories).
                   15911: 
1.665     raeburn  15912: subcats (reference to hash of arrays containing all subcategories within each 
                   15913:          category, -recursive)
                   15914: 
1.1075.2.132  raeburn  15915: maxd (reference to hash used to hold max depth for all top-level categories).
                   15916: 
1.655     raeburn  15917: Returns: nothing
                   15918: 
                   15919: Side effects: populates trails and allitems hash references.
                   15920: 
                   15921: =cut
                   15922: 
                   15923: sub extract_categories {
1.1075.2.132  raeburn  15924:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15925:     if (ref($categories) eq 'HASH') {
                   15926:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15927:         if (ref($cats->[0]) eq 'ARRAY') {
                   15928:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15929:                 my $name = $cats->[0][$i];
                   15930:                 my $item = &escape($name).'::0';
                   15931:                 my $trailstr;
                   15932:                 if ($name eq 'instcode') {
                   15933:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15934:                 } elsif ($name eq 'communities') {
                   15935:                     $trailstr = &mt('Communities');
1.655     raeburn  15936:                 } else {
                   15937:                     $trailstr = $name;
                   15938:                 }
                   15939:                 if ($allitems->{$item} eq '') {
                   15940:                     push(@{$trails},$trailstr);
                   15941:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15942:                 }
                   15943:                 my @parents = ($name);
                   15944:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15945:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15946:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15947:                         if (ref($subcats) eq 'HASH') {
                   15948:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15949:                         }
1.1075.2.132  raeburn  15950:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15951:                     }
                   15952:                 } else {
                   15953:                     if (ref($subcats) eq 'HASH') {
                   15954:                         $subcats->{$item} = [];
1.655     raeburn  15955:                     }
1.1075.2.132  raeburn  15956:                     if (ref($maxd) eq 'HASH') {
                   15957:                         $maxd->{$name} = 1;
                   15958:                     }
1.655     raeburn  15959:                 }
                   15960:             }
                   15961:         }
                   15962:     }
                   15963:     return;
                   15964: }
                   15965: 
                   15966: =pod
                   15967: 
1.1075.2.56  raeburn  15968: =item * &recurse_categories()
1.655     raeburn  15969: 
                   15970: Recursively used to generate breadcrumb trails for course categories.
                   15971: 
                   15972: Inputs:
1.663     raeburn  15973: 
1.655     raeburn  15974: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15975:       categories and subcategories).
1.663     raeburn  15976: 
1.655     raeburn  15977: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15978: 
                   15979: category (current course category, for which breadcrumb trail is being generated).
                   15980: 
                   15981: trails (reference to array of breadcrumb trails for each category).
                   15982: 
1.655     raeburn  15983: allitems (reference to hash - key is category key
                   15984:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15985: 
1.655     raeburn  15986: parents (array containing containers directories for current category, 
                   15987:          back to top level). 
                   15988: 
                   15989: Returns: nothing
                   15990: 
                   15991: Side effects: populates trails and allitems hash references
                   15992: 
                   15993: =cut
                   15994: 
                   15995: sub recurse_categories {
1.1075.2.132  raeburn  15996:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15997:     my $shallower = $depth - 1;
                   15998:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15999:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16000:             my $name = $cats->[$depth]{$category}[$k];
                   16001:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 16002:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16003:             if ($allitems->{$item} eq '') {
                   16004:                 push(@{$trails},$trailstr);
                   16005:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16006:             }
                   16007:             my $deeper = $depth+1;
                   16008:             push(@{$parents},$category);
1.665     raeburn  16009:             if (ref($subcats) eq 'HASH') {
                   16010:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16011:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16012:                     my $higher;
                   16013:                     if ($j > 0) {
                   16014:                         $higher = &escape($parents->[$j]).':'.
                   16015:                                   &escape($parents->[$j-1]).':'.$j;
                   16016:                     } else {
                   16017:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16018:                     }
                   16019:                     push(@{$subcats->{$higher}},$subcat);
                   16020:                 }
                   16021:             }
                   16022:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  16023:                                 $subcats,$maxd);
1.655     raeburn  16024:             pop(@{$parents});
                   16025:         }
                   16026:     } else {
                   16027:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  16028:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16029:         if ($allitems->{$item} eq '') {
                   16030:             push(@{$trails},$trailstr);
                   16031:             $allitems->{$item} = scalar(@{$trails})-1;
                   16032:         }
1.1075.2.132  raeburn  16033:         if (ref($maxd) eq 'HASH') {
                   16034:             if ($depth > $maxd->{$parents->[0]}) {
                   16035:                 $maxd->{$parents->[0]} = $depth;
                   16036:             }
                   16037:         }
1.655     raeburn  16038:     }
                   16039:     return;
                   16040: }
                   16041: 
1.663     raeburn  16042: =pod
                   16043: 
1.1075.2.56  raeburn  16044: =item * &assign_categories_table()
1.663     raeburn  16045: 
                   16046: Create a datatable for display of hierarchical categories in a domain,
                   16047: with checkboxes to allow a course to be categorized. 
                   16048: 
                   16049: Inputs:
                   16050: 
                   16051: cathash - reference to hash of categories defined for the domain (from
                   16052:           configuration.db)
                   16053: 
                   16054: currcat - scalar with an & separated list of categories assigned to a course. 
                   16055: 
1.919     raeburn  16056: type    - scalar contains course type (Course or Community).
                   16057: 
1.1075.2.117  raeburn  16058: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16059:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16060: 
1.663     raeburn  16061: Returns: $output (markup to be displayed) 
                   16062: 
                   16063: =cut
                   16064: 
                   16065: sub assign_categories_table {
1.1075.2.117  raeburn  16066:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16067:     my $output;
                   16068:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  16069:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16070:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16071:         $maxdepth = scalar(@cats);
                   16072:         if (@cats > 0) {
                   16073:             my $itemcount = 0;
                   16074:             if (ref($cats[0]) eq 'ARRAY') {
                   16075:                 my @currcategories;
                   16076:                 if ($currcat ne '') {
                   16077:                     @currcategories = split('&',$currcat);
                   16078:                 }
1.919     raeburn  16079:                 my $table;
1.663     raeburn  16080:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16081:                     my $parent = $cats[0][$i];
1.919     raeburn  16082:                     next if ($parent eq 'instcode');
                   16083:                     if ($type eq 'Community') {
                   16084:                         next unless ($parent eq 'communities');
                   16085:                     } else {
                   16086:                         next if ($parent eq 'communities');
                   16087:                     }
1.663     raeburn  16088:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16089:                     my $item = &escape($parent).'::0';
                   16090:                     my $checked = '';
                   16091:                     if (@currcategories > 0) {
                   16092:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16093:                             $checked = ' checked="checked"';
1.663     raeburn  16094:                         }
                   16095:                     }
1.919     raeburn  16096:                     my $parent_title = $parent;
                   16097:                     if ($parent eq 'communities') {
                   16098:                         $parent_title = &mt('Communities');
                   16099:                     }
                   16100:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16101:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16102:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16103:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16104:                     my $depth = 1;
                   16105:                     push(@path,$parent);
1.1075.2.117  raeburn  16106:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16107:                     pop(@path);
1.919     raeburn  16108:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16109:                     $itemcount ++;
                   16110:                 }
1.919     raeburn  16111:                 if ($itemcount) {
                   16112:                     $output = &Apache::loncommon::start_data_table().
                   16113:                               $table.
                   16114:                               &Apache::loncommon::end_data_table();
                   16115:                 }
1.663     raeburn  16116:             }
                   16117:         }
                   16118:     }
                   16119:     return $output;
                   16120: }
                   16121: 
                   16122: =pod
                   16123: 
1.1075.2.56  raeburn  16124: =item * &assign_category_rows()
1.663     raeburn  16125: 
                   16126: Create a datatable row for display of nested categories in a domain,
                   16127: with checkboxes to allow a course to be categorized,called recursively.
                   16128: 
                   16129: Inputs:
                   16130: 
                   16131: itemcount - track row number for alternating colors
                   16132: 
                   16133: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16134:       categories and subcategories.
                   16135: 
                   16136: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16137: 
                   16138: parent - parent of current category item
                   16139: 
                   16140: path - Array containing all categories back up through the hierarchy from the
                   16141:        current category to the top level.
                   16142: 
                   16143: currcategories - reference to array of current categories assigned to the course
                   16144: 
1.1075.2.117  raeburn  16145: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16146:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16147: 
1.663     raeburn  16148: Returns: $output (markup to be displayed).
                   16149: 
                   16150: =cut
                   16151: 
                   16152: sub assign_category_rows {
1.1075.2.117  raeburn  16153:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16154:     my ($text,$name,$item,$chgstr);
                   16155:     if (ref($cats) eq 'ARRAY') {
                   16156:         my $maxdepth = scalar(@{$cats});
                   16157:         if (ref($cats->[$depth]) eq 'HASH') {
                   16158:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16159:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16160:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  16161:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16162:                 for (my $j=0; $j<$numchildren; $j++) {
                   16163:                     $name = $cats->[$depth]{$parent}[$j];
                   16164:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16165:                     my $deeper = $depth+1;
                   16166:                     my $checked = '';
                   16167:                     if (ref($currcategories) eq 'ARRAY') {
                   16168:                         if (@{$currcategories} > 0) {
                   16169:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16170:                                 $checked = ' checked="checked"';
1.663     raeburn  16171:                             }
                   16172:                         }
                   16173:                     }
1.664     raeburn  16174:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16175:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16176:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16177:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16178:                              '</td><td>';
1.663     raeburn  16179:                     if (ref($path) eq 'ARRAY') {
                   16180:                         push(@{$path},$name);
1.1075.2.117  raeburn  16181:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16182:                         pop(@{$path});
                   16183:                     }
                   16184:                     $text .= '</td></tr>';
                   16185:                 }
                   16186:                 $text .= '</table></td>';
                   16187:             }
                   16188:         }
                   16189:     }
                   16190:     return $text;
                   16191: }
                   16192: 
1.1075.2.69  raeburn  16193: =pod
                   16194: 
                   16195: =back
                   16196: 
                   16197: =cut
                   16198: 
1.655     raeburn  16199: ############################################################
                   16200: ############################################################
                   16201: 
                   16202: 
1.443     albertel 16203: sub commit_customrole {
1.664     raeburn  16204:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16205:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16206:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16207:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16208:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16209:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16210:                  '</b><br />';
                   16211:     return $output;
                   16212: }
                   16213: 
                   16214: sub commit_standardrole {
1.1075.2.31  raeburn  16215:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16216:     my ($output,$logmsg,$linefeed);
                   16217:     if ($context eq 'auto') {
                   16218:         $linefeed = "\n";
                   16219:     } else {
                   16220:         $linefeed = "<br />\n";
                   16221:     }  
1.443     albertel 16222:     if ($three eq 'st') {
1.541     raeburn  16223:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  16224:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16225:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16226:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16227:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16228:         } else {
1.541     raeburn  16229:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16230:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16231:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16232:             if ($context eq 'auto') {
                   16233:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16234:             } else {
                   16235:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16236:                &mt('Add to classlist').': <b>ok</b>';
                   16237:             }
                   16238:             $output .= $linefeed;
1.443     albertel 16239:         }
                   16240:     } else {
                   16241:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16242:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16243:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16244:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16245:         if ($context eq 'auto') {
                   16246:             $output .= $result.$linefeed;
                   16247:         } else {
                   16248:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16249:         }
1.443     albertel 16250:     }
                   16251:     return $output;
                   16252: }
                   16253: 
                   16254: sub commit_studentrole {
1.1075.2.31  raeburn  16255:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16256:         $credits) = @_;
1.626     raeburn  16257:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16258:     if ($context eq 'auto') {
                   16259:         $linefeed = "\n";
                   16260:     } else {
                   16261:         $linefeed = '<br />'."\n";
                   16262:     }
1.443     albertel 16263:     if (defined($one) && defined($two)) {
                   16264:         my $cid=$one.'_'.$two;
                   16265:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16266:         my $secchange = 0;
                   16267:         my $expire_role_result;
                   16268:         my $modify_section_result;
1.628     raeburn  16269:         if ($oldsec ne '-1') { 
                   16270:             if ($oldsec ne $sec) {
1.443     albertel 16271:                 $secchange = 1;
1.628     raeburn  16272:                 my $now = time;
1.443     albertel 16273:                 my $uurl='/'.$cid;
                   16274:                 $uurl=~s/\_/\//g;
                   16275:                 if ($oldsec) {
                   16276:                     $uurl.='/'.$oldsec;
                   16277:                 }
1.626     raeburn  16278:                 $oldsecurl = $uurl;
1.628     raeburn  16279:                 $expire_role_result = 
1.1075.2.161.  .14(raeb 16280:-23):                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
1.628     raeburn  16281:                 if ($env{'request.course.sec'} ne '') { 
                   16282:                     if ($expire_role_result eq 'refused') {
                   16283:                         my @roles = ('st');
                   16284:                         my @statuses = ('previous');
                   16285:                         my @roledoms = ($one);
                   16286:                         my $withsec = 1;
                   16287:                         my %roleshash = 
                   16288:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16289:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16290:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16291:                             my ($oldstart,$oldend) = 
                   16292:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16293:                             if ($oldend > 0 && $oldend <= $now) {
                   16294:                                 $expire_role_result = 'ok';
                   16295:                             }
                   16296:                         }
                   16297:                     }
                   16298:                 }
1.443     albertel 16299:                 $result = $expire_role_result;
                   16300:             }
                   16301:         }
                   16302:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  16303:             $modify_section_result = 
                   16304:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16305:                                                            undef,undef,undef,$sec,
                   16306:                                                            $end,$start,'','',$cid,
                   16307:                                                            '',$context,$credits);
1.443     albertel 16308:             if ($modify_section_result =~ /^ok/) {
                   16309:                 if ($secchange == 1) {
1.628     raeburn  16310:                     if ($sec eq '') {
                   16311:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16312:                     } else {
                   16313:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16314:                     }
1.443     albertel 16315:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16316:                     if ($sec eq '') {
                   16317:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16318:                     } else {
                   16319:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16320:                     }
1.443     albertel 16321:                 } else {
1.628     raeburn  16322:                     if ($sec eq '') {
                   16323:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16324:                     } else {
                   16325:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16326:                     }
1.443     albertel 16327:                 }
                   16328:             } else {
1.628     raeburn  16329:                 if ($secchange) {       
                   16330:                     $$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;
                   16331:                 } else {
                   16332:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16333:                 }
1.443     albertel 16334:             }
                   16335:             $result = $modify_section_result;
                   16336:         } elsif ($secchange == 1) {
1.628     raeburn  16337:             if ($oldsec eq '') {
1.1075.2.20  raeburn  16338:                 $$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  16339:             } else {
                   16340:                 $$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;
                   16341:             }
1.626     raeburn  16342:             if ($expire_role_result eq 'refused') {
                   16343:                 my $newsecurl = '/'.$cid;
                   16344:                 $newsecurl =~ s/\_/\//g;
                   16345:                 if ($sec ne '') {
                   16346:                     $newsecurl.='/'.$sec;
                   16347:                 }
                   16348:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16349:                     if ($sec eq '') {
                   16350:                         $$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;
                   16351:                     } else {
                   16352:                         $$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;
                   16353:                     }
                   16354:                 }
                   16355:             }
1.443     albertel 16356:         }
                   16357:     } else {
1.626     raeburn  16358:         $$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 16359:         $result = "error: incomplete course id\n";
                   16360:     }
                   16361:     return $result;
                   16362: }
                   16363: 
1.1075.2.25  raeburn  16364: sub show_role_extent {
                   16365:     my ($scope,$context,$role) = @_;
                   16366:     $scope =~ s{^/}{};
                   16367:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16368:     push(@courseroles,'co');
                   16369:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16370:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16371:         $scope =~ s{/}{_};
                   16372:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16373:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16374:         my ($audom,$auname) = split(/\//,$scope);
                   16375:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16376:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16377:     } else {
                   16378:         $scope =~ s{/$}{};
                   16379:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16380:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16381:     }
                   16382: }
                   16383: 
1.443     albertel 16384: ############################################################
                   16385: ############################################################
                   16386: 
1.566     albertel 16387: sub check_clone {
1.578     raeburn  16388:     my ($args,$linefeed) = @_;
1.566     albertel 16389:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16390:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16391:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 16392:21):     my $clonetitle;
                   16393:21):     my @clonemsg;
1.566     albertel 16394:     my $can_clone = 0;
1.944     raeburn  16395:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16396:     if ($lctype ne 'community') {
                   16397:         $lctype = 'course';
                   16398:     }
1.566     albertel 16399:     if ($clonehome eq 'no_host') {
1.944     raeburn  16400:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16401:21):             push(@clonemsg,({
                   16402:21):                               mt => 'No new community created.',
                   16403:21):                               args => [],
                   16404:21):                             },
                   16405:21):                             {
                   16406:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16407:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16408:21):                             }));
1.908     raeburn  16409:         } else {
1.1075.2.161.  .1(raebu 16410:21):             push(@clonemsg,({
                   16411:21):                               mt => 'No new course created.',
                   16412:21):                               args => [],
                   16413:21):                             },
                   16414:21):                             {
                   16415:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16416:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16417:21):                             }));
                   16418:21):         }
1.566     albertel 16419:     } else {
                   16420: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 16421:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16422:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16423:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 16424:21):                 push(@clonemsg,({
                   16425:21):                                   mt => 'No new community created.',
                   16426:21):                                   args => [],
                   16427:21):                                 },
                   16428:21):                                 {
                   16429:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16430:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16431:21):                                 }));
                   16432:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16433:             }
                   16434:         }
1.1075.2.119  raeburn  16435: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16436:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16437: 	    $can_clone = 1;
                   16438: 	} else {
1.1075.2.95  raeburn  16439: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16440: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  16441:             if ($clonehash{'cloners'} eq '') {
                   16442:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16443:                 if ($domdefs{'canclone'}) {
                   16444:                     unless ($domdefs{'canclone'} eq 'none') {
                   16445:                         if ($domdefs{'canclone'} eq 'domain') {
                   16446:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16447:                                 $can_clone = 1;
                   16448:                             }
                   16449:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16450:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16451:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16452:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16453:                                 $can_clone = 1;
                   16454:                             }
                   16455:                         }
                   16456:                     }
1.908     raeburn  16457:                 }
1.1075.2.95  raeburn  16458:             } else {
                   16459: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16460:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16461:                     $can_clone = 1;
1.1075.2.95  raeburn  16462:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16463:                     $can_clone = 1;
1.1075.2.96  raeburn  16464:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16465:                     $can_clone = 1;
1.1075.2.95  raeburn  16466:                 }
                   16467:                 unless ($can_clone) {
1.1075.2.96  raeburn  16468:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16469:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  16470:                         my (%gotdomdefaults,%gotcodedefaults);
                   16471:                         foreach my $cloner (@cloners) {
                   16472:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16473:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16474:                                 my (%codedefaults,@code_order);
                   16475:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16476:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16477:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16478:                                     }
                   16479:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16480:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16481:                                     }
                   16482:                                 } else {
                   16483:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16484:                                                                             \%codedefaults,
                   16485:                                                                             \@code_order);
                   16486:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16487:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16488:                                 }
                   16489:                                 if (@code_order > 0) {
                   16490:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16491:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16492:                                                                                 $args->{'crscode'})) {
                   16493:                                         $can_clone = 1;
                   16494:                                         last;
                   16495:                                     }
                   16496:                                 }
                   16497:                             }
                   16498:                         }
                   16499:                     }
1.1075.2.96  raeburn  16500:                 }
                   16501:             }
                   16502:             unless ($can_clone) {
                   16503:                 my $ccrole = 'cc';
                   16504:                 if ($args->{'crstype'} eq 'Community') {
                   16505:                     $ccrole = 'co';
                   16506:                 }
                   16507:                 my %roleshash =
                   16508:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16509:                                                   $args->{'ccdomain'},
                   16510:                                                   'userroles',['active'],[$ccrole],
                   16511:                                                   [$args->{'clonedomain'}]);
                   16512:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16513:                     $can_clone = 1;
                   16514:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16515:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16516:                     $can_clone = 1;
1.1075.2.95  raeburn  16517:                 }
                   16518:             }
                   16519:             unless ($can_clone) {
                   16520:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16521:21):                     push(@clonemsg,({
                   16522:21):                                       mt => 'No new community created.',
                   16523:21):                                       args => [],
                   16524:21):                                     },
                   16525:21):                                     {
                   16526:21):                                       mt => 'The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',
                   16527:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16528:21):                                     }));
1.1075.2.95  raeburn  16529:                 } else {
1.1075.2.161.  .1(raebu 16530:21):                     push(@clonemsg,({
                   16531:21):                                       mt => 'No new course created.',
                   16532:21):                                       args => [],
                   16533:21):                                     },
                   16534:21):                                     {
                   16535:21):                                       mt => 'The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',
                   16536:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16537:21):                                     }));
1.578     raeburn  16538: 	        }
1.566     albertel 16539: 	    }
1.578     raeburn  16540:         }
1.566     albertel 16541:     }
1.1075.2.161.  .1(raebu 16542:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16543: }
                   16544: 
1.444     albertel 16545: sub construct_course {
1.1075.2.119  raeburn  16546:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16547:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16548:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16549:     my $linefeed =  '<br />'."\n";
                   16550:     if ($context eq 'auto') {
                   16551:         $linefeed = "\n";
                   16552:     }
1.566     albertel 16553: 
                   16554: #
                   16555: # Are we cloning?
                   16556: #
1.1075.2.161.  .1(raebu 16557:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16558:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16559:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16560:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16561:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16562: 	}
                   16563:     }
                   16564: 
1.444     albertel 16565: #
                   16566: # Open course
                   16567: #
                   16568:     my $crstype = lc($args->{'crstype'});
                   16569:     my %cenv=();
                   16570:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16571:                                              $args->{'cdescr'},
                   16572:                                              $args->{'curl'},
                   16573:                                              $args->{'course_home'},
                   16574:                                              $args->{'nonstandard'},
                   16575:                                              $args->{'crscode'},
                   16576:                                              $args->{'ccuname'}.':'.
                   16577:                                              $args->{'ccdomain'},
1.882     raeburn  16578:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16579:21):                                              $cnum,$context,$category,
                   16580:21):                                              $callercontext);
1.444     albertel 16581: 
                   16582:     # Note: The testing routines depend on this being output; see 
                   16583:     # Utils::Course. This needs to at least be output as a comment
                   16584:     # if anyone ever decides to not show this, and Utils::Course::new
                   16585:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16586:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16587:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16588:21):     } else {
                   16589:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16590:21):     }
1.943     raeburn  16591:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16592:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16593:     }
                   16594: 
1.444     albertel 16595: #
                   16596: # Check if created correctly
                   16597: #
1.479     albertel 16598:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16599:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16600:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16601:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16602:21):             $outcome .= &mt_user($user_lh,
                   16603:21):                             'Course creation failed, unrecognized course home server.');
                   16604:21):         } else {
                   16605:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16606:21):         }
                   16607:21):         $outcome .= $linefeed;
                   16608:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16609:     }
1.541     raeburn  16610:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16611: 
1.444     albertel 16612: #
1.566     albertel 16613: # Do the cloning
1.1075.2.161.  .1(raebu 16614:21): #
                   16615:21):     my @clonemsg;
1.566     albertel 16616:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16617:21):         push(@clonemsg,
                   16618:21):                       {
                   16619:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16620:21):                           args => [$crstype,$clonetitle],
                   16621:21):                       });
1.566     albertel 16622: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16623: # Copy all files
1.1075.2.161.  .1(raebu 16624:21):         my @info =
                   16625:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16626:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16627:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16628:21):                                                      $args->{'tinyurls'});
                   16629:21):         if (@info) {
                   16630:21):             push(@clonemsg,@info);
                   16631:21):         }
1.444     albertel 16632: # Restore URL
1.566     albertel 16633: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16634: # Restore title
1.566     albertel 16635: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16636: # Restore creation date, creator and creation context.
                   16637:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16638:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16639:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16640: # Mark as cloned
1.566     albertel 16641: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16642: # Need to clone grading mode
                   16643:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16644:         $cenv{'grading'}=$newenv{'grading'};
                   16645: # Do not clone these environment entries
                   16646:         &Apache::lonnet::del('environment',
                   16647:                   ['default_enrollment_start_date',
                   16648:                    'default_enrollment_end_date',
                   16649:                    'question.email',
                   16650:                    'policy.email',
                   16651:                    'comment.email',
                   16652:                    'pch.users.denied',
1.725     raeburn  16653:                    'plc.users.denied',
                   16654:                    'hidefromcat',
1.1075.2.36  raeburn  16655:                    'checkforpriv',
1.1075.2.158  raeburn  16656:                    'categories'],
1.638     www      16657:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16658:         if ($args->{'textbook'}) {
                   16659:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16660:         }
1.444     albertel 16661:     }
1.566     albertel 16662: 
1.444     albertel 16663: #
                   16664: # Set environment (will override cloned, if existing)
                   16665: #
                   16666:     my @sections = ();
                   16667:     my @xlists = ();
                   16668:     if ($args->{'crstype'}) {
                   16669:         $cenv{'type'}=$args->{'crstype'};
                   16670:     }
1.1075.2.161.  .17(raeb 16671:-23):     if ($args->{'lti'}) {
                   16672:-23):         $cenv{'internal.lti'}=$args->{'lti'};
                   16673:-23):     }
1.444     albertel 16674:     if ($args->{'crsid'}) {
                   16675:         $cenv{'courseid'}=$args->{'crsid'};
                   16676:     }
                   16677:     if ($args->{'crscode'}) {
                   16678:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16679:     }
                   16680:     if ($args->{'crsquota'} ne '') {
                   16681:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16682:     } else {
                   16683:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16684:     }
                   16685:     if ($args->{'ccuname'}) {
                   16686:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16687:                                         ':'.$args->{'ccdomain'};
                   16688:     } else {
                   16689:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16690:     }
1.1075.2.31  raeburn  16691:     if ($args->{'defaultcredits'}) {
                   16692:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16693:     }
1.444     albertel 16694:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1075.2.161.  .20(raeb 16695:-23):     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 16696:     if ($args->{'crssections'}) {
                   16697:         $cenv{'internal.sectionnums'} = '';
                   16698:         if ($args->{'crssections'} =~ m/,/) {
                   16699:             @sections = split/,/,$args->{'crssections'};
                   16700:         } else {
                   16701:             $sections[0] = $args->{'crssections'};
                   16702:         }
                   16703:         if (@sections > 0) {
                   16704:             foreach my $item (@sections) {
                   16705:                 my ($sec,$gp) = split/:/,$item;
                   16706:                 my $class = $args->{'crscode'}.$sec;
                   16707:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16708:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1075.2.161.  .20(raeb 16709:-23):                 if ($addcheck eq 'ok') {
                   16710:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16711:-23):                         push(@oklcsecs,$gp);
                   16712:-23):                     }
                   16713:-23):                 } else {
1.1075.2.119  raeburn  16714:                     push(@badclasses,$class);
1.444     albertel 16715:                 }
                   16716:             }
                   16717:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16718:         }
                   16719:     }
                   16720: # do not hide course coordinator from staff listing, 
                   16721: # even if privileged
                   16722:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16723: # add course coordinator's domain to domains to check for privileged users
                   16724: # if different to course domain
                   16725:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16726:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16727:     }
1.444     albertel 16728: # add crosslistings
                   16729:     if ($args->{'crsxlist'}) {
                   16730:         $cenv{'internal.crosslistings'}='';
                   16731:         if ($args->{'crsxlist'} =~ m/,/) {
                   16732:             @xlists = split/,/,$args->{'crsxlist'};
                   16733:         } else {
                   16734:             $xlists[0] = $args->{'crsxlist'};
                   16735:         }
                   16736:         if (@xlists > 0) {
                   16737:             foreach my $item (@xlists) {
                   16738:                 my ($xl,$gp) = split/:/,$item;
                   16739:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16740:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1075.2.161.  .20(raeb 16741:-23):                 if ($addcheck eq 'ok') {
                   16742:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16743:-23):                         push(@oklcsecs,$gp);
                   16744:-23):                     }
                   16745:-23):                 } else {
1.1075.2.119  raeburn  16746:                     push(@badclasses,$xl);
1.444     albertel 16747:                 }
                   16748:             }
                   16749:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16750:         }
                   16751:     }
                   16752:     if ($args->{'autoadds'}) {
                   16753:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16754:     }
                   16755:     if ($args->{'autodrops'}) {
                   16756:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16757:     }
                   16758: # check for notification of enrollment changes
                   16759:     my @notified = ();
                   16760:     if ($args->{'notify_owner'}) {
                   16761:         if ($args->{'ccuname'} ne '') {
                   16762:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16763:         }
                   16764:     }
                   16765:     if ($args->{'notify_dc'}) {
                   16766:         if ($uname ne '') { 
1.630     raeburn  16767:             push(@notified,$uname.':'.$udom);
1.444     albertel 16768:         }
                   16769:     }
                   16770:     if (@notified > 0) {
                   16771:         my $notifylist;
                   16772:         if (@notified > 1) {
                   16773:             $notifylist = join(',',@notified);
                   16774:         } else {
                   16775:             $notifylist = $notified[0];
                   16776:         }
                   16777:         $cenv{'internal.notifylist'} = $notifylist;
                   16778:     }
                   16779:     if (@badclasses > 0) {
                   16780:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16781:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16782:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16783:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16784:         );
1.1075.2.119  raeburn  16785:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16786:                            &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  16787:         if ($context eq 'auto') {
                   16788:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16789:         } else {
1.566     albertel 16790:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16791:         }
                   16792:         foreach my $item (@badclasses) {
1.541     raeburn  16793:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16794:                 $outcome .= " - $item\n";
1.541     raeburn  16795:             } else {
1.1075.2.119  raeburn  16796:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16797:             }
1.1075.2.119  raeburn  16798:         }
                   16799:         if ($context eq 'auto') {
                   16800:             $outcome .= $linefeed;
                   16801:         } else {
                   16802:             $outcome .= "</ul><br /><br /></div>\n";
                   16803:         }
1.444     albertel 16804:     }
                   16805:     if ($args->{'no_end_date'}) {
                   16806:         $args->{'endaccess'} = 0;
                   16807:     }
1.1075.2.161.  .20(raeb 16808:-23): #  If an official course with institutional sections is created by cloning
                   16809:-23): #  an existing course, section-specific hiding of course totals in student's
                   16810:-23): #  view of grades as copied from cloned course, will be checked for valid
                   16811:-23): #  sections.
                   16812:-23):     if (($can_clone && $cloneid) &&
                   16813:-23):         ($cenv{'internal.coursecode'} ne '') &&
                   16814:-23):         ($cenv{'grading'} eq 'standard') &&
                   16815:-23):         ($cenv{'hidetotals'} ne '') &&
                   16816:-23):         ($cenv{'hidetotals'} ne 'all')) {
                   16817:-23):         my @hidesecs;
                   16818:-23):         my $deletehidetotals;
                   16819:-23):         if (@oklcsecs) {
                   16820:-23):             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   16821:-23):                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   16822:-23):                     push(@hidesecs,$sec);
                   16823:-23):                 }
                   16824:-23):             }
                   16825:-23):             if (@hidesecs) {
                   16826:-23):                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   16827:-23):             } else {
                   16828:-23):                 $deletehidetotals = 1;
                   16829:-23):             }
                   16830:-23):         } else {
                   16831:-23):             $deletehidetotals = 1;
                   16832:-23):         }
                   16833:-23):         if ($deletehidetotals) {
                   16834:-23):             delete($cenv{'hidetotals'});
                   16835:-23):             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   16836:-23):         }
                   16837:-23):     }
1.444     albertel 16838:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16839:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16840:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16841:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16842:     if ($args->{'showphotos'}) {
                   16843:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16844:     }
                   16845:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16846:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16847:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16848:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16849:             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'); 
                   16850:             if ($context eq 'auto') {
                   16851:                 $outcome .= $krb_msg;
                   16852:             } else {
1.566     albertel 16853:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16854:             }
                   16855:             $outcome .= $linefeed;
1.444     albertel 16856:         }
                   16857:     }
                   16858:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16859:        if ($args->{'setpolicy'}) {
                   16860:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16861:        }
                   16862:        if ($args->{'setcontent'}) {
                   16863:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16864:        }
1.1075.2.110  raeburn  16865:        if ($args->{'setcomment'}) {
                   16866:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16867:        }
1.444     albertel 16868:     }
                   16869:     if ($args->{'reshome'}) {
                   16870: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16871: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16872:     }
                   16873: #
                   16874: # course has keyed access
                   16875: #
                   16876:     if ($args->{'setkeys'}) {
                   16877:        $cenv{'keyaccess'}='yes';
                   16878:     }
                   16879: # if specified, key authority is not course, but user
                   16880: # only active if keyaccess is yes
                   16881:     if ($args->{'keyauth'}) {
1.487     albertel 16882: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16883: 	$user = &LONCAPA::clean_username($user);
                   16884: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16885: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16886: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16887: 	}
                   16888:     }
                   16889: 
1.1075.2.59  raeburn  16890: #
                   16891: #  generate and store uniquecode (available to course requester), if course should have one.
                   16892: #
                   16893:     if ($args->{'uniquecode'}) {
                   16894:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16895:         if ($code) {
                   16896:             $cenv{'internal.uniquecode'} = $code;
                   16897:             my %crsinfo =
                   16898:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16899:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16900:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16901:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16902:             }
                   16903:             if (ref($coderef)) {
                   16904:                 $$coderef = $code;
                   16905:             }
                   16906:         }
                   16907:     }
                   16908: 
1.444     albertel 16909:     if ($args->{'disresdis'}) {
                   16910:         $cenv{'pch.roles.denied'}='st';
                   16911:     }
                   16912:     if ($args->{'disablechat'}) {
                   16913:         $cenv{'plc.roles.denied'}='st';
                   16914:     }
                   16915: 
                   16916:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16917:     # course
                   16918:     $cenv{'course.helper.not.run'} = 1;
                   16919:     #
                   16920:     # Use new Randomseed
                   16921:     #
                   16922:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16923:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16924:     #
                   16925:     # The encryption code and receipt prefix for this course
                   16926:     #
                   16927:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16928:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16929:     #
                   16930:     # By default, use standard grading
                   16931:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16932: 
1.541     raeburn  16933:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16934:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16935: #
                   16936: # Open all assignments
                   16937: #
                   16938:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16939:        my $opendate = time;
                   16940:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16941:            $opendate = $args->{'openallfrom'};
                   16942:        }
1.444     albertel 16943:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16944:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16945:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16946:        $outcome .= &mt('All assignments open starting [_1]',
                   16947:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16948:                    &Apache::lonnet::cput
                   16949:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16950:    }
                   16951: #
                   16952: # Set first page
                   16953: #
                   16954:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16955: 	    || ($cloneid)) {
                   16956: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16957: 
                   16958: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16959:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16960: 
1.444     albertel 16961:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16962:         my $title; my $url;
                   16963:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16964: 	    $title=&mt('Syllabus');
1.444     albertel 16965:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16966:         } else {
1.963     raeburn  16967:             $title=&mt('Table of Contents');
1.444     albertel 16968:             $url='/adm/navmaps';
                   16969:         }
1.445     albertel 16970: 
                   16971:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16972: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16973: 
                   16974: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16975:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16976:     }
1.566     albertel 16977: 
1.1075.2.161.  .1(raebu 16978:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16979: }
                   16980: 
1.1075.2.59  raeburn  16981: sub make_unique_code {
                   16982:     my ($cdom,$cnum) = @_;
                   16983:     # get lock on uniquecodes db
                   16984:     my $lockhash = {
                   16985:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16986:                                                   ':'.$env{'user.domain'},
                   16987:                    };
                   16988:     my $tries = 0;
                   16989:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16990:     my ($code,$error);
                   16991: 
                   16992:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16993:         $tries ++;
                   16994:         sleep 1;
                   16995:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16996:     }
                   16997:     if ($gotlock eq 'ok') {
                   16998:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16999:         my $gotcode;
                   17000:         my $attempts = 0;
                   17001:         while ((!$gotcode) && ($attempts < 100)) {
                   17002:             $code = &generate_code();
                   17003:             if (!exists($currcodes{$code})) {
                   17004:                 $gotcode = 1;
                   17005:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17006:                     $error = 'nostore';
                   17007:                 }
                   17008:             }
                   17009:             $attempts ++;
                   17010:         }
                   17011:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17012:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17013:     } else {
                   17014:         $error = 'nolock';
                   17015:     }
                   17016:     return ($code,$error);
                   17017: }
                   17018: 
                   17019: sub generate_code {
                   17020:     my $code;
                   17021:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17022:     for (my $i=0; $i<6; $i++) {
                   17023:         my $lettnum = int (rand 2);
                   17024:         my $item = '';
                   17025:         if ($lettnum) {
                   17026:             $item = $letts[int( rand(18) )];
                   17027:         } else {
                   17028:             $item = 1+int( rand(8) );
                   17029:         }
                   17030:         $code .= $item;
                   17031:     }
                   17032:     return $code;
                   17033: }
                   17034: 
1.444     albertel 17035: ############################################################
                   17036: ############################################################
                   17037: 
1.953     droeschl 17038: #SD
                   17039: # only Community and Course, or anything else?
1.378     raeburn  17040: sub course_type {
                   17041:     my ($cid) = @_;
                   17042:     if (!defined($cid)) {
                   17043:         $cid = $env{'request.course.id'};
                   17044:     }
1.404     albertel 17045:     if (defined($env{'course.'.$cid.'.type'})) {
                   17046:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17047:     } else {
                   17048:         return 'Course';
1.377     raeburn  17049:     }
                   17050: }
1.156     albertel 17051: 
1.406     raeburn  17052: sub group_term {
                   17053:     my $crstype = &course_type();
                   17054:     my %names = (
                   17055:                   'Course' => 'group',
1.865     raeburn  17056:                   'Community' => 'group',
1.406     raeburn  17057:                 );
                   17058:     return $names{$crstype};
                   17059: }
                   17060: 
1.902     raeburn  17061: sub course_types {
1.1075.2.161.  .17(raeb 17062:-23):     my @types = ('official','unofficial','community','textbook','lti');
1.902     raeburn  17063:     my %typename = (
                   17064:                          official   => 'Official course',
                   17065:                          unofficial => 'Unofficial course',
                   17066:                          community  => 'Community',
1.1075.2.59  raeburn  17067:                          textbook   => 'Textbook course',
1.1075.2.161.  .17(raeb 17068:-23):                          lti        => 'LTI provider',
1.902     raeburn  17069:                    );
                   17070:     return (\@types,\%typename);
                   17071: }
                   17072: 
1.156     albertel 17073: sub icon {
                   17074:     my ($file)=@_;
1.505     albertel 17075:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17076:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17077:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17078:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17079: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17080: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17081: 	            $curfext.".gif") {
                   17082: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17083: 		$curfext.".gif";
                   17084: 	}
                   17085:     }
1.249     albertel 17086:     return &lonhttpdurl($iconname);
1.154     albertel 17087: } 
1.84      albertel 17088: 
1.575     albertel 17089: sub lonhttpdurl {
1.692     www      17090: #
                   17091: # Had been used for "small fry" static images on separate port 8080.
                   17092: # Modify here if lightweight http functionality desired again.
                   17093: # Currently eliminated due to increasing firewall issues.
                   17094: #
1.575     albertel 17095:     my ($url)=@_;
1.692     www      17096:     return $url;
1.215     albertel 17097: }
                   17098: 
1.213     albertel 17099: sub connection_aborted {
                   17100:     my ($r)=@_;
                   17101:     $r->print(" ");$r->rflush();
                   17102:     my $c = $r->connection;
                   17103:     return $c->aborted();
                   17104: }
                   17105: 
1.221     foxr     17106: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17107: #    strings as 'strings'.
                   17108: sub escape_single {
1.221     foxr     17109:     my ($input) = @_;
1.223     albertel 17110:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17111:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17112:     return $input;
                   17113: }
1.223     albertel 17114: 
1.222     foxr     17115: #  Same as escape_single, but escape's "'s  This 
                   17116: #  can be used for  "strings"
                   17117: sub escape_double {
                   17118:     my ($input) = @_;
                   17119:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17120:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17121:     return $input;
                   17122: }
1.223     albertel 17123:  
1.222     foxr     17124: #   Escapes the last element of a full URL.
                   17125: sub escape_url {
                   17126:     my ($url)   = @_;
1.238     raeburn  17127:     my @urlslices = split(/\//, $url,-1);
1.369     www      17128:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  17129:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17130: }
1.462     albertel 17131: 
1.820     raeburn  17132: sub compare_arrays {
                   17133:     my ($arrayref1,$arrayref2) = @_;
                   17134:     my (@difference,%count);
                   17135:     @difference = ();
                   17136:     %count = ();
                   17137:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17138:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17139:         foreach my $element (keys(%count)) {
                   17140:             if ($count{$element} == 1) {
                   17141:                 push(@difference,$element);
                   17142:             }
                   17143:         }
                   17144:     }
                   17145:     return @difference;
                   17146: }
                   17147: 
1.1075.2.152  raeburn  17148: sub lon_status_items {
                   17149:     my %defaults = (
                   17150:                      E         => 100,
                   17151:                      W         => 4,
                   17152:                      N         => 1,
                   17153:                      U         => 5,
                   17154:                      threshold => 200,
                   17155:                      sysmail   => 2500,
                   17156:                    );
                   17157:     my %names = (
                   17158:                    E => 'Errors',
                   17159:                    W => 'Warnings',
                   17160:                    N => 'Notices',
                   17161:                    U => 'Unsent',
                   17162:                 );
                   17163:     return (\%defaults,\%names);
                   17164: }
                   17165: 
1.817     bisitz   17166: # -------------------------------------------------------- Initialize user login
1.462     albertel 17167: sub init_user_environment {
1.463     albertel 17168:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17169:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17170: 
                   17171:     my $public=($username eq 'public' && $domain eq 'public');
                   17172: 
                   17173: # See if old ID present, if so, remove
                   17174: 
1.1075.2.161.  .22(raeb 17175:-24):     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17176:-24):         $coauthorenv);
1.462     albertel 17177:     my $now=time;
                   17178: 
                   17179:     if ($public) {
                   17180: 	my $max_public=100;
                   17181: 	my $oldest;
                   17182: 	my $oldest_time=0;
                   17183: 	for(my $next=1;$next<=$max_public;$next++) {
                   17184: 	    if (-e $lonids."/publicuser_$next.id") {
                   17185: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17186: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17187: 		    $oldest_time=$mtime;
                   17188: 		    $oldest=$next;
                   17189: 		}
                   17190: 	    } else {
                   17191: 		$cookie="publicuser_$next";
                   17192: 		last;
                   17193: 	    }
                   17194: 	}
                   17195: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17196:     } else {
1.463     albertel 17197: 	# if this isn't a robot, kill any existing non-robot sessions
                   17198: 	if (!$args->{'robot'}) {
                   17199: 	    opendir(DIR,$lonids);
                   17200: 	    while ($filename=readdir(DIR)) {
                   17201: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  17202:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17203:                             &GDBM_READER(),0640)) {
                   17204:                         my $linkedfile;
                   17205:                         if (exists($oldenv{'user.linkedenv'})) {
                   17206:                             $linkedfile = $oldenv{'user.linkedenv'};
                   17207:                         }
                   17208:                         untie(%oldenv);
                   17209:                         if (unlink("$lonids/$filename")) {
                   17210:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17211:                                 if (-l "$lonids/$linkedfile.id") {
                   17212:                                     unlink("$lonids/$linkedfile.id");
                   17213:                                 }
                   17214:                             }
                   17215:                         }
                   17216:                     } else {
                   17217:                         unlink($lonids.'/'.$filename);
                   17218:                     }
1.463     albertel 17219: 		}
1.462     albertel 17220: 	    }
1.463     albertel 17221: 	    closedir(DIR);
1.1075.2.84  raeburn  17222: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17223:             my $namespace = 'nohist_courseeditor';
                   17224:             my $lockingkey = 'paste'."\0".'locked_num';
                   17225:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17226:                                                 $domain,$username);
                   17227:             if (exists($lockhash{$lockingkey})) {
                   17228:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17229:                 unless ($delresult eq 'ok') {
                   17230:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17231:                 }
                   17232:             }
1.462     albertel 17233: 	}
                   17234: # Give them a new cookie
1.463     albertel 17235: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17236: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17237: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17238:     
                   17239: # Initialize roles
                   17240: 
1.1075.2.161.  .22(raeb 17241:-24): 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17242:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17243:     }
                   17244: # ------------------------------------ Check browser type and MathML capability
                   17245: 
1.1075.2.77  raeburn  17246:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17247:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17248: 
                   17249: # ------------------------------------------------------------- Get environment
                   17250: 
                   17251:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17252:     my ($tmp) = keys(%userenv);
                   17253:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   17254:     } else {
                   17255: 	undef(%userenv);
                   17256:     }
                   17257:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17258: 	$form->{'interface'}=$userenv{'interface'};
                   17259:     }
                   17260:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17261: 
                   17262: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17263:     foreach my $option ('interface','localpath','localres') {
                   17264:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17265:     }
                   17266: # --------------------------------------------------------- Write first profile
                   17267: 
                   17268:     {
1.1075.2.150  raeburn  17269:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 17270: 	my %initial_env = 
                   17271: 	    ("user.name"          => $username,
                   17272: 	     "user.domain"        => $domain,
                   17273: 	     "user.home"          => $authhost,
                   17274: 	     "browser.type"       => $clientbrowser,
                   17275: 	     "browser.version"    => $clientversion,
                   17276: 	     "browser.mathml"     => $clientmathml,
                   17277: 	     "browser.unicode"    => $clientunicode,
                   17278: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  17279:              "browser.mobile"     => $clientmobile,
                   17280:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  17281:              "browser.osversion"  => $clientosversion,
1.462     albertel 17282: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17283: 	     "request.course.fn"  => '',
                   17284: 	     "request.course.uri" => '',
                   17285: 	     "request.course.sec" => '',
                   17286: 	     "request.role"       => 'cm',
                   17287: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  17288: 	     "request.host"       => $ip,);
1.462     albertel 17289: 
                   17290:         if ($form->{'localpath'}) {
                   17291: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17292: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17293:         }
                   17294: 	
                   17295: 	if ($form->{'interface'}) {
                   17296: 	    $form->{'interface'}=~s/\W//gs;
                   17297: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17298: 	    $env{'browser.interface'}=$form->{'interface'};
                   17299: 	}
                   17300: 
1.1075.2.54  raeburn  17301:         if ($form->{'iptoken'}) {
                   17302:             my $lonhost = $r->dir_config('lonHostID');
                   17303:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17304:             $env{'user.noloadbalance'} = $lonhost;
                   17305:         }
                   17306: 
1.1075.2.120  raeburn  17307:         if ($form->{'noloadbalance'}) {
                   17308:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17309:             my $hosthere = $form->{'noloadbalance'};
                   17310:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17311:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17312:                 $env{'user.noloadbalance'} = $hosthere;
                   17313:             }
                   17314:         }
                   17315: 
1.1016    raeburn  17316:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  17317:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17318:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  17319: 
1.1075.2.161.  .10(raeb 17320:-22):             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1075.2.125  raeburn  17321:                 $userenv{'availabletools.'.$tool} = 
                   17322:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17323:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17324:             }
1.724     raeburn  17325: 
1.1075.2.161.  .17(raeb 17326:-23):             foreach my $crstype ('official','unofficial','community','textbook','lti') {
1.1075.2.125  raeburn  17327:                 $userenv{'canrequest.'.$crstype} =
                   17328:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17329:                                                       'reload','requestcourses',
                   17330:                                                       \%userenv,\%domdef,\%is_adv);
                   17331:             }
1.765     raeburn  17332: 
1.1075.2.161.  .21(raeb 17333:-24):             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   17334:-24):                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   17335:-24):                 if ($userenv{'authoreditors'}) {
                   17336:-24):                     $userenv{'editors'} = $userenv{'authoreditors'};
                   17337:-24):                 } elsif ($domdef{'editors'} ne '') {
                   17338:-24):                     $userenv{'editors'} = $domdef{'editors'};
                   17339:-24):                 } else {
                   17340:-24):                     $userenv{'editors'} = 'edit,xml';
                   17341:-24):                 }
          .25(raeb 17342:-24):                 if ($userenv{'authorarchive'}) {
                   17343:-24):                     $userenv{'canarchive'} = 1;
                   17344:-24):                 } elsif (($userenv{'authorarchive'} eq '') &&
                   17345:-24):                          ($domdef{'archive'})) {
                   17346:-24):                     $userenv{'canarchive'} = 1;
                   17347:-24):                 }
          .21(raeb 17348:-24):             }
                   17349:-24): 
1.1075.2.125  raeburn  17350:             $userenv{'canrequest.author'} =
                   17351:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17352:                                                   'reload','requestauthor',
                   17353:                                                   \%userenv,\%domdef,\%is_adv);
                   17354:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17355:                                                  $domain,$username);
                   17356:             my $reqstatus = $reqauthor{'author_status'};
                   17357:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   17358:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17359:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17360:                                                       $reqauthor{'author'}{'timestamp'};
                   17361:                 }
1.1075.2.14  raeburn  17362:             }
                   17363:         }
                   17364: 
1.462     albertel 17365: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17366: 
1.462     albertel 17367: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17368: 		 &GDBM_WRCREAT(),0640)) {
                   17369: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17370: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17371: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17372:             if (ref($firstaccenv) eq 'HASH') {
                   17373:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17374:             }
                   17375:             if (ref($timerintenv) eq 'HASH') {
                   17376:                 &_add_to_env(\%disk_env,$timerintenv);
                   17377:             }
1.1075.2.161.  .22(raeb 17378:-24):             if (ref($coauthorenv) eq 'HASH') {
                   17379:-24):                 if (keys(%{$coauthorenv})) {
                   17380:-24):                     &_add_to_env(\%disk_env,$coauthorenv);
                   17381:-24):                 }
                   17382:-24):             }
1.463     albertel 17383: 	    if (ref($args->{'extra_env'})) {
                   17384: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17385: 	    }
1.462     albertel 17386: 	    untie(%disk_env);
                   17387: 	} else {
1.705     tempelho 17388: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17389: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17390: 	    return 'error: '.$!;
                   17391: 	}
                   17392:     }
                   17393:     $env{'request.role'}='cm';
                   17394:     $env{'request.role.adv'}=$env{'user.adv'};
                   17395:     $env{'browser.type'}=$clientbrowser;
                   17396: 
                   17397:     return $cookie;
                   17398: 
                   17399: }
                   17400: 
                   17401: sub _add_to_env {
                   17402:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17403:     if (ref($env_data) eq 'HASH') {
                   17404:         while (my ($key,$value) = each(%$env_data)) {
                   17405: 	    $idf->{$prefix.$key} = $value;
                   17406: 	    $env{$prefix.$key}   = $value;
                   17407:         }
1.462     albertel 17408:     }
                   17409: }
                   17410: 
1.685     tempelho 17411: # --- Get the symbolic name of a problem and the url
                   17412: sub get_symb {
                   17413:     my ($request,$silent) = @_;
1.726     raeburn  17414:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17415:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17416:     if ($symb eq '') {
                   17417:         if (!$silent) {
1.1071    raeburn  17418:             if (ref($request)) { 
                   17419:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17420:             }
1.685     tempelho 17421:             return ();
                   17422:         }
                   17423:     }
                   17424:     &Apache::lonenc::check_decrypt(\$symb);
                   17425:     return ($symb);
                   17426: }
                   17427: 
                   17428: # --------------------------------------------------------------Get annotation
                   17429: 
                   17430: sub get_annotation {
                   17431:     my ($symb,$enc) = @_;
                   17432: 
                   17433:     my $key = $symb;
                   17434:     if (!$enc) {
                   17435:         $key =
                   17436:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17437:     }
                   17438:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17439:     return $annotation{$key};
                   17440: }
                   17441: 
                   17442: sub clean_symb {
1.731     raeburn  17443:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17444: 
                   17445:     &Apache::lonenc::check_decrypt(\$symb);
                   17446:     my $enc = $env{'request.enc'};
1.731     raeburn  17447:     if ($delete_enc) {
1.730     raeburn  17448:         delete($env{'request.enc'});
                   17449:     }
1.685     tempelho 17450: 
                   17451:     return ($symb,$enc);
                   17452: }
1.462     albertel 17453: 
1.1075.2.69  raeburn  17454: ############################################################
                   17455: ############################################################
                   17456: 
                   17457: =pod
                   17458: 
                   17459: =head1 Routines for building display used to search for courses
                   17460: 
                   17461: 
                   17462: =over 4
                   17463: 
                   17464: =item * &build_filters()
                   17465: 
                   17466: Create markup for a table used to set filters to use when selecting
                   17467: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17468: and quotacheck.pl
                   17469: 
                   17470: 
                   17471: Inputs:
                   17472: 
                   17473: filterlist - anonymous array of fields to include as potential filters
                   17474: 
                   17475: crstype - course type
                   17476: 
                   17477: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17478:               to pop-open a course selector (will contain "extra element").
                   17479: 
                   17480: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17481: 
                   17482: filter - anonymous hash of criteria and their values
                   17483: 
                   17484: action - form action
                   17485: 
                   17486: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17487: 
                   17488: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   17489: 
                   17490: cloneruname - username of owner of new course who wants to clone
                   17491: 
                   17492: clonerudom - domain of owner of new course who wants to clone
                   17493: 
                   17494: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   17495: 
                   17496: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17497: 
                   17498: codedom - domain
                   17499: 
                   17500: formname - value of form element named "form".
                   17501: 
                   17502: fixeddom - domain, if fixed.
                   17503: 
                   17504: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   17505: 
                   17506: cnameelement - name of form element in form on opener page which will receive title of selected course
                   17507: 
                   17508: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17509: 
                   17510: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17511: 
                   17512: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17513: 
                   17514: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17515: 
                   17516: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17517: 
                   17518: 
                   17519: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17520: 
                   17521: 
                   17522: Side Effects: None
                   17523: 
                   17524: =cut
                   17525: 
                   17526: # ---------------------------------------------- search for courses based on last activity etc.
                   17527: 
                   17528: sub build_filters {
                   17529:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17530:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17531:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17532:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17533:         $clonetext,$clonewarning) = @_;
                   17534:     my ($list,$jscript);
                   17535:     my $onchange = 'javascript:updateFilters(this)';
                   17536:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17537:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17538:         $typeselectform,$instcodetitle);
                   17539:     if ($formname eq '') {
                   17540:         $formname = $caller;
                   17541:     }
                   17542:     foreach my $item (@{$filterlist}) {
                   17543:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17544:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17545:             if ($item eq 'domainfilter') {
                   17546:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17547:             } elsif ($item eq 'coursefilter') {
                   17548:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17549:             } elsif ($item eq 'ownerfilter') {
                   17550:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17551:             } elsif ($item eq 'ownerdomfilter') {
                   17552:                 $filter->{'ownerdomfilter'} =
                   17553:                     &LONCAPA::clean_domain($filter->{$item});
                   17554:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17555:                                                        'ownerdomfilter',1);
                   17556:             } elsif ($item eq 'personfilter') {
                   17557:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17558:             } elsif ($item eq 'persondomfilter') {
                   17559:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17560:                                                         'persondomfilter',1);
                   17561:             } else {
                   17562:                 $filter->{$item} =~ s/\W//g;
                   17563:             }
                   17564:             if (!$filter->{$item}) {
                   17565:                 $filter->{$item} = '';
                   17566:             }
                   17567:         }
                   17568:         if ($item eq 'domainfilter') {
                   17569:             my $allow_blank = 1;
                   17570:             if ($formname eq 'portform') {
                   17571:                 $allow_blank=0;
                   17572:             } elsif ($formname eq 'studentform') {
                   17573:                 $allow_blank=0;
                   17574:             }
                   17575:             if ($fixeddom) {
                   17576:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17577:                                     ' value="'.$codedom.'" />'.
                   17578:                                     &Apache::lonnet::domain($codedom,'description');
                   17579:             } else {
                   17580:                 $domainselectform = &select_dom_form($filter->{$item},
                   17581:                                                      'domainfilter',
                   17582:                                                       $allow_blank,'',$onchange);
                   17583:             }
                   17584:         } else {
                   17585:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17586:         }
                   17587:     }
                   17588: 
                   17589:     # last course activity filter and selection
                   17590:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17591: 
                   17592:     # course created filter and selection
                   17593:     if (exists($filter->{'createdfilter'})) {
                   17594:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17595:     }
                   17596: 
                   17597:     my %lt = &Apache::lonlocal::texthash(
                   17598:                 'cac' => "$crstype Activity",
                   17599:                 'ccr' => "$crstype Created",
                   17600:                 'cde' => "$crstype Title",
                   17601:                 'cdo' => "$crstype Domain",
                   17602:                 'ins' => 'Institutional Code',
                   17603:                 'inc' => 'Institutional Categorization',
                   17604:                 'cow' => "$crstype Owner/Co-owner",
                   17605:                 'cop' => "$crstype Personnel Includes",
                   17606:                 'cog' => 'Type',
                   17607:              );
                   17608: 
                   17609:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17610:         my $typeval = 'Course';
                   17611:         if ($crstype eq 'Community') {
                   17612:             $typeval = 'Community';
                   17613:         }
                   17614:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17615:     } else {
                   17616:         $typeselectform =  '<select name="type" size="1"';
                   17617:         if ($onchange) {
                   17618:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17619:         }
                   17620:         $typeselectform .= '>'."\n";
                   17621:         foreach my $posstype ('Course','Community') {
                   17622:             $typeselectform.='<option value="'.$posstype.'"'.
                   17623:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17624:         }
                   17625:         $typeselectform.="</select>";
                   17626:     }
                   17627: 
                   17628:     my ($cloneableonlyform,$cloneabletitle);
                   17629:     if (exists($filter->{'cloneableonly'})) {
                   17630:         my $cloneableon = '';
                   17631:         my $cloneableoff = ' checked="checked"';
                   17632:         if ($filter->{'cloneableonly'}) {
                   17633:             $cloneableon = $cloneableoff;
                   17634:             $cloneableoff = '';
                   17635:         }
                   17636:         $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>';
                   17637:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17638:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17639:         } else {
                   17640:             $cloneabletitle = &mt('Cloneable by you');
                   17641:         }
                   17642:     }
                   17643:     my $officialjs;
                   17644:     if ($crstype eq 'Course') {
                   17645:         if (exists($filter->{'instcodefilter'})) {
                   17646: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17647: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17648:             if ($codedom) {
                   17649:                 $officialjs = 1;
                   17650:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17651:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17652:                                                                   $officialjs,$codetitlesref);
                   17653:                 if ($jscript) {
                   17654:                     $jscript = '<script type="text/javascript">'."\n".
                   17655:                                '// <![CDATA['."\n".
                   17656:                                $jscript."\n".
                   17657:                                '// ]]>'."\n".
                   17658:                                '</script>'."\n";
                   17659:                 }
                   17660:             }
                   17661:             if ($instcodeform eq '') {
                   17662:                 $instcodeform =
                   17663:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17664:                     $list->{'instcodefilter'}.'" />';
                   17665:                 $instcodetitle = $lt{'ins'};
                   17666:             } else {
                   17667:                 $instcodetitle = $lt{'inc'};
                   17668:             }
                   17669:             if ($fixeddom) {
                   17670:                 $instcodetitle .= '<br />('.$codedom.')';
                   17671:             }
                   17672:         }
                   17673:     }
                   17674:     my $output = qq|
                   17675: <form method="post" name="filterpicker" action="$action">
                   17676: <input type="hidden" name="form" value="$formname" />
                   17677: |;
                   17678:     if ($formname eq 'modifycourse') {
                   17679:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17680:                    '<input type="hidden" name="prevphase" value="'.
                   17681:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17682:     } elsif ($formname eq 'quotacheck') {
                   17683:         $output .= qq|
                   17684: <input type="hidden" name="sortby" value="" />
                   17685: <input type="hidden" name="sortorder" value="" />
                   17686: |;
                   17687:     } else {
1.1075.2.69  raeburn  17688:         my $name_input;
                   17689:         if ($cnameelement ne '') {
                   17690:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17691:                           $cnameelement.'" />';
                   17692:         }
                   17693:         $output .= qq|
                   17694: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17695: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17696: $name_input
                   17697: $roleelement
                   17698: $multelement
                   17699: $typeelement
                   17700: |;
                   17701:         if ($formname eq 'portform') {
                   17702:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17703:         }
                   17704:     }
                   17705:     if ($fixeddom) {
                   17706:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17707:     }
                   17708:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17709:     if ($sincefilterform) {
                   17710:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17711:                   .$sincefilterform
                   17712:                   .&Apache::lonhtmlcommon::row_closure();
                   17713:     }
                   17714:     if ($createdfilterform) {
                   17715:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17716:                   .$createdfilterform
                   17717:                   .&Apache::lonhtmlcommon::row_closure();
                   17718:     }
                   17719:     if ($domainselectform) {
                   17720:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17721:                   .$domainselectform
                   17722:                   .&Apache::lonhtmlcommon::row_closure();
                   17723:     }
                   17724:     if ($typeselectform) {
                   17725:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17726:             $output .= $typeselectform;
                   17727:         } else {
                   17728:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17729:                       .$typeselectform
                   17730:                       .&Apache::lonhtmlcommon::row_closure();
                   17731:         }
                   17732:     }
                   17733:     if ($instcodeform) {
                   17734:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17735:                   .$instcodeform
                   17736:                   .&Apache::lonhtmlcommon::row_closure();
                   17737:     }
                   17738:     if (exists($filter->{'ownerfilter'})) {
                   17739:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17740:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17741:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17742:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17743:                    $ownerdomselectform.'</td></tr></table>'.
                   17744:                    &Apache::lonhtmlcommon::row_closure();
                   17745:     }
                   17746:     if (exists($filter->{'personfilter'})) {
                   17747:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17748:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17749:                    '<input type="text" name="personfilter" size="20" value="'.
                   17750:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17751:                    $persondomselectform.'</td></tr></table>'.
                   17752:                    &Apache::lonhtmlcommon::row_closure();
                   17753:     }
                   17754:     if (exists($filter->{'coursefilter'})) {
                   17755:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17756:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17757:                   .$list->{'coursefilter'}.'" />'
                   17758:                   .&Apache::lonhtmlcommon::row_closure();
                   17759:     }
                   17760:     if ($cloneableonlyform) {
                   17761:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17762:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17763:     }
                   17764:     if (exists($filter->{'descriptfilter'})) {
                   17765:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17766:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17767:                   .$list->{'descriptfilter'}.'" />'
                   17768:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17769:     }
                   17770:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17771:                '<input type="hidden" name="updater" value="" />'."\n".
                   17772:                '<input type="submit" name="gosearch" value="'.
                   17773:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17774:     return $jscript.$clonewarning.$output;
                   17775: }
                   17776: 
                   17777: =pod
                   17778: 
                   17779: =item * &timebased_select_form()
                   17780: 
                   17781: Create markup for a dropdown list used to select a time-based
                   17782: filter e.g., Course Activity, Course Created, when searching for courses
                   17783: or communities
                   17784: 
                   17785: Inputs:
                   17786: 
                   17787: item - name of form element (sincefilter or createdfilter)
                   17788: 
                   17789: filter - anonymous hash of criteria and their values
                   17790: 
                   17791: Returns: HTML for a select box contained a blank, then six time selections,
                   17792:          with value set in incoming form variables currently selected.
                   17793: 
                   17794: Side Effects: None
                   17795: 
                   17796: =cut
                   17797: 
                   17798: sub timebased_select_form {
                   17799:     my ($item,$filter) = @_;
                   17800:     if (ref($filter) eq 'HASH') {
                   17801:         $filter->{$item} =~ s/[^\d-]//g;
                   17802:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17803:         return &select_form(
                   17804:                             $filter->{$item},
                   17805:                             $item,
                   17806:                             {      '-1' => '',
                   17807:                                 '86400' => &mt('today'),
                   17808:                                '604800' => &mt('last week'),
                   17809:                               '2592000' => &mt('last month'),
                   17810:                               '7776000' => &mt('last three months'),
                   17811:                              '15552000' => &mt('last six months'),
                   17812:                              '31104000' => &mt('last year'),
                   17813:                     'select_form_order' =>
                   17814:                            ['-1','86400','604800','2592000','7776000',
                   17815:                             '15552000','31104000']});
                   17816:     }
                   17817: }
                   17818: 
                   17819: =pod
                   17820: 
                   17821: =item * &js_changer()
                   17822: 
                   17823: Create script tag containing Javascript used to submit course search form
                   17824: when course type or domain is changed, and also to hide 'Searching ...' on
                   17825: page load completion for page showing search result.
                   17826: 
                   17827: Inputs: None
                   17828: 
                   17829: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17830: 
                   17831: Side Effects: None
                   17832: 
                   17833: =cut
                   17834: 
                   17835: sub js_changer {
                   17836:     return <<ENDJS;
                   17837: <script type="text/javascript">
                   17838: // <![CDATA[
                   17839: function updateFilters(caller) {
                   17840:     if (typeof(caller) != "undefined") {
                   17841:         document.filterpicker.updater.value = caller.name;
                   17842:     }
                   17843:     document.filterpicker.submit();
                   17844: }
                   17845: 
                   17846: function hideSearching() {
                   17847:     if (document.getElementById('searching')) {
                   17848:         document.getElementById('searching').style.display = 'none';
                   17849:     }
                   17850:     return;
                   17851: }
                   17852: 
                   17853: // ]]>
                   17854: </script>
                   17855: 
                   17856: ENDJS
                   17857: }
                   17858: 
                   17859: =pod
                   17860: 
                   17861: =item * &search_courses()
                   17862: 
                   17863: Process selected filters form course search form and pass to lonnet::courseiddump
                   17864: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17865: 
                   17866: Inputs:
                   17867: 
                   17868: dom - domain being searched
                   17869: 
                   17870: type - course type ('Course' or 'Community' or '.' if any).
                   17871: 
                   17872: filter - anonymous hash of criteria and their values
                   17873: 
                   17874: numtitles - for institutional codes - number of categories
                   17875: 
                   17876: cloneruname - optional username of new course owner
                   17877: 
                   17878: clonerudom - optional domain of new course owner
                   17879: 
1.1075.2.95  raeburn  17880: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17881:             (used when DC is using course creation form)
                   17882: 
                   17883: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17884: 
1.1075.2.95  raeburn  17885: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17886:            (and so can clone automatically)
                   17887: 
                   17888: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17889: 
                   17890: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17891:               courses to clone
1.1075.2.69  raeburn  17892: 
                   17893: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17894: 
                   17895: 
                   17896: Side Effects: None
                   17897: 
                   17898: =cut
                   17899: 
                   17900: 
                   17901: sub search_courses {
1.1075.2.95  raeburn  17902:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17903:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17904:     my (%courses,%showcourses,$cloner);
                   17905:     if (($filter->{'ownerfilter'} ne '') ||
                   17906:         ($filter->{'ownerdomfilter'} ne '')) {
                   17907:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17908:                                        $filter->{'ownerdomfilter'};
                   17909:     }
                   17910:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17911:         if (!$filter->{$item}) {
                   17912:             $filter->{$item}='.';
                   17913:         }
                   17914:     }
                   17915:     my $now = time;
                   17916:     my $timefilter =
                   17917:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17918:     my ($createdbefore,$createdafter);
                   17919:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17920:         $createdbefore = $now;
                   17921:         $createdafter = $now-$filter->{'createdfilter'};
                   17922:     }
                   17923:     my ($instcodefilter,$regexpok);
                   17924:     if ($numtitles) {
                   17925:         if ($env{'form.official'} eq 'on') {
                   17926:             $instcodefilter =
                   17927:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17928:             $regexpok = 1;
                   17929:         } elsif ($env{'form.official'} eq 'off') {
                   17930:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17931:             unless ($instcodefilter eq '') {
                   17932:                 $regexpok = -1;
                   17933:             }
                   17934:         }
                   17935:     } else {
                   17936:         $instcodefilter = $filter->{'instcodefilter'};
                   17937:     }
                   17938:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17939:     if ($type eq '') { $type = '.'; }
                   17940: 
                   17941:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17942:         $cloner = $cloneruname.':'.$clonerudom;
                   17943:     }
                   17944:     %courses = &Apache::lonnet::courseiddump($dom,
                   17945:                                              $filter->{'descriptfilter'},
                   17946:                                              $timefilter,
                   17947:                                              $instcodefilter,
                   17948:                                              $filter->{'combownerfilter'},
                   17949:                                              $filter->{'coursefilter'},
                   17950:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17951:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17952:                                              $filter->{'cloneableonly'},
                   17953:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17954:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17955:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17956:         my $ccrole;
                   17957:         if ($type eq 'Community') {
                   17958:             $ccrole = 'co';
                   17959:         } else {
                   17960:             $ccrole = 'cc';
                   17961:         }
                   17962:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17963:                                                      $filter->{'persondomfilter'},
                   17964:                                                      'userroles',undef,
                   17965:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17966:                                                      $dom);
                   17967:         foreach my $role (keys(%rolehash)) {
                   17968:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17969:             my $cid = $cdom.'_'.$cnum;
                   17970:             if (exists($courses{$cid})) {
                   17971:                 if (ref($courses{$cid}) eq 'HASH') {
                   17972:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17973:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17974:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17975:                         }
                   17976:                     } else {
                   17977:                         $courses{$cid}{roles} = [$courserole];
                   17978:                     }
                   17979:                     $showcourses{$cid} = $courses{$cid};
                   17980:                 }
                   17981:             }
                   17982:         }
                   17983:         %courses = %showcourses;
                   17984:     }
                   17985:     return %courses;
                   17986: }
                   17987: 
                   17988: =pod
                   17989: 
                   17990: =back
                   17991: 
1.1075.2.88  raeburn  17992: =head1 Routines for version requirements for current course.
                   17993: 
                   17994: =over 4
                   17995: 
                   17996: =item * &check_release_required()
                   17997: 
                   17998: Compares required LON-CAPA version with version on server, and
                   17999: if required version is newer looks for a server with the required version.
                   18000: 
                   18001: Looks first at servers in user's owen domain; if none suitable, looks at
                   18002: servers in course's domain are permitted to host sessions for user's domain.
                   18003: 
                   18004: Inputs:
                   18005: 
                   18006: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18007: 
                   18008: $courseid - Course ID of current course
                   18009: 
                   18010: $rolecode - User's current role in course (for switchserver query string).
                   18011: 
                   18012: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18013: 
                   18014: 
                   18015: Returns:
                   18016: 
                   18017: $switchserver - query string tp append to /adm/switchserver call (if
                   18018:                 current server's LON-CAPA version is too old.
                   18019: 
                   18020: $warning - Message is displayed if no suitable server could be found.
                   18021: 
                   18022: =cut
                   18023: 
                   18024: sub check_release_required {
                   18025:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18026:     my ($switchserver,$warning);
                   18027:     if ($required ne '') {
                   18028:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18029:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18030:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18031:             my $otherserver;
                   18032:             if (($major eq '' && $minor eq '') ||
                   18033:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18034:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18035:                 my $switchlcrev =
                   18036:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18037:                                                            $userdomserver);
                   18038:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18039:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18040:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18041:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18042:                     if ($cdom ne $env{'user.domain'}) {
                   18043:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18044:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18045:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18046:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18047:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18048:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18049:                         my $canhost =
                   18050:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18051:                                                               $coursedomserver,
                   18052:                                                               $remoterev,
                   18053:                                                               $udomdefaults{'remotesessions'},
                   18054:                                                               $defdomdefaults{'hostedsessions'});
                   18055: 
                   18056:                         if ($canhost) {
                   18057:                             $otherserver = $coursedomserver;
                   18058:                         } else {
                   18059:                             $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.");
                   18060:                         }
                   18061:                     } else {
                   18062:                         $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).");
                   18063:                     }
                   18064:                 } else {
                   18065:                     $otherserver = $userdomserver;
                   18066:                 }
                   18067:             }
                   18068:             if ($otherserver ne '') {
                   18069:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18070:             }
                   18071:         }
                   18072:     }
                   18073:     return ($switchserver,$warning);
                   18074: }
                   18075: 
                   18076: =pod
                   18077: 
                   18078: =item * &check_release_result()
                   18079: 
                   18080: Inputs:
                   18081: 
                   18082: $switchwarning - Warning message if no suitable server found to host session.
                   18083: 
                   18084: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18085:                 and current role.
                   18086: 
                   18087: Returns: HTML to display with information about requirement to switch server.
                   18088:          Either displaying warning with link to Roles/Courses screen or
                   18089:          display link to switchserver.
                   18090: 
1.1075.2.69  raeburn  18091: =cut
                   18092: 
1.1075.2.88  raeburn  18093: sub check_release_result {
                   18094:     my ($switchwarning,$switchserver) = @_;
                   18095:     my $output = &start_page('Selected course unavailable on this server').
                   18096:                  '<p class="LC_warning">';
                   18097:     if ($switchwarning) {
                   18098:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18099:         if (&show_course()) {
                   18100:             $output .= &mt('Display courses');
                   18101:         } else {
                   18102:             $output .= &mt('Display roles');
                   18103:         }
                   18104:         $output .= '</a>';
                   18105:     } elsif ($switchserver) {
                   18106:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18107:                    '<br />'.
                   18108:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18109:                    &mt('Switch Server').
                   18110:                    '</a>';
                   18111:     }
                   18112:     $output .= '</p>'.&end_page();
                   18113:     return $output;
                   18114: }
                   18115: 
                   18116: =pod
                   18117: 
                   18118: =item * &needs_coursereinit()
                   18119: 
                   18120: Determine if course contents stored for user's session needs to be
                   18121: refreshed, because content has changed since "Big Hash" last tied.
                   18122: 
                   18123: Check for change is made if time last checked is more than 10 minutes ago
                   18124: (by default).
                   18125: 
                   18126: Inputs:
                   18127: 
                   18128: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18129: 
                   18130: $interval (optional) - Time which may elapse (in s) between last check for content
                   18131:                        change in current course. (default: 600 s).
                   18132: 
                   18133: Returns: an array; first element is:
                   18134: 
                   18135: =over 4
                   18136: 
                   18137: 'switch' - if content updates mean user's session
                   18138:            needs to be switched to a server running a newer LON-CAPA version
                   18139: 
                   18140: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18141:            on current server hosting user's session
                   18142: 
                   18143: ''       - if no action required.
                   18144: 
                   18145: =back
                   18146: 
                   18147: If first item element is 'switch':
                   18148: 
                   18149: second item is $switchwarning - Warning message if no suitable server found to host session.
                   18150: 
                   18151: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18152:                               and current role.
                   18153: 
                   18154: otherwise: no other elements returned.
                   18155: 
                   18156: =back
                   18157: 
                   18158: =cut
                   18159: 
                   18160: sub needs_coursereinit {
                   18161:     my ($loncaparev,$interval) = @_;
                   18162:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18163:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18164:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18165:     my $now = time;
                   18166:     if ($interval eq '') {
                   18167:         $interval = 600;
                   18168:     }
                   18169:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   18170:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 18171:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 18172:21):         if ($blocked) {
                   18173:21):             return ();
                   18174:21):         }
          .13(raeb 18175:-23):         my $update;
                   18176:-23):         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18177:-23):         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18178:-23):         if ($lastmainchange > $env{'request.course.tied'}) {
                   18179:-23):             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18180:-23):             if ($needswitch) {
                   18181:-23):                 return ('switch',$switchwarning,$switchserver);
                   18182:-23):             }
                   18183:-23):             $update = 'main';
                   18184:-23):         }
                   18185:-23):         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18186:-23):             if ($update) {
                   18187:-23):                 $update = 'both';
                   18188:-23):             } else {
                   18189:-23):                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18190:-23):                 if ($needswitch) {
                   18191:-23):                     return ('switch',$switchwarning,$switchserver);
                   18192:-23):                 } else {
                   18193:-23):                     $update = 'supp';
1.1075.2.88  raeburn  18194:                 }
                   18195:             }
1.1075.2.161.  .13(raeb 18196:-23):             return ($update);
                   18197:-23):         }
                   18198:-23):     }
                   18199:-23):     return ();
                   18200:-23): }
                   18201:-23): 
                   18202:-23): sub switch_for_update {
                   18203:-23):     my ($loncaparev,$cdom,$cnum) = @_;
                   18204:-23):     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18205:-23):     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18206:-23):         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18207:-23):         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18208:-23):             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18209:-23):                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18210:-23):             my ($switchserver,$switchwarning) =
                   18211:-23):                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18212:-23):                                         $curr_reqd_hash{'internal.releaserequired'});
                   18213:-23):             if ($switchwarning ne '' || $switchserver ne '') {
                   18214:-23):                 return ('switch',$switchwarning,$switchserver);
                   18215:-23):             }
1.1075.2.88  raeburn  18216:         }
                   18217:     }
                   18218:     return ();
                   18219: }
1.1075.2.69  raeburn  18220: 
1.1075.2.11  raeburn  18221: sub update_content_constraints {
                   18222:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18223:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18224:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   18225:     my %checkresponsetypes;
                   18226:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   18227:         my ($item,$name,$value) = split(/:/,$key);
                   18228:         if ($item eq 'resourcetag') {
                   18229:             if ($name eq 'responsetype') {
                   18230:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18231:             }
                   18232:         }
                   18233:     }
                   18234:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18235:     if (defined($navmap)) {
                   18236:         my %allresponses;
                   18237:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   18238:             my %responses = $res->responseTypes();
                   18239:             foreach my $key (keys(%responses)) {
                   18240:                 next unless(exists($checkresponsetypes{$key}));
                   18241:                 $allresponses{$key} += $responses{$key};
                   18242:             }
                   18243:         }
                   18244:         foreach my $key (keys(%allresponses)) {
                   18245:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18246:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18247:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18248:             }
                   18249:         }
                   18250:         undef($navmap);
                   18251:     }
                   18252:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18253:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18254:     }
                   18255:     return;
                   18256: }
                   18257: 
1.1075.2.27  raeburn  18258: sub allmaps_incourse {
                   18259:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18260:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18261:         $cid = $env{'request.course.id'};
                   18262:         $cdom = $env{'course.'.$cid.'.domain'};
                   18263:         $cnum = $env{'course.'.$cid.'.num'};
                   18264:         $chome = $env{'course.'.$cid.'.home'};
                   18265:     }
                   18266:     my %allmaps = ();
                   18267:     my $lastchange =
                   18268:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18269:     if ($lastchange > $env{'request.course.tied'}) {
                   18270:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18271:         unless ($ferr) {
                   18272:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   18273:         }
                   18274:     }
                   18275:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18276:     if (defined($navmap)) {
                   18277:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18278:             $allmaps{$res->src()} = 1;
                   18279:         }
                   18280:     }
                   18281:     return \%allmaps;
                   18282: }
                   18283: 
1.1075.2.11  raeburn  18284: sub parse_supplemental_title {
                   18285:     my ($title) = @_;
                   18286: 
                   18287:     my ($foldertitle,$renametitle);
                   18288:     if ($title =~ /&amp;&amp;&amp;/) {
                   18289:         $title = &HTML::Entites::decode($title);
                   18290:     }
                   18291:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18292:         $renametitle=$4;
                   18293:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18294:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18295:         my $name =  &plainname($uname,$udom);
                   18296:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18297:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1075.2.161.  .16(raeb 18298:-23):         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
                   18299:-23):         if ($foldertitle ne '') {
                   18300:-23):             $title .= ': <br />'.$foldertitle;
                   18301:-23):         }
1.1075.2.11  raeburn  18302:     }
                   18303:     if (wantarray) {
                   18304:         return ($title,$foldertitle,$renametitle);
                   18305:     }
                   18306:     return $title;
                   18307: }
                   18308: 
1.1075.2.161.  .13(raeb 18309:-23): sub get_supplemental {
                   18310:-23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18311:-23):     my $hashid=$cnum.':'.$cdom;
                   18312:-23):     my ($supplemental,$cached,$set_httprefs);
                   18313:-23):     unless ($ignorecache) {
                   18314:-23):         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18315:-23):     }
                   18316:-23):     unless (defined($cached)) {
                   18317:-23):         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18318:-23):         unless ($chome eq 'no_host') {
                   18319:-23):             my @order = @LONCAPA::map::order;
                   18320:-23):             my @resources = @LONCAPA::map::resources;
                   18321:-23):             my @resparms = @LONCAPA::map::resparms;
                   18322:-23):             my @zombies = @LONCAPA::map::zombies;
                   18323:-23):             my ($errors,%ids,%hidden);
                   18324:-23):             $errors =
                   18325:-23):                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   18326:-23):                                       $errors,$possdel,\%ids,\%hidden);
                   18327:-23):             @LONCAPA::map::order = @order;
                   18328:-23):             @LONCAPA::map::resources = @resources;
                   18329:-23):             @LONCAPA::map::resparms = @resparms;
                   18330:-23):             @LONCAPA::map::zombies = @zombies;
                   18331:-23):             $set_httprefs = 1;
                   18332:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18333:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18334:-23):             }
                   18335:-23):             $supplemental = {
                   18336:-23):                                ids => \%ids,
                   18337:-23):                                hidden => \%hidden,
                   18338:-23):                             };
                   18339:-23):             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   18340:-23):         }
                   18341:-23):     }
                   18342:-23):     return ($supplemental,$set_httprefs);
                   18343:-23): }
                   18344:-23): 
1.1075.2.43  raeburn  18345: sub recurse_supplemental {
1.1075.2.161.  .13(raeb 18346:-23):     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18347:-23):     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18348:-23):         my $mapnum;
                   18349:-23):         if ($suppmap eq 'supplemental.sequence') {
                   18350:-23):             $mapnum = 0;
                   18351:-23):         } else {
                   18352:-23):             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18353:-23):         }
1.1075.2.43  raeburn  18354:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18355:         if ($fatal) {
                   18356:             $errors ++;
                   18357:         } else {
1.1075.2.161.  .13(raeb 18358:-23):             my @order = @LONCAPA::map::order;
                   18359:-23):             if (@order > 0) {
                   18360:-23):                 my @resources = @LONCAPA::map::resources;
                   18361:-23):                 my @resparms = @LONCAPA::map::resparms;
                   18362:-23):                 foreach my $idx (@order) {
                   18363:-23):                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1075.2.43  raeburn  18364:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.161.  .13(raeb 18365:-23):                         my $id = $mapnum.':'.$idx;
                   18366:-23):                         push(@{$suppids->{$src}},$id);
                   18367:-23):                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18368:-23):                             $hiddensupp->{$id} = 1;
                   18369:-23):                         }
1.1075.2.46  raeburn  18370:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1075.2.161.  .13(raeb 18371:-23):                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18372:-23):                                                             $hiddensupp,$hiddensupp->{$id});
1.1075.2.43  raeburn  18373:                         } else {
1.1075.2.161.  .13(raeb 18374:-23):                             my $allowed;
                   18375:-23):                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18376:-23):                                 $allowed = 1;
                   18377:-23):                             } elsif ($possdel) {
                   18378:-23):                                 foreach my $item (@{$suppids->{$src}}) {
                   18379:-23):                                     next if ($item eq $id);
                   18380:-23):                                     unless ($hiddensupp->{$item}) {
                   18381:-23):                                        $allowed = 1;
                   18382:-23):                                        last;
                   18383:-23):                                     }
                   18384:-23):                                 }
                   18385:-23):                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18386:-23):                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18387:-23):                                 }
                   18388:-23):                             }
                   18389:-23):                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18390:-23):                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18391:-23):                             }
                   18392:-23):                         }
                   18393:-23):                     }
                   18394:-23):                 }
                   18395:-23):             }
                   18396:-23):         }
                   18397:-23):     }
                   18398:-23):     return $errors;
                   18399:-23): }
                   18400:-23): 
                   18401:-23): sub set_supp_httprefs {
                   18402:-23):     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18403:-23):     if (ref($supplemental) eq 'HASH') {
                   18404:-23):         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18405:-23):             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18406:-23):                 next if ($src =~ /\.sequence$/);
                   18407:-23):                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18408:-23):                     my $allowed;
                   18409:-23):                     if ($env{'request.role.adv'}) {
                   18410:-23):                         $allowed = 1;
                   18411:-23):                     } else {
                   18412:-23):                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18413:-23):                             unless ($supplemental->{'hidden'}->{$id}) {
                   18414:-23):                                 $allowed = 1;
                   18415:-23):                                 last;
                   18416:-23):                             }
                   18417:-23):                         }
                   18418:-23):                     }
                   18419:-23):                     if (exists($env{'httpref.'.$src})) {
                   18420:-23):                         if ($possdel) {
                   18421:-23):                             unless ($allowed) {
                   18422:-23):                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18423:-23):                             }
1.1075.2.43  raeburn  18424:                         }
1.1075.2.161.  .13(raeb 18425:-23):                     } elsif ($allowed) {
                   18426:-23):                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1075.2.43  raeburn  18427:                     }
                   18428:                 }
                   18429:             }
1.1075.2.161.  .13(raeb 18430:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18431:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18432:-23):             }
1.1075.2.43  raeburn  18433:         }
                   18434:     }
1.1075.2.161.  .13(raeb 18435:-23): }
                   18436:-23): 
                   18437:-23): sub get_supp_parameter {
                   18438:-23):     my ($resparm,$name)=@_;
                   18439:-23):     return if ($resparm eq '');
                   18440:-23):     my $value=undef;
                   18441:-23):     my $ptype=undef;
                   18442:-23):     foreach (split('&&&',$resparm)) {
                   18443:-23):         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18444:-23):         if ($thisname eq $name) {
                   18445:-23):             $value=$thisvalue;
                   18446:-23):             $ptype=$thistype;
                   18447:-23):         }
                   18448:-23):     }
                   18449:-23):     return $value;
1.1075.2.43  raeburn  18450: }
                   18451: 
1.1075.2.18  raeburn  18452: sub symb_to_docspath {
1.1075.2.119  raeburn  18453:     my ($symb,$navmapref) = @_;
                   18454:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  18455:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18456:     if ($resurl=~/\.(sequence|page)$/) {
                   18457:         $mapurl=$resurl;
                   18458:     } elsif ($resurl eq 'adm/navmaps') {
                   18459:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18460:     }
                   18461:     my $mapresobj;
1.1075.2.119  raeburn  18462:     unless (ref($$navmapref)) {
                   18463:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18464:     }
                   18465:     if (ref($$navmapref)) {
                   18466:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  18467:     }
                   18468:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18469:     my $type=$2;
                   18470:     my $path;
                   18471:     if (ref($mapresobj)) {
                   18472:         my $pcslist = $mapresobj->map_hierarchy();
                   18473:         if ($pcslist ne '') {
                   18474:             foreach my $pc (split(/,/,$pcslist)) {
                   18475:                 next if ($pc <= 1);
1.1075.2.119  raeburn  18476:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  18477:                 if (ref($res)) {
                   18478:                     my $thisurl = $res->src();
                   18479:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18480:                     my $thistitle = $res->title();
                   18481:                     $path .= '&'.
                   18482:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  18483:                              &escape($thistitle).
1.1075.2.18  raeburn  18484:                              ':'.$res->randompick().
                   18485:                              ':'.$res->randomout().
                   18486:                              ':'.$res->encrypted().
                   18487:                              ':'.$res->randomorder().
                   18488:                              ':'.$res->is_page();
                   18489:                 }
                   18490:             }
                   18491:         }
                   18492:         $path =~ s/^\&//;
                   18493:         my $maptitle = $mapresobj->title();
                   18494:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18495:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18496:         }
                   18497:         $path .= (($path ne '')? '&' : '').
                   18498:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18499:                  &escape($maptitle).
1.1075.2.18  raeburn  18500:                  ':'.$mapresobj->randompick().
                   18501:                  ':'.$mapresobj->randomout().
                   18502:                  ':'.$mapresobj->encrypted().
                   18503:                  ':'.$mapresobj->randomorder().
                   18504:                  ':'.$mapresobj->is_page();
                   18505:     } else {
                   18506:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18507:         my $ispage = (($type eq 'page')? 1 : '');
                   18508:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18509:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18510:         }
                   18511:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18512:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  18513:     }
                   18514:     unless ($mapurl eq 'default') {
                   18515:         $path = 'default&'.
1.1075.2.46  raeburn  18516:                 &escape('Main Content').
1.1075.2.18  raeburn  18517:                 ':::::&'.$path;
                   18518:     }
                   18519:     return $path;
                   18520: }
                   18521: 
1.1075.2.161.  .13(raeb 18522:-23): sub validate_folderpath {
                   18523:-23):     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18524:-23):     if ($env{'form.folderpath'} ne '') {
                   18525:-23):         my @items = split(/\&/,$env{'form.folderpath'});
                   18526:-23):         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
                   18527:-23):         for (my $i=0; $i<@items; $i++) {
                   18528:-23):             my $odd = $i%2;
                   18529:-23):             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18530:-23):                 $badpath = 1;
                   18531:-23):             } elsif ($odd && $supplementalflag) {
                   18532:-23):                 my $idx = $i-1;
                   18533:-23):                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18534:-23):                     my $esc_name = $1;
                   18535:-23):                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18536:-23):                         $supppath .= '&'.$esc_name;
                   18537:-23):                         $changed = 1;
                   18538:-23):                     } else {
                   18539:-23):                         $supppath .= '&'.$items[$i];
                   18540:-23):                     }
                   18541:-23):                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18542:-23):                     $changed = 1;
                   18543:-23):                     my $is_hidden;
                   18544:-23):                     unless ($got_supp) {
                   18545:-23):                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
                   18546:-23):                         if (ref($supplemental) eq 'HASH') {
                   18547:-23):                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18548:-23):                                 %supphidden = %{$supplemental->{'hidden'}};
                   18549:-23):                             }
                   18550:-23):                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18551:-23):                                 %suppids = %{$supplemental->{'ids'}};
                   18552:-23):                             }
                   18553:-23):                         }
                   18554:-23):                         $got_supp = 1;
                   18555:-23):                     }
                   18556:-23):                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18557:-23):                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18558:-23):                         if ($supphidden{$mapid}) {
                   18559:-23):                             $is_hidden = 1;
                   18560:-23):                         }
                   18561:-23):                     }
                   18562:-23):                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18563:-23):                 } else {
                   18564:-23):                     $supppath .= '&'.$items[$i];
                   18565:-23):                 }
                   18566:-23):             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18567:-23):                 $badpath = 1;
                   18568:-23):             } elsif ($supplementalflag) {
                   18569:-23):                 $supppath .= '&'.$items[$i];
                   18570:-23):             }
                   18571:-23):             last if ($badpath);
                   18572:-23):         }
                   18573:-23):         if ($badpath) {
                   18574:-23):             delete($env{'form.folderpath'});
                   18575:-23):         } elsif ($changed && $supplementalflag) {
                   18576:-23):             $supppath =~ s/^\&//;
                   18577:-23):             $env{'form.folderpath'} = $supppath;
                   18578:-23):         }
                   18579:-23):     }
                   18580:-23):     return;
                   18581:-23): }
                   18582:-23): 
1.1075.2.14  raeburn  18583: sub captcha_display {
1.1075.2.137  raeburn  18584:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18585:     my ($output,$error);
1.1075.2.107  raeburn  18586:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  18587:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18588:     if ($captcha eq 'original') {
                   18589:         $output = &create_captcha();
                   18590:         unless ($output) {
                   18591:             $error = 'captcha';
                   18592:         }
                   18593:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18594:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  18595:         unless ($output) {
                   18596:             $error = 'recaptcha';
                   18597:         }
                   18598:     }
1.1075.2.107  raeburn  18599:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  18600: }
                   18601: 
                   18602: sub captcha_response {
1.1075.2.137  raeburn  18603:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18604:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  18605:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18606:     if ($captcha eq 'original') {
                   18607:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18608:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18609:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  18610:     } else {
                   18611:         $captcha_chk = 1;
                   18612:     }
                   18613:     return ($captcha_chk,$captcha_error);
                   18614: }
                   18615: 
                   18616: sub get_captcha_config {
1.1075.2.137  raeburn  18617:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  18618:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  18619:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18620:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18621:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18622:     if ($context eq 'usercreation') {
                   18623:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18624:         if (ref($domconfig{$context}) eq 'HASH') {
                   18625:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18626:             if (ref($hashtocheck) eq 'HASH') {
                   18627:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18628:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18629:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18630:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18631:                     }
                   18632:                     if ($privkey && $pubkey) {
                   18633:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  18634:                         $version = $hashtocheck->{'recaptchaversion'};
                   18635:                         if ($version ne '2') {
                   18636:                             $version = 1;
                   18637:                         }
1.1075.2.14  raeburn  18638:                     } else {
                   18639:                         $captcha = 'original';
                   18640:                     }
                   18641:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18642:                     $captcha = 'original';
                   18643:                 }
                   18644:             }
                   18645:         } else {
                   18646:             $captcha = 'captcha';
                   18647:         }
                   18648:     } elsif ($context eq 'login') {
                   18649:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18650:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18651:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18652:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   18653:             if ($privkey && $pubkey) {
                   18654:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  18655:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18656:                 if ($version ne '2') {
                   18657:                     $version = 1;
                   18658:                 }
1.1075.2.14  raeburn  18659:             } else {
                   18660:                 $captcha = 'original';
                   18661:             }
                   18662:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18663:             $captcha = 'original';
                   18664:         }
1.1075.2.137  raeburn  18665:     } elsif ($context eq 'passwords') {
                   18666:         if ($dom_in_effect) {
                   18667:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18668:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18669:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18670:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18671:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18672:                 }
                   18673:                 if ($privkey && $pubkey) {
                   18674:                     $captcha = 'recaptcha';
                   18675:                     $version = $passwdconf{'recaptchaversion'};
                   18676:                     if ($version ne '2') {
                   18677:                         $version = 1;
                   18678:                     }
                   18679:                 } else {
                   18680:                     $captcha = 'original';
                   18681:                 }
                   18682:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18683:                 $captcha = 'original';
                   18684:             }
                   18685:         }
1.1075.2.14  raeburn  18686:     }
1.1075.2.107  raeburn  18687:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  18688: }
                   18689: 
                   18690: sub create_captcha {
                   18691:     my %captcha_params = &captcha_settings();
                   18692:     my ($output,$maxtries,$tries) = ('',10,0);
                   18693:     while ($tries < $maxtries) {
                   18694:         $tries ++;
                   18695:         my $captcha = Authen::Captcha->new (
                   18696:                                            output_folder => $captcha_params{'output_dir'},
                   18697:                                            data_folder   => $captcha_params{'db_dir'},
                   18698:                                           );
                   18699:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18700: 
                   18701:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18702:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  18703:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  18704:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.161.  .15(raeb 18705:-23):                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1075.2.158  raeburn  18706:                       '</span><br />'.
1.1075.2.66  raeburn  18707:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  18708:             last;
                   18709:         }
                   18710:     }
1.1075.2.158  raeburn  18711:     if ($output eq '') {
                   18712:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18713:     }
1.1075.2.14  raeburn  18714:     return $output;
                   18715: }
                   18716: 
                   18717: sub captcha_settings {
                   18718:     my %captcha_params = (
                   18719:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18720:                            www_output_dir => "/captchaspool",
                   18721:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18722:                            numchars       => '5',
                   18723:                          );
                   18724:     return %captcha_params;
                   18725: }
                   18726: 
                   18727: sub check_captcha {
                   18728:     my ($captcha_chk,$captcha_error);
                   18729:     my $code = $env{'form.code'};
                   18730:     my $md5sum = $env{'form.crypt'};
                   18731:     my %captcha_params = &captcha_settings();
                   18732:     my $captcha = Authen::Captcha->new(
                   18733:                       output_folder => $captcha_params{'output_dir'},
                   18734:                       data_folder   => $captcha_params{'db_dir'},
                   18735:                   );
1.1075.2.26  raeburn  18736:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  18737:     my %captcha_hash = (
                   18738:                         0       => 'Code not checked (file error)',
                   18739:                        -1      => 'Failed: code expired',
                   18740:                        -2      => 'Failed: invalid code (not in database)',
                   18741:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18742:     );
                   18743:     if ($captcha_chk != 1) {
                   18744:         $captcha_error = $captcha_hash{$captcha_chk}
                   18745:     }
                   18746:     return ($captcha_chk,$captcha_error);
                   18747: }
                   18748: 
                   18749: sub create_recaptcha {
1.1075.2.107  raeburn  18750:     my ($pubkey,$version) = @_;
                   18751:     if ($version >= 2) {
1.1075.2.158  raeburn  18752:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18753:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  18754:     } else {
                   18755:         my $use_ssl;
                   18756:         if ($ENV{'SERVER_PORT'} == 443) {
                   18757:             $use_ssl = 1;
                   18758:         }
                   18759:         my $captcha = Captcha::reCAPTCHA->new;
                   18760:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18761:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18762:                &mt('If the text is hard to read, [_1] will replace them.',
                   18763:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18764:                '<br /><br />';
                   18765:      }
1.1075.2.14  raeburn  18766: }
                   18767: 
                   18768: sub check_recaptcha {
1.1075.2.107  raeburn  18769:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  18770:     my $captcha_chk;
1.1075.2.150  raeburn  18771:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  18772:     if ($version >= 2) {
                   18773:         my $ua = LWP::UserAgent->new;
                   18774:         $ua->timeout(10);
                   18775:         my %info = (
                   18776:                      secret   => $privkey,
                   18777:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  18778:                      remoteip => $ip,
1.1075.2.107  raeburn  18779:                    );
                   18780:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   18781:         if ($response->is_success)  {
                   18782:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18783:             if (ref($data) eq 'HASH') {
                   18784:                 if ($data->{'success'}) {
                   18785:                     $captcha_chk = 1;
                   18786:                 }
                   18787:             }
                   18788:         }
                   18789:     } else {
                   18790:         my $captcha = Captcha::reCAPTCHA->new;
                   18791:         my $captcha_result =
                   18792:             $captcha->check_answer(
                   18793:                                     $privkey,
1.1075.2.150  raeburn  18794:                                     $ip,
1.1075.2.107  raeburn  18795:                                     $env{'form.recaptcha_challenge_field'},
                   18796:                                     $env{'form.recaptcha_response_field'},
                   18797:                                   );
                   18798:         if ($captcha_result->{is_valid}) {
                   18799:             $captcha_chk = 1;
                   18800:         }
1.1075.2.14  raeburn  18801:     }
                   18802:     return $captcha_chk;
                   18803: }
                   18804: 
1.1075.2.64  raeburn  18805: sub emailusername_info {
1.1075.2.103  raeburn  18806:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18807:     my %titles = &Apache::lonlocal::texthash (
                   18808:                      lastname      => 'Last Name',
                   18809:                      firstname     => 'First Name',
                   18810:                      institution   => 'School/college/university',
                   18811:                      location      => "School's city, state/province, country",
                   18812:                      web           => "School's web address",
                   18813:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18814:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18815:                  );
                   18816:     return (\@fields,\%titles);
                   18817: }
                   18818: 
1.1075.2.56  raeburn  18819: sub cleanup_html {
                   18820:     my ($incoming) = @_;
                   18821:     my $outgoing;
                   18822:     if ($incoming ne '') {
                   18823:         $outgoing = $incoming;
                   18824:         $outgoing =~ s/;/&#059;/g;
                   18825:         $outgoing =~ s/\#/&#035;/g;
                   18826:         $outgoing =~ s/\&/&#038;/g;
                   18827:         $outgoing =~ s/</&#060;/g;
                   18828:         $outgoing =~ s/>/&#062;/g;
                   18829:         $outgoing =~ s/\(/&#040/g;
                   18830:         $outgoing =~ s/\)/&#041;/g;
                   18831:         $outgoing =~ s/"/&#034;/g;
                   18832:         $outgoing =~ s/'/&#039;/g;
                   18833:         $outgoing =~ s/\$/&#036;/g;
                   18834:         $outgoing =~ s{/}{&#047;}g;
                   18835:         $outgoing =~ s/=/&#061;/g;
                   18836:         $outgoing =~ s/\\/&#092;/g
                   18837:     }
                   18838:     return $outgoing;
                   18839: }
                   18840: 
1.1075.2.74  raeburn  18841: # Checks for critical messages and returns a redirect url if one exists.
                   18842: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18843:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18844: sub critical_redirect {
1.1075.2.161.  .1(raebu 18845:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18846:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18847:         return ();
                   18848:     }
1.1075.2.74  raeburn  18849:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18850:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18851:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18852:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18853:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18854:21):             if ($blocked) {
                   18855:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18856:21):                 if ($env{'request.course.sec'} ne '') {
                   18857:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18858:21):                 }
                   18859:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18860:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18861:21):                     return;
                   18862:21):                 }
                   18863:21):             }
                   18864:21):         }
1.1075.2.74  raeburn  18865:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18866:                                         $env{'user.name'});
                   18867:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18868:         my $redirecturl;
                   18869:         if ($what[0]) {
1.1075.2.158  raeburn  18870:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18871:                 $redirecturl='/adm/email?critical=display';
                   18872:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18873:                 return (1, $url);
                   18874:             }
                   18875:         }
                   18876:     }
                   18877:     return ();
                   18878: }
                   18879: 
1.1075.2.64  raeburn  18880: # Use:
                   18881: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18882: #
                   18883: ##################################################
                   18884: #          password associated functions         #
                   18885: ##################################################
                   18886: sub des_keys {
                   18887:     # Make a new key for DES encryption.
                   18888:     # Each key has two parts which are returned separately.
                   18889:     # Please note:  Each key must be passed through the &hex function
                   18890:     # before it is output to the web browser.  The hex versions cannot
                   18891:     # be used to decrypt.
                   18892:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18893:                 '8','9','a','b','c','d','e','f');
                   18894:     my $lkey='';
                   18895:     for (0..7) {
                   18896:         $lkey.=$hexstr[rand(15)];
                   18897:     }
                   18898:     my $ukey='';
                   18899:     for (0..7) {
                   18900:         $ukey.=$hexstr[rand(15)];
                   18901:     }
                   18902:     return ($lkey,$ukey);
                   18903: }
                   18904: 
                   18905: sub des_decrypt {
                   18906:     my ($key,$cyphertext) = @_;
                   18907:     my $keybin=pack("H16",$key);
                   18908:     my $cypher;
                   18909:     if ($Crypt::DES::VERSION>=2.03) {
                   18910:         $cypher=new Crypt::DES $keybin;
                   18911:     } else {
                   18912:         $cypher=new DES $keybin;
                   18913:     }
1.1075.2.106  raeburn  18914:     my $plaintext='';
                   18915:     my $cypherlength = length($cyphertext);
                   18916:     my $numchunks = int($cypherlength/32);
                   18917:     for (my $j=0; $j<$numchunks; $j++) {
                   18918:         my $start = $j*32;
                   18919:         my $cypherblock = substr($cyphertext,$start,32);
                   18920:         my $chunk =
                   18921:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18922:         $chunk .=
                   18923:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18924:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18925:         $plaintext .= $chunk;
                   18926:     }
1.1075.2.64  raeburn  18927:     return $plaintext;
                   18928: }
                   18929: 
1.1075.2.161.  .1(raebu 18930:21): sub get_requested_shorturls {
                   18931:21):     my ($cdom,$cnum,$navmap) = @_;
                   18932:21):     return unless (ref($navmap));
                   18933:21):     my ($numnew,$errors);
                   18934:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18935:21):     if (@toshorten) {
                   18936:21):         my (%maps,%resources,%titles);
                   18937:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18938:21):                                                                'shorturls',$cdom,$cnum);
                   18939:21):         if (keys(%resources)) {
                   18940:21):             my %tocreate;
                   18941:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18942:21):                 my $symb = $resources{$item};
                   18943:21):                 if ($symb) {
                   18944:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18945:21):                 }
                   18946:21):             }
                   18947:21):             if (keys(%tocreate)) {
                   18948:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18949:21):                                                       \%tocreate);
                   18950:21):             }
                   18951:21):         }
                   18952:21):     }
                   18953:21):     return ($numnew,$errors);
                   18954:21): }
                   18955:21): 
                   18956:21): sub make_short_symbs {
                   18957:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18958:21):     my ($numnew,@errors);
                   18959:21):     if (ref($tocreateref) eq 'HASH') {
                   18960:21):         my %tocreate = %{$tocreateref};
                   18961:21):         if (keys(%tocreate)) {
                   18962:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18963:21):             my $su = Short::URL->new(no_vowels => 1);
                   18964:21):             my $init = '';
                   18965:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   18966:21):             # get lock on tiny db
                   18967:21):             my $now = time;
                   18968:21):             if ($lockuser eq '') {
                   18969:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18970:21):             }
                   18971:21):             my $lockhash = {
                   18972:21):                                 "lock\0$now" => $lockuser,
                   18973:21):                             };
                   18974:21):             my $tries = 0;
                   18975:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18976:21):             my ($code,$error);
                   18977:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   18978:21):                 $tries ++;
                   18979:21):                 sleep 1;
                   18980:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18981:21):             }
                   18982:21):             if ($gotlock eq 'ok') {
                   18983:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18984:21):                                        \%addcourse,\%courseonly,\%failed);
                   18985:21):                 if (keys(%failed)) {
                   18986:21):                     my $numfailed = scalar(keys(%failed));
                   18987:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18988:21):                 }
                   18989:21):                 if (keys(%newunique)) {
                   18990:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18991:21):                     if ($putres eq 'ok') {
                   18992:21):                         $numnew = scalar(keys(%newunique));
                   18993:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18994:21):                         unless ($newputres eq 'ok') {
                   18995:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18996:21):                         }
                   18997:21):                     } else {
                   18998:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18999:21):                     }
                   19000:21):                 }
                   19001:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19002:21):                 unless ($dellockres eq 'ok') {
                   19003:21):                     push(@errors,&mt('error: could not release lockfile'));
                   19004:21):                 }
                   19005:21):             } else {
                   19006:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   19007:21):             }
                   19008:21):             if (keys(%courseonly)) {
                   19009:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19010:21):                 if ($result ne 'ok') {
                   19011:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19012:21):                 }
                   19013:21):             }
                   19014:21):         }
                   19015:21):     }
                   19016:21):     return ($numnew,\@errors);
                   19017:21): }
                   19018:21): 
                   19019:21): sub shorten_symbs {
                   19020:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19021:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19022:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19023:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19024:21):     my (%possibles,%collisions);
                   19025:21):     foreach my $key (keys(%{$tocreate})) {
                   19026:21):         my $num = String::CRC32::crc32($key);
                   19027:21):         my $tiny = $su->encode($num,$init);
                   19028:21):         if ($tiny) {
                   19029:21):             $possibles{$tiny} = $key;
                   19030:21):         }
                   19031:21):     }
                   19032:21):     if (!$init) {
                   19033:21):         $init = 1;
                   19034:21):     } else {
                   19035:21):         $init ++;
                   19036:21):     }
                   19037:21):     if (keys(%possibles)) {
                   19038:21):         my @posstiny = keys(%possibles);
                   19039:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19040:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19041:21):         if (keys(%currtiny)) {
                   19042:21):             foreach my $key (keys(%currtiny)) {
                   19043:21):                 next if ($currtiny{$key} eq '');
                   19044:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   19045:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19046:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19047:21):                         $courseonly->{$tsymb} = $key;
                   19048:21):                     }
                   19049:21):                 } else {
                   19050:21):                     $collisions{$possibles{$key}} = 1;
                   19051:21):                 }
                   19052:21):                 delete($possibles{$key});
                   19053:21):             }
                   19054:21):         }
                   19055:21):         foreach my $key (keys(%possibles)) {
                   19056:21):             $newunique->{$key} = $possibles{$key};
                   19057:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19058:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19059:21):                 $addcourse->{$tsymb} = $key;
                   19060:21):             }
                   19061:21):         }
                   19062:21):     }
                   19063:21):     if (keys(%collisions)) {
                   19064:21):         if ($init <5) {
                   19065:21):             if (!$init) {
                   19066:21):                 $init = 1;
                   19067:21):             } else {
                   19068:21):                 $init ++;
                   19069:21):             }
                   19070:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19071:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   19072:21):         } else {
                   19073:21):             foreach my $key (keys(%collisions)) {
                   19074:21):                 $failed->{$key} = 1;
                   19075:21):                 $failed->{$key} = 1;
                   19076:21):             }
                   19077:21):         }
                   19078:21):     }
                   19079:21):     return $init;
                   19080:21): }
                   19081:21): 
1.1075.2.135  raeburn  19082: sub is_nonframeable {
                   19083:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19084:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   19085:     return if (($remprotocol eq '') || ($remhost eq ''));
                   19086: 
                   19087:     $remprotocol = lc($remprotocol);
                   19088:     $remhost = lc($remhost);
                   19089:     my $remport = 80;
                   19090:     if ($remprotocol eq 'https') {
                   19091:         $remport = 443;
                   19092:     }
                   19093:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   19094:     if ($cached) {
                   19095:         unless ($nocache) {
                   19096:             if ($result) {
                   19097:                 return 1;
                   19098:             } else {
                   19099:                 return 0;
                   19100:             }
                   19101:         }
                   19102:     }
                   19103:     my $uselink;
                   19104:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  19105:     my $ua = LWP::UserAgent->new;
                   19106:     $ua->timeout(5);
                   19107:     my $response=$ua->request($request);
1.1075.2.135  raeburn  19108:     if ($response->is_success()) {
                   19109:         my $secpolicy = lc($response->header('content-security-policy'));
                   19110:         my $xframeop = lc($response->header('x-frame-options'));
                   19111:         $secpolicy =~ s/^\s+|\s+$//g;
                   19112:         $xframeop =~ s/^\s+|\s+$//g;
                   19113:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   19114:             my $remotehost = $remprotocol.'://'.$remhost;
                   19115:             my ($origin,$protocol,$port);
                   19116:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19117:                 $port = $ENV{'SERVER_PORT'};
                   19118:             } else {
                   19119:                 $port = 80;
                   19120:             }
                   19121:             if ($absolute eq '') {
                   19122:                 $protocol = 'http:';
                   19123:                 if ($port == 443) {
                   19124:                     $protocol = 'https:';
                   19125:                 }
                   19126:                 $origin = $protocol.'//'.lc($hostname);
                   19127:             } else {
                   19128:                 $origin = lc($absolute);
                   19129:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19130:             }
                   19131:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19132:                 my $framepolicy = $1;
                   19133:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19134:                 my @policies = split(/\s+/,$framepolicy);
                   19135:                 if (@policies) {
                   19136:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19137:                         $uselink = 1;
                   19138:                     } else {
                   19139:                         $uselink = 1;
                   19140:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19141:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19142:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19143:                             undef($uselink);
                   19144:                         }
                   19145:                         if ($uselink) {
                   19146:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19147:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19148:                                     undef($uselink);
                   19149:                                 }
                   19150:                             }
                   19151:                         }
                   19152:                         if ($uselink) {
                   19153:                             my @possok;
                   19154:                             if ($ip ne '') {
                   19155:                                 push(@possok,$ip);
                   19156:                             }
                   19157:                             my $hoststr = '';
                   19158:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19159:                                 if ($hoststr eq '') {
                   19160:                                     $hoststr = $part;
                   19161:                                 } else {
                   19162:                                     $hoststr = "$part.$hoststr";
                   19163:                                 }
                   19164:                                 if ($hoststr eq $hostname) {
                   19165:                                     push(@possok,$hostname);
                   19166:                                 } else {
                   19167:                                     push(@possok,"*.$hoststr");
                   19168:                                 }
                   19169:                             }
                   19170:                             if (@possok) {
                   19171:                                 foreach my $poss (@possok) {
                   19172:                                     last if (!$uselink);
                   19173:                                     foreach my $policy (@policies) {
                   19174:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19175:                                             undef($uselink);
                   19176:                                             last;
                   19177:                                         }
                   19178:                                     }
                   19179:                                 }
                   19180:                             }
                   19181:                         }
                   19182:                     }
                   19183:                 }
                   19184:             } elsif ($xframeop ne '') {
                   19185:                 $uselink = 1;
                   19186:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19187:                 if (@policies) {
                   19188:                     unless (grep(/^deny$/,@policies)) {
                   19189:                         if ($origin ne '') {
                   19190:                             if (grep(/^sameorigin$/,@policies)) {
                   19191:                                 if ($remotehost eq $origin) {
                   19192:                                     undef($uselink);
                   19193:                                 }
                   19194:                             }
                   19195:                             if ($uselink) {
                   19196:                                 foreach my $policy (@policies) {
                   19197:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19198:                                         my $allowfrom = $1;
                   19199:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19200:                                             undef($uselink);
                   19201:                                             last;
                   19202:                                         }
                   19203:                                     }
                   19204:                                 }
                   19205:                             }
                   19206:                         }
                   19207:                     }
                   19208:                 }
                   19209:             }
                   19210:         }
                   19211:     }
                   19212:     if ($nocache) {
                   19213:         if ($cached) {
                   19214:             my $devalidate;
                   19215:             if ($uselink && !$result) {
                   19216:                 $devalidate = 1;
                   19217:             } elsif (!$uselink && $result) {
                   19218:                 $devalidate = 1;
                   19219:             }
                   19220:             if ($devalidate) {
                   19221:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19222:             }
                   19223:         }
                   19224:     } else {
                   19225:         if ($uselink) {
                   19226:             $result = 1;
                   19227:         } else {
                   19228:             $result = 0;
                   19229:         }
                   19230:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19231:     }
                   19232:     return $uselink;
                   19233: }
                   19234: 
1.1075.2.161.  .1(raebu 19235:21): sub page_menu {
                   19236:21):     my ($menucolls,$menunum) = @_;
                   19237:21):     my %menu;
                   19238:21):     foreach my $item (split(/;/,$menucolls)) {
                   19239:21):         my ($num,$value) = split(/\%/,$item);
                   19240:21):         if ($num eq $menunum) {
                   19241:21):             my @entries = split(/\&/,$value);
                   19242:21):             foreach my $entry (@entries) {
                   19243:21):                 my ($name,$fields) = split(/=/,$entry);
                   19244:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   19245:21):                     $menu{$name} = $fields;
                   19246:21):                 } else {
                   19247:21):                     my @shown;
                   19248:21):                     if ($fields =~ /,/) {
                   19249:21):                         @shown = split(/,/,$fields);
                   19250:21):                     } else {
                   19251:21):                         @shown = ($fields);
                   19252:21):                     }
                   19253:21):                     if (@shown) {
                   19254:21):                         foreach my $field (@shown) {
                   19255:21):                             next if ($field eq '');
                   19256:21):                             $menu{$field} = 1;
                   19257:21):                         }
                   19258:21):                     }
                   19259:21):                 }
                   19260:21):             }
                   19261:21):         }
                   19262:21):     }
                   19263:21):     return %menu;
                   19264:21): }
                   19265:21): 
1.112     bowersj2 19266: 1;
                   19267: __END__;
1.41      ng       19268: 

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