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

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.  .26(raeb    4:-24): # $Id: loncommon.pm,v 1.1075.2.161.2.25 2024/08/17 23:31:37 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):         }
                   3455:22):     } else {
                   3456:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3457:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3458:22):     }
                   3459:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3460:22):     $numrules = 0;
                   3461:22):     $min = $Apache::lonnet::passwdmin;
                   3462:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3463:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3464:22):             if ($passwdconf{'min'} > $min) {
                   3465:22):                 $min = $passwdconf{'min'};
                   3466:22):             }
                   3467:22):         }
                   3468:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3469:22):             $max = $passwdconf{'max'};
                   3470:22):             $numrules ++;
                   3471:22):         }
                   3472:22):         @chars = @{$passwdconf{'chars'}};
                   3473:22):         if (@chars) {
                   3474:22):             $numrules ++;
                   3475:22):         }
                   3476:22):     }
                   3477:22):     if ($min > 0) {
                   3478:22):         $numrules ++;
                   3479:22):     }
                   3480:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3481:22):         if ($min) {
                   3482:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3483:22):         }
                   3484:22):         if ($max) {
                   3485:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3486:22):         }
                   3487:22):         my (@charalerts,@charrules);
                   3488:22):         if (@chars) {
                   3489:22):             if (grep(/^uc$/,@chars)) {
                   3490:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3491:22):                 push(@charrules,'uc');
                   3492:22):             }
                   3493:22):             if (grep(/^lc$/,@chars)) {
                   3494:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3495:22):                 push(@charrules,'lc');
                   3496:22):             }
                   3497:22):             if (grep(/^num$/,@chars)) {
                   3498:22):                 push(@charalerts,&mt('contain at least one number'));
                   3499:22):                 push(@charrules,'num');
                   3500:22):             }
                   3501:22):             if (grep(/^spec$/,@chars)) {
                   3502:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3503:22):                 push(@charrules,'spec');
                   3504:22):             }
                   3505:22):         }
                   3506:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3507:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3508:22):             if ($min) {
                   3509:22):                 $intargjs .= qq|
                   3510:22):             if (currpwval.length < $min) {
                   3511:22):                 rulesmsg += ' - $alert{min}';
                   3512:22):             }
                   3513:22): |;
                   3514:22):             }
                   3515:22):             if ($max) {
                   3516:22):                 $intargjs .= qq|
                   3517:22):             if (currpwval.length > $max) {
                   3518:22):                 rulesmsg += ' - $alert{max}';
                   3519:22):             }
                   3520:22): |;
                   3521:22):             }
                   3522:22):             if (@chars > 0) {
                   3523:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3524:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3525:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3526:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3527:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3528:22):                 my %rules;
                   3529:22):                 map { $rules{$_} = 1; } @chars;
                   3530:22):                 if ($rules{'uc'}) {
                   3531:22):                     $intargjs .= qq|
                   3532:22):             var ucRegExp = /[A-Z]/;
                   3533:22):             if (!ucRegExp.test(currpwval)) {
                   3534:22):                 brokerules.push('uc');
                   3535:22):             }
                   3536:22): |;
                   3537:22):                 }
                   3538:22):                 if ($rules{'lc'}) {
                   3539:22):                     $intargjs .= qq|
                   3540:22):             var lcRegExp = /[a-z]/;
                   3541:22):             if (!lcRegExp.test(currpwval)) {
                   3542:22):                 brokerules.push('lc');
                   3543:22):             }
                   3544:22): |;
                   3545:22):                 }
                   3546:22):                 if ($rules{'num'}) {
                   3547:22):                      $intargjs .= qq|
                   3548:22):             var numRegExp = /[0-9]/;
                   3549:22):             if (!numRegExp.test(currpwval)) {
                   3550:22):                 brokerules.push('num');
                   3551:22):             }
                   3552:22): |;
                   3553:22):                 }
                   3554:22):                 if ($rules{'spec'}) {
                   3555:22):                      $intargjs .= q|
                   3556:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3557:22):             if (!specRegExp.test(currpwval)) {
                   3558:22):                 brokerules.push('spec');
                   3559:22):             }
                   3560:22): |;
                   3561:22):                 }
                   3562:22):                 $intargjs .= qq|
                   3563:22):             if (brokerules.length > 0) {
                   3564:22):                 for (var i=0; i<brokerules.length; i++) {
                   3565:22):                     for (var j=0; j<charrules.length; j++) {
                   3566:22):                         if (brokerules[i] == charrules[j]) {
                   3567:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3568:22):                             break;
                   3569:22):                         }
                   3570:22):                     }
                   3571:22):                 }
                   3572:22):             }
                   3573:22): |;
                   3574:22):             }
                   3575:22):             $intargjs .= qq|
                   3576:22):             if (rulesmsg != '') {
                   3577:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3578:22):                 alert(rulesmsg);
                   3579:22):                 return false;
                   3580:22):             }
                   3581:22): |;
                   3582:22):     }
                   3583:22):     return ($numrules,$intargjs);
                   3584:22): }
                   3585:22): 
1.80      albertel 3586: ###############################################################
                   3587: ##    Get Kerberos Defaults for Domain                 ##
                   3588: ###############################################################
                   3589: ##
                   3590: ## Returns default kerberos version and an associated argument
                   3591: ## as listed in file domain.tab. If not listed, provides
                   3592: ## appropriate default domain and kerberos version.
                   3593: ##
                   3594: #-------------------------------------------
                   3595: 
                   3596: =pod
                   3597: 
1.648     raeburn  3598: =item * &get_kerberos_defaults()
1.80      albertel 3599: 
                   3600: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3601: version and domain. If not found, it defaults to version 4 and the 
                   3602: domain of the server.
1.80      albertel 3603: 
1.648     raeburn  3604: =over 4
                   3605: 
1.80      albertel 3606: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3607: 
1.648     raeburn  3608: =back
                   3609: 
                   3610: =back
                   3611: 
1.80      albertel 3612: =cut
                   3613: 
                   3614: #-------------------------------------------
                   3615: sub get_kerberos_defaults {
                   3616:     my $domain=shift;
1.641     raeburn  3617:     my ($krbdef,$krbdefdom);
                   3618:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3619:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3620:         $krbdef = $domdefaults{'auth_def'};
                   3621:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3622:     } else {
1.80      albertel 3623:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3624:         my $krbdefdom=$1;
                   3625:         $krbdefdom=~tr/a-z/A-Z/;
                   3626:         $krbdef = "krb4";
                   3627:     }
                   3628:     return ($krbdef,$krbdefdom);
                   3629: }
1.112     bowersj2 3630: 
1.32      matthew  3631: 
1.46      matthew  3632: ###############################################################
                   3633: ##                Thesaurus Functions                        ##
                   3634: ###############################################################
1.20      www      3635: 
1.46      matthew  3636: =pod
1.20      www      3637: 
1.112     bowersj2 3638: =head1 Thesaurus Functions
                   3639: 
                   3640: =over 4
                   3641: 
1.648     raeburn  3642: =item * &initialize_keywords()
1.46      matthew  3643: 
                   3644: Initializes the package variable %Keywords if it is empty.  Uses the
                   3645: package variable $thesaurus_db_file.
                   3646: 
                   3647: =cut
                   3648: 
                   3649: ###################################################
                   3650: 
                   3651: sub initialize_keywords {
                   3652:     return 1 if (scalar keys(%Keywords));
                   3653:     # If we are here, %Keywords is empty, so fill it up
                   3654:     #   Make sure the file we need exists...
                   3655:     if (! -e $thesaurus_db_file) {
                   3656:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3657:                                  " failed because it does not exist");
                   3658:         return 0;
                   3659:     }
                   3660:     #   Set up the hash as a database
                   3661:     my %thesaurus_db;
                   3662:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3663:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3664:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3665:                                  $thesaurus_db_file);
                   3666:         return 0;
                   3667:     } 
                   3668:     #  Get the average number of appearances of a word.
                   3669:     my $avecount = $thesaurus_db{'average.count'};
                   3670:     #  Put keywords (those that appear > average) into %Keywords
                   3671:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3672:         my ($count,undef) = split /:/,$data;
                   3673:         $Keywords{$word}++ if ($count > $avecount);
                   3674:     }
                   3675:     untie %thesaurus_db;
                   3676:     # Remove special values from %Keywords.
1.356     albertel 3677:     foreach my $value ('total.count','average.count') {
                   3678:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3679:   }
1.46      matthew  3680:     return 1;
                   3681: }
                   3682: 
                   3683: ###################################################
                   3684: 
                   3685: =pod
                   3686: 
1.648     raeburn  3687: =item * &keyword($word)
1.46      matthew  3688: 
                   3689: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3690: than the average number of times in the thesaurus database.  Calls 
                   3691: &initialize_keywords
                   3692: 
                   3693: =cut
                   3694: 
                   3695: ###################################################
1.20      www      3696: 
                   3697: sub keyword {
1.46      matthew  3698:     return if (!&initialize_keywords());
                   3699:     my $word=lc(shift());
                   3700:     $word=~s/\W//g;
                   3701:     return exists($Keywords{$word});
1.20      www      3702: }
1.46      matthew  3703: 
                   3704: ###############################################################
                   3705: 
                   3706: =pod 
1.20      www      3707: 
1.648     raeburn  3708: =item * &get_related_words()
1.46      matthew  3709: 
1.160     matthew  3710: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3711: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3712: will be returned.  The order of the words returned is determined by the
                   3713: database which holds them.
                   3714: 
                   3715: Uses global $thesaurus_db_file.
                   3716: 
1.1057    foxr     3717: 
1.46      matthew  3718: =cut
                   3719: 
                   3720: ###############################################################
                   3721: sub get_related_words {
                   3722:     my $keyword = shift;
                   3723:     my %thesaurus_db;
                   3724:     if (! -e $thesaurus_db_file) {
                   3725:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3726:                                  "failed because the file does not exist");
                   3727:         return ();
                   3728:     }
                   3729:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3730:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3731:         return ();
                   3732:     } 
                   3733:     my @Words=();
1.429     www      3734:     my $count=0;
1.46      matthew  3735:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3736: 	# The first element is the number of times
                   3737: 	# the word appears.  We do not need it now.
1.429     www      3738: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3739: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3740: 	my $threshold=$mostfrequentcount/10;
                   3741:         foreach my $possibleword (@RelatedWords) {
                   3742:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3743:             if ($wordcount>$threshold) {
                   3744: 		push(@Words,$word);
                   3745:                 $count++;
                   3746:                 if ($count>10) { last; }
                   3747: 	    }
1.20      www      3748:         }
                   3749:     }
1.46      matthew  3750:     untie %thesaurus_db;
                   3751:     return @Words;
1.14      harris41 3752: }
1.46      matthew  3753: 
1.112     bowersj2 3754: =pod
                   3755: 
                   3756: =back
                   3757: 
                   3758: =cut
1.61      www      3759: 
                   3760: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3761: =pod
                   3762: 
1.112     bowersj2 3763: =head1 User Name Functions
                   3764: 
                   3765: =over 4
                   3766: 
1.648     raeburn  3767: =item * &plainname($uname,$udom,$first)
1.81      albertel 3768: 
1.112     bowersj2 3769: Takes a users logon name and returns it as a string in
1.226     albertel 3770: "first middle last generation" form 
                   3771: if $first is set to 'lastname' then it returns it as
                   3772: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3773: 
                   3774: =cut
1.61      www      3775: 
1.295     www      3776: 
1.81      albertel 3777: ###############################################################
1.61      www      3778: sub plainname {
1.226     albertel 3779:     my ($uname,$udom,$first)=@_;
1.537     albertel 3780:     return if (!defined($uname) || !defined($udom));
1.295     www      3781:     my %names=&getnames($uname,$udom);
1.226     albertel 3782:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3783: 					  $names{'middlename'},
                   3784: 					  $names{'lastname'},
                   3785: 					  $names{'generation'},$first);
                   3786:     $name=~s/^\s+//;
1.62      www      3787:     $name=~s/\s+$//;
                   3788:     $name=~s/\s+/ /g;
1.353     albertel 3789:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3790:     return $name;
1.61      www      3791: }
1.66      www      3792: 
                   3793: # -------------------------------------------------------------------- Nickname
1.81      albertel 3794: =pod
                   3795: 
1.648     raeburn  3796: =item * &nickname($uname,$udom)
1.81      albertel 3797: 
                   3798: Gets a users name and returns it as a string as
                   3799: 
                   3800: "&quot;nickname&quot;"
1.66      www      3801: 
1.81      albertel 3802: if the user has a nickname or
                   3803: 
                   3804: "first middle last generation"
                   3805: 
                   3806: if the user does not
                   3807: 
                   3808: =cut
1.66      www      3809: 
                   3810: sub nickname {
                   3811:     my ($uname,$udom)=@_;
1.537     albertel 3812:     return if (!defined($uname) || !defined($udom));
1.295     www      3813:     my %names=&getnames($uname,$udom);
1.68      albertel 3814:     my $name=$names{'nickname'};
1.66      www      3815:     if ($name) {
                   3816:        $name='&quot;'.$name.'&quot;'; 
                   3817:     } else {
                   3818:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3819: 	     $names{'lastname'}.' '.$names{'generation'};
                   3820:        $name=~s/\s+$//;
                   3821:        $name=~s/\s+/ /g;
                   3822:     }
                   3823:     return $name;
                   3824: }
                   3825: 
1.295     www      3826: sub getnames {
                   3827:     my ($uname,$udom)=@_;
1.537     albertel 3828:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3829:     if ($udom eq 'public' && $uname eq 'public') {
                   3830: 	return ('lastname' => &mt('Public'));
                   3831:     }
1.295     www      3832:     my $id=$uname.':'.$udom;
                   3833:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3834:     if ($cached) {
                   3835: 	return %{$names};
                   3836:     } else {
                   3837: 	my %loadnames=&Apache::lonnet::get('environment',
                   3838:                     ['firstname','middlename','lastname','generation','nickname'],
                   3839: 					 $udom,$uname);
                   3840: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3841: 	return %loadnames;
                   3842:     }
                   3843: }
1.61      www      3844: 
1.542     raeburn  3845: # -------------------------------------------------------------------- getemails
1.648     raeburn  3846: 
1.542     raeburn  3847: =pod
                   3848: 
1.648     raeburn  3849: =item * &getemails($uname,$udom)
1.542     raeburn  3850: 
                   3851: Gets a user's email information and returns it as a hash with keys:
                   3852: notification, critnotification, permanentemail
                   3853: 
                   3854: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3855: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3856:  
1.648     raeburn  3857: 
1.542     raeburn  3858: =cut
                   3859: 
1.648     raeburn  3860: 
1.466     albertel 3861: sub getemails {
                   3862:     my ($uname,$udom)=@_;
                   3863:     if ($udom eq 'public' && $uname eq 'public') {
                   3864: 	return;
                   3865:     }
1.467     www      3866:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3867:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3868:     my $id=$uname.':'.$udom;
                   3869:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3870:     if ($cached) {
                   3871: 	return %{$names};
                   3872:     } else {
                   3873: 	my %loadnames=&Apache::lonnet::get('environment',
                   3874:                     			   ['notification','critnotification',
                   3875: 					    'permanentemail'],
                   3876: 					   $udom,$uname);
                   3877: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3878: 	return %loadnames;
                   3879:     }
                   3880: }
                   3881: 
1.551     albertel 3882: sub flush_email_cache {
                   3883:     my ($uname,$udom)=@_;
                   3884:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3885:     if (!$uname) { $uname=$env{'user.name'};   }
                   3886:     return if ($udom eq 'public' && $uname eq 'public');
                   3887:     my $id=$uname.':'.$udom;
                   3888:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3889: }
                   3890: 
1.728     raeburn  3891: # -------------------------------------------------------------------- getlangs
                   3892: 
                   3893: =pod
                   3894: 
                   3895: =item * &getlangs($uname,$udom)
                   3896: 
                   3897: Gets a user's language preference and returns it as a hash with key:
                   3898: language.
                   3899: 
                   3900: =cut
                   3901: 
                   3902: 
                   3903: sub getlangs {
                   3904:     my ($uname,$udom) = @_;
                   3905:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3906:     if (!$uname) { $uname=$env{'user.name'};   }
                   3907:     my $id=$uname.':'.$udom;
                   3908:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3909:     if ($cached) {
                   3910:         return %{$langs};
                   3911:     } else {
                   3912:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3913:                                            $udom,$uname);
                   3914:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3915:         return %loadlangs;
                   3916:     }
                   3917: }
                   3918: 
                   3919: sub flush_langs_cache {
                   3920:     my ($uname,$udom)=@_;
                   3921:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3922:     if (!$uname) { $uname=$env{'user.name'};   }
                   3923:     return if ($udom eq 'public' && $uname eq 'public');
                   3924:     my $id=$uname.':'.$udom;
                   3925:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3926: }
                   3927: 
1.61      www      3928: # ------------------------------------------------------------------ Screenname
1.81      albertel 3929: 
                   3930: =pod
                   3931: 
1.648     raeburn  3932: =item * &screenname($uname,$udom)
1.81      albertel 3933: 
                   3934: Gets a users screenname and returns it as a string
                   3935: 
                   3936: =cut
1.61      www      3937: 
                   3938: sub screenname {
                   3939:     my ($uname,$udom)=@_;
1.258     albertel 3940:     if ($uname eq $env{'user.name'} &&
                   3941: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3942:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3943:     return $names{'screenname'};
1.62      www      3944: }
                   3945: 
1.212     albertel 3946: 
1.802     bisitz   3947: # ------------------------------------------------------------- Confirm Wrapper
                   3948: =pod
                   3949: 
1.1075.2.42  raeburn  3950: =item * &confirmwrapper($message)
1.802     bisitz   3951: 
                   3952: Wrap messages about completion of operation in box
                   3953: 
                   3954: =cut
                   3955: 
                   3956: sub confirmwrapper {
                   3957:     my ($message)=@_;
                   3958:     if ($message) {
                   3959:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3960:                .$message."\n"
                   3961:                .'</div>'."\n";
                   3962:     } else {
                   3963:         return $message;
                   3964:     }
                   3965: }
                   3966: 
1.62      www      3967: # ------------------------------------------------------------- Message Wrapper
                   3968: 
                   3969: sub messagewrapper {
1.369     www      3970:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3971:     return 
1.441     albertel 3972:         '<a href="/adm/email?compose=individual&amp;'.
                   3973:         'recname='.$username.'&amp;recdom='.$domain.
                   3974: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3975:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3976: }
1.802     bisitz   3977: 
1.74      www      3978: # --------------------------------------------------------------- Notes Wrapper
                   3979: 
                   3980: sub noteswrapper {
                   3981:     my ($link,$un,$do)=@_;
                   3982:     return 
1.896     amueller 3983: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3984: }
1.802     bisitz   3985: 
1.62      www      3986: # ------------------------------------------------------------- Aboutme Wrapper
                   3987: 
                   3988: sub aboutmewrapper {
1.1070    raeburn  3989:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3990:     if (!defined($username)  && !defined($domain)) {
                   3991:         return;
                   3992:     }
1.1075.2.15  raeburn  3993:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3994: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3995: }
                   3996: 
                   3997: # ------------------------------------------------------------ Syllabus Wrapper
                   3998: 
                   3999: sub syllabuswrapper {
1.707     bisitz   4000:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4001:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4002: }
1.14      harris41 4003: 
1.1075.2.161.  .11(raeb 4004:-22): sub aboutme_on {
                   4005:-22):     my ($uname,$udom)=@_;
                   4006:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   4007:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4008:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4009:-22):     my $hashkey=$uname.':'.$udom;
                   4010:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4011:-22):     if ($cached) {
                   4012:-22):         return $aboutme;
                   4013:-22):     }
                   4014:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4015:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4016:-22):     return $aboutme;
                   4017:-22): }
                   4018:-22): 
                   4019:-22): sub devalidate_aboutme_cache {
                   4020:-22):     my ($uname,$udom)=@_;
                   4021:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4022:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   4023:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   4024:-22):     my $id=$uname.':'.$udom;
                   4025:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4026:-22): }
                   4027:-22): 
1.802     bisitz   4028: # -----------------------------------------------------------------------------
                   4029: 
1.208     matthew  4030: sub track_student_link {
1.887     raeburn  4031:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4032:     my $link ="/adm/trackstudent?";
1.208     matthew  4033:     my $title = 'View recent activity';
                   4034:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4035:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4036:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4037:         $title .= ' of this student';
1.268     albertel 4038:     } 
1.208     matthew  4039:     if (defined($target) && $target !~ /^\s*$/) {
                   4040:         $target = qq{target="$target"};
                   4041:     } else {
                   4042:         $target = '';
                   4043:     }
1.268     albertel 4044:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4045:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4046:     $title = &mt($title);
                   4047:     $linktext = &mt($linktext);
1.448     albertel 4048:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4049: 	&help_open_topic('View_recent_activity');
1.208     matthew  4050: }
                   4051: 
1.781     raeburn  4052: sub slot_reservations_link {
                   4053:     my ($linktext,$sname,$sdom,$target) = @_;
                   4054:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4055:     my $title = 'View slot reservation history';
                   4056:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4057:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4058:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4059:         $title .= ' of this student';
                   4060:     }
                   4061:     if (defined($target) && $target !~ /^\s*$/) {
                   4062:         $target = qq{target="$target"};
                   4063:     } else {
                   4064:         $target = '';
                   4065:     }
                   4066:     $title = &mt($title);
                   4067:     $linktext = &mt($linktext);
                   4068:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4069: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4070: 
                   4071: }
                   4072: 
1.508     www      4073: # ===================================================== Display a student photo
                   4074: 
                   4075: 
1.509     albertel 4076: sub student_image_tag {
1.508     www      4077:     my ($domain,$user)=@_;
                   4078:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4079:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4080: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4081:     } else {
                   4082: 	return '';
                   4083:     }
                   4084: }
                   4085: 
1.112     bowersj2 4086: =pod
                   4087: 
                   4088: =back
                   4089: 
                   4090: =head1 Access .tab File Data
                   4091: 
                   4092: =over 4
                   4093: 
1.648     raeburn  4094: =item * &languageids() 
1.112     bowersj2 4095: 
                   4096: returns list of all language ids
                   4097: 
                   4098: =cut
                   4099: 
1.14      harris41 4100: sub languageids {
1.16      harris41 4101:     return sort(keys(%language));
1.14      harris41 4102: }
                   4103: 
1.112     bowersj2 4104: =pod
                   4105: 
1.648     raeburn  4106: =item * &languagedescription() 
1.112     bowersj2 4107: 
                   4108: returns description of a specified language id
                   4109: 
                   4110: =cut
                   4111: 
1.14      harris41 4112: sub languagedescription {
1.125     www      4113:     my $code=shift;
                   4114:     return  ($supported_language{$code}?'* ':'').
                   4115:             $language{$code}.
1.126     www      4116: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4117: }
                   4118: 
1.1048    foxr     4119: =pod
                   4120: 
                   4121: =item * &plainlanguagedescription
                   4122: 
                   4123: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4124: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4125: 
                   4126: =cut
                   4127: 
1.145     www      4128: sub plainlanguagedescription {
                   4129:     my $code=shift;
                   4130:     return $language{$code};
                   4131: }
                   4132: 
1.1048    foxr     4133: =pod
                   4134: 
                   4135: =item * &supportedlanguagecode
                   4136: 
                   4137: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4138: code.
                   4139: 
                   4140: =cut
                   4141: 
1.145     www      4142: sub supportedlanguagecode {
                   4143:     my $code=shift;
                   4144:     return $supported_language{$code};
1.97      www      4145: }
                   4146: 
1.112     bowersj2 4147: =pod
                   4148: 
1.1048    foxr     4149: =item * &latexlanguage()
                   4150: 
                   4151: Given a language key code returns the correspondnig language to use
                   4152: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4153: is no supported hyphenation for the language code.
                   4154: 
                   4155: =cut
                   4156: 
                   4157: sub latexlanguage {
                   4158:     my $code = shift;
                   4159:     return $latex_language{$code};
                   4160: }
                   4161: 
                   4162: =pod
                   4163: 
                   4164: =item * &latexhyphenation()
                   4165: 
                   4166: Same as above but what's supplied is the language as it might be stored
                   4167: in the metadata.
                   4168: 
                   4169: =cut
                   4170: 
                   4171: sub latexhyphenation {
                   4172:     my $key = shift;
                   4173:     return $latex_language_bykey{$key};
                   4174: }
                   4175: 
                   4176: =pod
                   4177: 
1.648     raeburn  4178: =item * &copyrightids() 
1.112     bowersj2 4179: 
                   4180: returns list of all copyrights
                   4181: 
                   4182: =cut
                   4183: 
                   4184: sub copyrightids {
                   4185:     return sort(keys(%cprtag));
                   4186: }
                   4187: 
                   4188: =pod
                   4189: 
1.648     raeburn  4190: =item * &copyrightdescription() 
1.112     bowersj2 4191: 
                   4192: returns description of a specified copyright id
                   4193: 
                   4194: =cut
                   4195: 
                   4196: sub copyrightdescription {
1.166     www      4197:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4198: }
1.197     matthew  4199: 
                   4200: =pod
                   4201: 
1.648     raeburn  4202: =item * &source_copyrightids() 
1.192     taceyjo1 4203: 
                   4204: returns list of all source copyrights
                   4205: 
                   4206: =cut
                   4207: 
                   4208: sub source_copyrightids {
                   4209:     return sort(keys(%scprtag));
                   4210: }
                   4211: 
                   4212: =pod
                   4213: 
1.648     raeburn  4214: =item * &source_copyrightdescription() 
1.192     taceyjo1 4215: 
                   4216: returns description of a specified source copyright id
                   4217: 
                   4218: =cut
                   4219: 
                   4220: sub source_copyrightdescription {
                   4221:     return &mt($scprtag{shift(@_)});
                   4222: }
1.112     bowersj2 4223: 
                   4224: =pod
                   4225: 
1.648     raeburn  4226: =item * &filecategories() 
1.112     bowersj2 4227: 
                   4228: returns list of all file categories
                   4229: 
                   4230: =cut
                   4231: 
                   4232: sub filecategories {
                   4233:     return sort(keys(%category_extensions));
                   4234: }
                   4235: 
                   4236: =pod
                   4237: 
1.648     raeburn  4238: =item * &filecategorytypes() 
1.112     bowersj2 4239: 
                   4240: returns list of file types belonging to a given file
                   4241: category
                   4242: 
                   4243: =cut
                   4244: 
                   4245: sub filecategorytypes {
1.356     albertel 4246:     my ($cat) = @_;
                   4247:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4248: }
                   4249: 
                   4250: =pod
                   4251: 
1.648     raeburn  4252: =item * &fileembstyle() 
1.112     bowersj2 4253: 
                   4254: returns embedding style for a specified file type
                   4255: 
                   4256: =cut
                   4257: 
                   4258: sub fileembstyle {
                   4259:     return $fe{lc(shift(@_))};
1.169     www      4260: }
                   4261: 
1.351     www      4262: sub filemimetype {
                   4263:     return $fm{lc(shift(@_))};
                   4264: }
                   4265: 
1.169     www      4266: 
                   4267: sub filecategoryselect {
                   4268:     my ($name,$value)=@_;
1.189     matthew  4269:     return &select_form($value,$name,
1.970     raeburn  4270:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4271: }
                   4272: 
                   4273: =pod
                   4274: 
1.648     raeburn  4275: =item * &filedescription() 
1.112     bowersj2 4276: 
                   4277: returns description for a specified file type
                   4278: 
                   4279: =cut
                   4280: 
                   4281: sub filedescription {
1.188     matthew  4282:     my $file_description = $fd{lc(shift())};
                   4283:     $file_description =~ s:([\[\]]):~$1:g;
                   4284:     return &mt($file_description);
1.112     bowersj2 4285: }
                   4286: 
                   4287: =pod
                   4288: 
1.648     raeburn  4289: =item * &filedescriptionex() 
1.112     bowersj2 4290: 
                   4291: returns description for a specified file type with
                   4292: extra formatting
                   4293: 
                   4294: =cut
                   4295: 
                   4296: sub filedescriptionex {
                   4297:     my $ex=shift;
1.188     matthew  4298:     my $file_description = $fd{lc($ex)};
                   4299:     $file_description =~ s:([\[\]]):~$1:g;
                   4300:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4301: }
                   4302: 
                   4303: # End of .tab access
                   4304: =pod
                   4305: 
                   4306: =back
                   4307: 
                   4308: =cut
                   4309: 
                   4310: # ------------------------------------------------------------------ File Types
                   4311: sub fileextensions {
                   4312:     return sort(keys(%fe));
                   4313: }
                   4314: 
1.97      www      4315: # ----------------------------------------------------------- Display Languages
                   4316: # returns a hash with all desired display languages
                   4317: #
                   4318: 
                   4319: sub display_languages {
                   4320:     my %languages=();
1.695     raeburn  4321:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4322: 	$languages{$lang}=1;
1.97      www      4323:     }
                   4324:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4325:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4326: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4327: 	    $languages{$lang}=1;
1.97      www      4328:         }
                   4329:     }
                   4330:     return %languages;
1.14      harris41 4331: }
                   4332: 
1.582     albertel 4333: sub languages {
                   4334:     my ($possible_langs) = @_;
1.695     raeburn  4335:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4336:     if (!ref($possible_langs)) {
                   4337: 	if( wantarray ) {
                   4338: 	    return @preferred_langs;
                   4339: 	} else {
                   4340: 	    return $preferred_langs[0];
                   4341: 	}
                   4342:     }
                   4343:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4344:     my @preferred_possibilities;
                   4345:     foreach my $preferred_lang (@preferred_langs) {
                   4346: 	if (exists($possibilities{$preferred_lang})) {
                   4347: 	    push(@preferred_possibilities, $preferred_lang);
                   4348: 	}
                   4349:     }
                   4350:     if( wantarray ) {
                   4351: 	return @preferred_possibilities;
                   4352:     }
                   4353:     return $preferred_possibilities[0];
                   4354: }
                   4355: 
1.742     raeburn  4356: sub user_lang {
                   4357:     my ($touname,$toudom,$fromcid) = @_;
                   4358:     my @userlangs;
                   4359:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4360:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4361:                     $env{'course.'.$fromcid.'.languages'}));
                   4362:     } else {
                   4363:         my %langhash = &getlangs($touname,$toudom);
                   4364:         if ($langhash{'languages'} ne '') {
                   4365:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4366:         } else {
                   4367:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4368:             if ($domdefs{'lang_def'} ne '') {
                   4369:                 @userlangs = ($domdefs{'lang_def'});
                   4370:             }
                   4371:         }
                   4372:     }
                   4373:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4374:     my $user_lh = Apache::localize->get_handle(@languages);
                   4375:     return $user_lh;
                   4376: }
                   4377: 
                   4378: 
1.112     bowersj2 4379: ###############################################################
                   4380: ##               Student Answer Attempts                     ##
                   4381: ###############################################################
                   4382: 
                   4383: =pod
                   4384: 
                   4385: =head1 Alternate Problem Views
                   4386: 
                   4387: =over 4
                   4388: 
1.648     raeburn  4389: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4390:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4391: 
                   4392: Return string with previous attempt on problem. Arguments:
                   4393: 
                   4394: =over 4
                   4395: 
                   4396: =item * $symb: Problem, including path
                   4397: 
                   4398: =item * $username: username of the desired student
                   4399: 
                   4400: =item * $domain: domain of the desired student
1.14      harris41 4401: 
1.112     bowersj2 4402: =item * $course: Course ID
1.14      harris41 4403: 
1.112     bowersj2 4404: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4405:     something
1.14      harris41 4406: 
1.112     bowersj2 4407: =item * $regexp: if string matches this regexp, the string will be
                   4408:     sent to $gradesub
1.14      harris41 4409: 
1.112     bowersj2 4410: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4411: 
1.1075.2.86  raeburn  4412: =item * $usec: section of the desired student
                   4413: 
                   4414: =item * $identifier: counter for student (multiple students one problem) or
                   4415:     problem (one student; whole sequence).
                   4416: 
1.112     bowersj2 4417: =back
1.14      harris41 4418: 
1.112     bowersj2 4419: The output string is a table containing all desired attempts, if any.
1.16      harris41 4420: 
1.112     bowersj2 4421: =cut
1.1       albertel 4422: 
                   4423: sub get_previous_attempt {
1.1075.2.86  raeburn  4424:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4425:   my $prevattempts='';
1.43      ng       4426:   no strict 'refs';
1.1       albertel 4427:   if ($symb) {
1.3       albertel 4428:     my (%returnhash)=
                   4429:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4430:     if ($returnhash{'version'}) {
                   4431:       my %lasthash=();
                   4432:       my $version;
                   4433:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4434:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4435:             if ($key =~ /\.rawrndseed$/) {
                   4436:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4437:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4438:             } else {
                   4439:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4440:             }
1.19      harris41 4441:         }
1.1       albertel 4442:       }
1.596     albertel 4443:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4444:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4445:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4446:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4447:       foreach my $key (sort(keys(%lasthash))) {
                   4448: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4449: 	if ($#parts > 0) {
1.31      albertel 4450: 	  my $data=$parts[-1];
1.989     raeburn  4451:           next if ($data eq 'foilorder');
1.31      albertel 4452: 	  pop(@parts);
1.1010    www      4453:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4454:           if ($data eq 'type') {
                   4455:               unless ($showsurv) {
                   4456:                   my $id = join(',',@parts);
                   4457:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4458:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4459:                       $lasthidden{$ign.'.'.$id} = 1;
                   4460:                   }
1.945     raeburn  4461:               }
1.1075.2.86  raeburn  4462:               if ($identifier ne '') {
                   4463:                   my $id = join(',',@parts);
                   4464:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4465:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4466:                       $hidestatus{$ign.'.'.$id} = 1;
                   4467:                   }
                   4468:               }
                   4469:           } elsif ($data eq 'regrader') {
                   4470:               if (($identifier ne '') && (@parts)) {
                   4471:                   my $id = join(',',@parts);
                   4472:                   $regraded{$ign.'.'.$id} = 1;
                   4473:               }
1.1010    www      4474:           } 
1.31      albertel 4475: 	} else {
1.41      ng       4476: 	  if ($#parts == 0) {
                   4477: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4478: 	  } else {
                   4479: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4480: 	  }
1.31      albertel 4481: 	}
1.16      harris41 4482:       }
1.596     albertel 4483:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4484:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4485:         my (%solved,%resets,%probstatus);
                   4486:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4487:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4488:                 foreach my $id (keys(%regraded)) {
                   4489:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4490:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4491:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4492:                         push(@{$resets{$id}},$version);
                   4493:                     }
                   4494:                 }
                   4495:             }
                   4496:         }
1.40      ng       4497: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4498:             my (@hidden,@unsolved);
1.945     raeburn  4499:             if (%typeparts) {
                   4500:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4501:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4502:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4503:                         push(@hidden,$id);
1.1075.2.86  raeburn  4504:                     } elsif ($identifier ne '') {
                   4505:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4506:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4507:                                 ($hidestatus{$id})) {
                   4508:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4509:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4510:                                 push(@{$solved{$id}},$version);
                   4511:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4512:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4513:                                 my $skip;
                   4514:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4515:                                     foreach my $reset (@{$resets{$id}}) {
                   4516:                                         if ($reset > $solved{$id}[-1]) {
                   4517:                                             $skip=1;
                   4518:                                             last;
                   4519:                                         }
                   4520:                                     }
                   4521:                                 }
                   4522:                                 unless ($skip) {
                   4523:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4524:                                     push(@unsolved,$partslist);
                   4525:                                 }
                   4526:                             }
                   4527:                         }
1.945     raeburn  4528:                     }
                   4529:                 }
                   4530:             }
                   4531:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4532:                            '<td>'.&mt('Transaction [_1]',$version);
                   4533:             if (@unsolved) {
                   4534:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4535:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4536:                                  &mt('Hide').'</label></span>';
                   4537:             }
                   4538:             $prevattempts .= '</td>';
1.945     raeburn  4539:             if (@hidden) {
                   4540:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4541:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4542:                     my $hide;
                   4543:                     foreach my $id (@hidden) {
                   4544:                         if ($key =~ /^\Q$id\E/) {
                   4545:                             $hide = 1;
                   4546:                             last;
                   4547:                         }
                   4548:                     }
                   4549:                     if ($hide) {
                   4550:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4551:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4552:                             my $value = &format_previous_attempt_value($key,
                   4553:                                              $returnhash{$version.':'.$key});
                   4554:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4555:                         } else {
                   4556:                             $prevattempts.='<td>&nbsp;</td>';
                   4557:                         }
                   4558:                     } else {
                   4559:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4560:                             my $value = $returnhash{$version.':'.$key};
                   4561:                             if ($key =~ /\.rndseed$/) {
                   4562:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4563:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4564:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4565:                                 }
                   4566:                             }
                   4567:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4568:                                            '&nbsp;</td>';
1.945     raeburn  4569:                         } else {
                   4570:                             $prevattempts.='<td>&nbsp;</td>';
                   4571:                         }
                   4572:                     }
                   4573:                 }
                   4574:             } else {
                   4575: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4576:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4577:                     my $value = $returnhash{$version.':'.$key};
                   4578:                     if ($key =~ /\.rndseed$/) {
                   4579:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4580:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4581:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4582:                         }
                   4583:                     }
                   4584:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4585:                                    '&nbsp;</td>';
1.945     raeburn  4586: 	        }
                   4587:             }
                   4588: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4589: 	 }
1.1       albertel 4590:       }
1.945     raeburn  4591:       my @currhidden = keys(%lasthidden);
1.596     albertel 4592:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4593:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4594:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4595:           if (%typeparts) {
                   4596:               my $hidden;
                   4597:               foreach my $id (@currhidden) {
                   4598:                   if ($key =~ /^\Q$id\E/) {
                   4599:                       $hidden = 1;
                   4600:                       last;
                   4601:                   }
                   4602:               }
                   4603:               if ($hidden) {
                   4604:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4605:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4606:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4607:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4608:                           $value = &$gradesub($value);
                   4609:                       }
                   4610:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4611:                   } else {
                   4612:                       $prevattempts.='<td>&nbsp;</td>';
                   4613:                   }
                   4614:               } else {
                   4615:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4616:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4617:                       $value = &$gradesub($value);
                   4618:                   }
                   4619:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4620:               }
                   4621:           } else {
                   4622: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4623: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4624:                   $value = &$gradesub($value);
                   4625:               }
                   4626: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4627:           }
1.16      harris41 4628:       }
1.596     albertel 4629:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4630:     } else {
1.1075.2.161.  .17(raeb 4631:-23):       my $msg;
                   4632:-23):       if ($symb =~ /ext\.tool$/) {
                   4633:-23):           $msg = &mt('No grade passed back.');
                   4634:-23):       } else {
                   4635:-23):           $msg = &mt('Nothing submitted - no attempts.');
                   4636:-23):       }
1.596     albertel 4637:       $prevattempts=
                   4638: 	  &start_data_table().&start_data_table_row().
1.1075.2.161.  .17(raeb 4639:-23): 	  '<td>'.$msg.'</td>'.
1.596     albertel 4640: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4641:     }
                   4642:   } else {
1.596     albertel 4643:     $prevattempts=
                   4644: 	  &start_data_table().&start_data_table_row().
                   4645: 	  '<td>'.&mt('No data.').'</td>'.
                   4646: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4647:   }
1.10      albertel 4648: }
                   4649: 
1.581     albertel 4650: sub format_previous_attempt_value {
                   4651:     my ($key,$value) = @_;
1.1011    www      4652:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4653: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4654:     } elsif (ref($value) eq 'ARRAY') {
                   4655: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4656:     } elsif ($key =~ /answerstring$/) {
                   4657:         my %answers = &Apache::lonnet::str2hash($value);
                   4658:         my @anskeys = sort(keys(%answers));
                   4659:         if (@anskeys == 1) {
                   4660:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4661:             if ($answer =~ m{\0}) {
                   4662:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4663:             }
                   4664:             my $tag_internal_answer_name = 'INTERNAL';
                   4665:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4666:                 $value = $answer; 
                   4667:             } else {
                   4668:                 $value = $anskeys[0].'='.$answer;
                   4669:             }
                   4670:         } else {
                   4671:             foreach my $ans (@anskeys) {
                   4672:                 my $answer = $answers{$ans};
1.1001    raeburn  4673:                 if ($answer =~ m{\0}) {
                   4674:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4675:                 }
                   4676:                 $value .=  $ans.'='.$answer.'<br />';;
                   4677:             } 
                   4678:         }
1.581     albertel 4679:     } else {
                   4680: 	$value = &unescape($value);
                   4681:     }
                   4682:     return $value;
                   4683: }
                   4684: 
                   4685: 
1.107     albertel 4686: sub relative_to_absolute {
                   4687:     my ($url,$output)=@_;
                   4688:     my $parser=HTML::TokeParser->new(\$output);
                   4689:     my $token;
                   4690:     my $thisdir=$url;
                   4691:     my @rlinks=();
                   4692:     while ($token=$parser->get_token) {
                   4693: 	if ($token->[0] eq 'S') {
                   4694: 	    if ($token->[1] eq 'a') {
                   4695: 		if ($token->[2]->{'href'}) {
                   4696: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4697: 		}
                   4698: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4699: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4700: 	    } elsif ($token->[1] eq 'base') {
                   4701: 		$thisdir=$token->[2]->{'href'};
                   4702: 	    }
                   4703: 	}
                   4704:     }
                   4705:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4706:     foreach my $link (@rlinks) {
1.726     raeburn  4707: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4708: 		($link=~/^\//) ||
                   4709: 		($link=~/^javascript:/i) ||
                   4710: 		($link=~/^mailto:/i) ||
                   4711: 		($link=~/^\#/)) {
                   4712: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4713: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4714: 	}
                   4715:     }
                   4716: # -------------------------------------------------- Deal with Applet codebases
                   4717:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4718:     return $output;
                   4719: }
                   4720: 
1.112     bowersj2 4721: =pod
                   4722: 
1.648     raeburn  4723: =item * &get_student_view()
1.112     bowersj2 4724: 
                   4725: show a snapshot of what student was looking at
                   4726: 
                   4727: =cut
                   4728: 
1.10      albertel 4729: sub get_student_view {
1.186     albertel 4730:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4731:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4732:   my (%form);
1.10      albertel 4733:   my @elements=('symb','courseid','domain','username');
                   4734:   foreach my $element (@elements) {
1.186     albertel 4735:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4736:   }
1.186     albertel 4737:   if (defined($moreenv)) {
                   4738:       %form=(%form,%{$moreenv});
                   4739:   }
1.236     albertel 4740:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4741:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4742:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4743:   $userview=~s/\<body[^\>]*\>//gi;
                   4744:   $userview=~s/\<\/body\>//gi;
                   4745:   $userview=~s/\<html\>//gi;
                   4746:   $userview=~s/\<\/html\>//gi;
                   4747:   $userview=~s/\<head\>//gi;
                   4748:   $userview=~s/\<\/head\>//gi;
                   4749:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4750:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4751:   if (wantarray) {
                   4752:      return ($userview,$response);
                   4753:   } else {
                   4754:      return $userview;
                   4755:   }
                   4756: }
                   4757: 
                   4758: sub get_student_view_with_retries {
                   4759:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4760: 
                   4761:     my $ok = 0;                 # True if we got a good response.
                   4762:     my $content;
                   4763:     my $response;
                   4764: 
                   4765:     # Try to get the student_view done. within the retries count:
                   4766:     
                   4767:     do {
                   4768:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4769:          $ok      = $response->is_success;
                   4770:          if (!$ok) {
                   4771:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4772:          }
                   4773:          $retries--;
                   4774:     } while (!$ok && ($retries > 0));
                   4775:     
                   4776:     if (!$ok) {
                   4777:        $content = '';          # On error return an empty content.
                   4778:     }
1.651     www      4779:     if (wantarray) {
                   4780:        return ($content, $response);
                   4781:     } else {
                   4782:        return $content;
                   4783:     }
1.11      albertel 4784: }
                   4785: 
1.1075.2.149  raeburn  4786: sub css_links {
                   4787:     my ($currsymb,$level) = @_;
                   4788:     my ($links,@symbs,%cssrefs,%httpref);
                   4789:     if ($level eq 'map') {
                   4790:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4791:         if (ref($navmap)) {
                   4792:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4793:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4794:             foreach my $res (@resources) {
                   4795:                 if (ref($res) && $res->symb()) {
                   4796:                     push(@symbs,$res->symb());
                   4797:                 }
                   4798:             }
                   4799:         }
                   4800:     } else {
                   4801:         @symbs = ($currsymb);
                   4802:     }
                   4803:     foreach my $symb (@symbs) {
                   4804:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4805:         if ($css_href =~ /\S/) {
                   4806:             unless ($css_href =~ m{https?://}) {
                   4807:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4808:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4809:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4810:                 unless ($css_href =~ m{^/}) {
                   4811:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4812:                 }
                   4813:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4814:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4815:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4816:                         my $thisurl = $proburl;
                   4817:                         if ($env{'httpref.'.$proburl}) {
                   4818:                             $thisurl = $env{'httpref.'.$proburl};
                   4819:                         }
                   4820:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4821:                     }
                   4822:                 }
                   4823:             }
                   4824:             $cssrefs{$css_href} = 1;
                   4825:         }
                   4826:     }
                   4827:     if (keys(%httpref)) {
                   4828:         &Apache::lonnet::appenv(\%httpref);
                   4829:     }
                   4830:     if (keys(%cssrefs)) {
                   4831:         foreach my $css_href (keys(%cssrefs)) {
                   4832:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4833:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4834:         }
                   4835:     }
                   4836:     return $links;
                   4837: }
                   4838: 
1.112     bowersj2 4839: =pod
                   4840: 
1.648     raeburn  4841: =item * &get_student_answers() 
1.112     bowersj2 4842: 
                   4843: show a snapshot of how student was answering problem
                   4844: 
                   4845: =cut
                   4846: 
1.11      albertel 4847: sub get_student_answers {
1.100     sakharuk 4848:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4849:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4850:   my (%moreenv);
1.11      albertel 4851:   my @elements=('symb','courseid','domain','username');
                   4852:   foreach my $element (@elements) {
1.186     albertel 4853:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4854:   }
1.186     albertel 4855:   $moreenv{'grade_target'}='answer';
                   4856:   %moreenv=(%form,%moreenv);
1.497     raeburn  4857:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4858:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4859:   return $userview;
1.1       albertel 4860: }
1.116     albertel 4861: 
                   4862: =pod
                   4863: 
                   4864: =item * &submlink()
                   4865: 
1.242     albertel 4866: Inputs: $text $uname $udom $symb $target
1.116     albertel 4867: 
                   4868: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4869: 
                   4870: =cut
                   4871: 
                   4872: ###############################################
                   4873: sub submlink {
1.242     albertel 4874:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4875:     if (!($uname && $udom)) {
                   4876: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4877: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4878: 	if (!$symb) { $symb=$cursymb; }
                   4879:     }
1.254     matthew  4880:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4881:     $symb=&escape($symb);
1.960     bisitz   4882:     if ($target) { $target=" target=\"$target\""; }
                   4883:     return
                   4884:         '<a href="/adm/grades?command=submission'.
                   4885:         '&amp;symb='.$symb.
                   4886:         '&amp;student='.$uname.
                   4887:         '&amp;userdom='.$udom.'"'.
                   4888:         $target.'>'.$text.'</a>';
1.242     albertel 4889: }
                   4890: ##############################################
                   4891: 
                   4892: =pod
                   4893: 
                   4894: =item * &pgrdlink()
                   4895: 
                   4896: Inputs: $text $uname $udom $symb $target
                   4897: 
                   4898: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4899: 
                   4900: =cut
                   4901: 
                   4902: ###############################################
                   4903: sub pgrdlink {
                   4904:     my $link=&submlink(@_);
                   4905:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4906:     return $link;
                   4907: }
                   4908: ##############################################
                   4909: 
                   4910: =pod
                   4911: 
                   4912: =item * &pprmlink()
                   4913: 
                   4914: Inputs: $text $uname $udom $symb $target
                   4915: 
                   4916: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4917: student and a specific resource
1.242     albertel 4918: 
                   4919: =cut
                   4920: 
                   4921: ###############################################
                   4922: sub pprmlink {
                   4923:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4924:     if (!($uname && $udom)) {
                   4925: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4926: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4927: 	if (!$symb) { $symb=$cursymb; }
                   4928:     }
1.254     matthew  4929:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4930:     $symb=&escape($symb);
1.242     albertel 4931:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4932:     return '<a href="/adm/parmset?command=set&amp;'.
                   4933: 	'symb='.$symb.'&amp;uname='.$uname.
                   4934: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4935: }
                   4936: ##############################################
1.37      matthew  4937: 
1.112     bowersj2 4938: =pod
                   4939: 
                   4940: =back
                   4941: 
                   4942: =cut
                   4943: 
1.37      matthew  4944: ###############################################
1.51      www      4945: 
                   4946: 
                   4947: sub timehash {
1.687     raeburn  4948:     my ($thistime) = @_;
                   4949:     my $timezone = &Apache::lonlocal::gettimezone();
                   4950:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4951:                      ->set_time_zone($timezone);
                   4952:     my $wday = $dt->day_of_week();
                   4953:     if ($wday == 7) { $wday = 0; }
                   4954:     return ( 'second' => $dt->second(),
                   4955:              'minute' => $dt->minute(),
                   4956:              'hour'   => $dt->hour(),
                   4957:              'day'     => $dt->day_of_month(),
                   4958:              'month'   => $dt->month(),
                   4959:              'year'    => $dt->year(),
                   4960:              'weekday' => $wday,
                   4961:              'dayyear' => $dt->day_of_year(),
                   4962:              'dlsav'   => $dt->is_dst() );
1.51      www      4963: }
                   4964: 
1.370     www      4965: sub utc_string {
                   4966:     my ($date)=@_;
1.371     www      4967:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4968: }
                   4969: 
1.51      www      4970: sub maketime {
                   4971:     my %th=@_;
1.687     raeburn  4972:     my ($epoch_time,$timezone,$dt);
                   4973:     $timezone = &Apache::lonlocal::gettimezone();
                   4974:     eval {
                   4975:         $dt = DateTime->new( year   => $th{'year'},
                   4976:                              month  => $th{'month'},
                   4977:                              day    => $th{'day'},
                   4978:                              hour   => $th{'hour'},
                   4979:                              minute => $th{'minute'},
                   4980:                              second => $th{'second'},
                   4981:                              time_zone => $timezone,
                   4982:                          );
                   4983:     };
                   4984:     if (!$@) {
                   4985:         $epoch_time = $dt->epoch;
                   4986:         if ($epoch_time) {
                   4987:             return $epoch_time;
                   4988:         }
                   4989:     }
1.51      www      4990:     return POSIX::mktime(
                   4991:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4992:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4993: }
                   4994: 
                   4995: #########################################
1.51      www      4996: 
                   4997: sub findallcourses {
1.482     raeburn  4998:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4999:     my %roles;
                   5000:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5001:     my %courses;
1.51      www      5002:     my $now=time;
1.482     raeburn  5003:     if (!defined($uname)) {
                   5004:         $uname = $env{'user.name'};
                   5005:     }
                   5006:     if (!defined($udom)) {
                   5007:         $udom = $env{'user.domain'};
                   5008:     }
                   5009:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5010:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5011:         if (!%roles) {
                   5012:             %roles = (
                   5013:                        cc => 1,
1.907     raeburn  5014:                        co => 1,
1.482     raeburn  5015:                        in => 1,
                   5016:                        ep => 1,
                   5017:                        ta => 1,
                   5018:                        cr => 1,
                   5019:                        st => 1,
                   5020:              );
                   5021:         }
                   5022:         foreach my $entry (keys(%roleshash)) {
                   5023:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5024:             if ($trole =~ /^cr/) { 
                   5025:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5026:             } else {
                   5027:                 next if (!exists($roles{$trole}));
                   5028:             }
                   5029:             if ($tend) {
                   5030:                 next if ($tend < $now);
                   5031:             }
                   5032:             if ($tstart) {
                   5033:                 next if ($tstart > $now);
                   5034:             }
1.1058    raeburn  5035:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5036:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5037:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5038:             if ($secpart eq '') {
                   5039:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5040:                 $sec = 'none';
1.1058    raeburn  5041:                 $value .= $cnum.'/';
1.482     raeburn  5042:             } else {
                   5043:                 $cnum = $cnumpart;
                   5044:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5045:                 $value .= $cnum.'/'.$sec;
                   5046:             }
                   5047:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5048:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5049:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5050:                 }
                   5051:             } else {
                   5052:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5053:             }
1.482     raeburn  5054:         }
                   5055:     } else {
                   5056:         foreach my $key (keys(%env)) {
1.483     albertel 5057: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5058:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5059: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5060: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5061: 	        next if (%roles && !exists($roles{$role}));
                   5062: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5063:                 my $active=1;
                   5064:                 if ($starttime) {
                   5065: 		    if ($now<$starttime) { $active=0; }
                   5066:                 }
                   5067:                 if ($endtime) {
                   5068:                     if ($now>$endtime) { $active=0; }
                   5069:                 }
                   5070:                 if ($active) {
1.1058    raeburn  5071:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5072:                     if ($sec eq '') {
                   5073:                         $sec = 'none';
1.1058    raeburn  5074:                     } else {
                   5075:                         $value .= $sec;
                   5076:                     }
                   5077:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5078:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5079:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5080:                         }
                   5081:                     } else {
                   5082:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5083:                     }
1.474     raeburn  5084:                 }
                   5085:             }
1.51      www      5086:         }
                   5087:     }
1.474     raeburn  5088:     return %courses;
1.51      www      5089: }
1.37      matthew  5090: 
1.54      www      5091: ###############################################
1.474     raeburn  5092: 
                   5093: sub blockcheck {
1.1075.2.158  raeburn  5094:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  5095: 
1.1075.2.161.  .4(raebu 5096:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  5097:         my ($has_evb,$check_ipaccess);
                   5098:         my $dom = $env{'user.domain'};
                   5099:         if ($env{'request.course.id'}) {
                   5100:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5101:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5102:             my $checkrole = "cm./$cdom/$cnum";
                   5103:             my $sec = $env{'request.course.sec'};
                   5104:             if ($sec ne '') {
                   5105:                 $checkrole .= "/$sec";
                   5106:             }
                   5107:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5108:                 ($env{'request.role'} !~ /^st/)) {
                   5109:                 $has_evb = 1;
                   5110:             }
                   5111:             unless ($has_evb) {
                   5112:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5113:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5114:                     if ($udom eq $cdom) {
                   5115:                         $check_ipaccess = 1;
                   5116:                     }
                   5117:                 }
                   5118:             }
1.1075.2.161.  .3(raebu 5119:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5120:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5121:22):             my $checkrole;
                   5122:22):             if ($env{'request.role.domain'} eq '') {
                   5123:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   5124:22):             } else {
                   5125:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5126:22):             }
                   5127:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5128:22):                 $has_evb = 1;
                   5129:22):             }
1.1075.2.158  raeburn  5130:         }
                   5131:         unless ($has_evb || $check_ipaccess) {
                   5132:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5133:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5134:                 $dom = $udom;
                   5135:             }
                   5136:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5137:                 $check_ipaccess = 1;
                   5138:             } else {
                   5139:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5140:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5141:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5142:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5143:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5144:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5145:                         $check_ipaccess = 1;
                   5146:                     }
                   5147:                 }
                   5148:             }
                   5149:         }
                   5150:         if ($check_ipaccess) {
                   5151:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5152:             unless (defined($cached)) {
                   5153:                 my %domconfig =
                   5154:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5155:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5156:             }
                   5157:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5158:                 foreach my $id (keys(%{$ipaccessref})) {
                   5159:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5160:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5161:                         if ($range) {
                   5162:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5163:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5164:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5165:                                         return ('','','',$id,$dom);
                   5166:                                         last;
                   5167:                                     }
                   5168:                                 }
                   5169:                             }
                   5170:                         }
                   5171:                     }
                   5172:                 }
                   5173:             }
                   5174:         }
1.1075.2.161.  .4(raebu 5175:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5176:22):             return ();
                   5177:22):         }
1.1075.2.158  raeburn  5178:     }
1.1075.2.73  raeburn  5179:     if (defined($udom) && defined($uname)) {
                   5180:         # If uname and udom are for a course, check for blocks in the course.
                   5181:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5182:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5183:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5184:             return ($startblock,$endblock,$triggerblock);
                   5185:         }
                   5186:     } else {
1.490     raeburn  5187:         $udom = $env{'user.domain'};
                   5188:         $uname = $env{'user.name'};
                   5189:     }
                   5190: 
1.502     raeburn  5191:     my $startblock = 0;
                   5192:     my $endblock = 0;
1.1062    raeburn  5193:     my $triggerblock = '';
1.1075.2.160  raeburn  5194:     my %live_courses;
                   5195:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5196:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5197:     }
1.474     raeburn  5198: 
1.490     raeburn  5199:     # If uname is for a user, and activity is course-specific, i.e.,
                   5200:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5201: 
1.490     raeburn  5202:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5203:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5204:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5205:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5206:         foreach my $key (keys(%live_courses)) {
                   5207:             if ($key ne $env{'request.course.id'}) {
                   5208:                 delete($live_courses{$key});
                   5209:             }
                   5210:         }
                   5211:     }
                   5212: 
                   5213:     my $otheruser = 0;
                   5214:     my %own_courses;
                   5215:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5216:         # Resource belongs to user other than current user.
                   5217:         $otheruser = 1;
                   5218:         # Gather courses for current user
                   5219:         %own_courses = 
                   5220:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5221:     }
                   5222: 
                   5223:     # Gather active course roles - course coordinator, instructor, 
                   5224:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5225: 
                   5226:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5227:         my ($cdom,$cnum);
                   5228:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5229:             $cdom = $env{'course.'.$course.'.domain'};
                   5230:             $cnum = $env{'course.'.$course.'.num'};
                   5231:         } else {
1.490     raeburn  5232:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5233:         }
                   5234:         my $no_ownblock = 0;
                   5235:         my $no_userblock = 0;
1.533     raeburn  5236:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5237:             # Check if current user has 'evb' priv for this
                   5238:             if (defined($own_courses{$course})) {
                   5239:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5240:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5241:                     if ($sec ne 'none') {
                   5242:                         $checkrole .= '/'.$sec;
                   5243:                     }
                   5244:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5245:                         $no_ownblock = 1;
                   5246:                         last;
                   5247:                     }
                   5248:                 }
                   5249:             }
                   5250:             # if they have 'evb' priv and are currently not playing student
                   5251:             next if (($no_ownblock) &&
                   5252:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5253:         }
1.474     raeburn  5254:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5255:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5256:             if ($sec ne 'none') {
1.482     raeburn  5257:                 $checkrole .= '/'.$sec;
1.474     raeburn  5258:             }
1.490     raeburn  5259:             if ($otheruser) {
                   5260:                 # Resource belongs to user other than current user.
                   5261:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5262:                 my (%allroles,%userroles);
                   5263:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5264:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5265:                         my ($trole,$tdom,$tnum,$tsec);
                   5266:                         if ($entry =~ /^cr/) {
                   5267:                             ($trole,$tdom,$tnum,$tsec) = 
                   5268:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5269:                         } else {
                   5270:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5271:                         }
                   5272:                         my ($spec,$area,$trest);
                   5273:                         $area = '/'.$tdom.'/'.$tnum;
                   5274:                         $trest = $tnum;
                   5275:                         if ($tsec ne '') {
                   5276:                             $area .= '/'.$tsec;
                   5277:                             $trest .= '/'.$tsec;
                   5278:                         }
                   5279:                         $spec = $trole.'.'.$area;
                   5280:                         if ($trole =~ /^cr/) {
                   5281:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5282:                                                               $tdom,$spec,$trest,$area);
                   5283:                         } else {
                   5284:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5285:                                                                 $tdom,$spec,$trest,$area);
                   5286:                         }
                   5287:                     }
1.1075.2.124  raeburn  5288:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5289:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5290:                         if ($1) {
                   5291:                             $no_userblock = 1;
                   5292:                             last;
                   5293:                         }
1.486     raeburn  5294:                     }
                   5295:                 }
1.490     raeburn  5296:             } else {
                   5297:                 # Resource belongs to current user
                   5298:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5299:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5300:                     $no_ownblock = 1;
                   5301:                     last;
                   5302:                 }
1.474     raeburn  5303:             }
                   5304:         }
                   5305:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5306:         next if (($no_ownblock) &&
1.491     albertel 5307:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5308:         next if ($no_userblock);
1.474     raeburn  5309: 
1.1075.2.128  raeburn  5310:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5311:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5312:         
1.1062    raeburn  5313:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5314:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5315:         if (($start != 0) && 
                   5316:             (($startblock == 0) || ($startblock > $start))) {
                   5317:             $startblock = $start;
1.1062    raeburn  5318:             if ($trigger ne '') {
                   5319:                 $triggerblock = $trigger;
                   5320:             }
1.502     raeburn  5321:         }
                   5322:         if (($end != 0)  &&
                   5323:             (($endblock == 0) || ($endblock < $end))) {
                   5324:             $endblock = $end;
1.1062    raeburn  5325:             if ($trigger ne '') {
                   5326:                 $triggerblock = $trigger;
                   5327:             }
1.502     raeburn  5328:         }
1.490     raeburn  5329:     }
1.1062    raeburn  5330:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5331: }
                   5332: 
                   5333: sub get_blocks {
1.1075.2.147  raeburn  5334:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5335:     my $startblock = 0;
                   5336:     my $endblock = 0;
1.1062    raeburn  5337:     my $triggerblock = '';
1.490     raeburn  5338:     my $course = $cdom.'_'.$cnum;
                   5339:     $setters->{$course} = {};
                   5340:     $setters->{$course}{'staff'} = [];
                   5341:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5342:     $setters->{$course}{'triggers'} = [];
                   5343:     my (@blockers,%triggered);
                   5344:     my $now = time;
                   5345:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5346:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5347:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5348:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5349:             $blocked = 1;
                   5350:             $nosymbcache = 1;
1.1075.2.148  raeburn  5351:             $noenccheck = 1;
1.1075.2.147  raeburn  5352:         }
1.1075.2.148  raeburn  5353:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5354:         foreach my $block (@blockers) {
                   5355:             if ($block =~ /^firstaccess____(.+)$/) {
                   5356:                 my $item = $1;
                   5357:                 my $type = 'map';
                   5358:                 my $timersymb = $item;
                   5359:                 if ($item eq 'course') {
                   5360:                     $type = 'course';
                   5361:                 } elsif ($item =~ /___\d+___/) {
                   5362:                     $type = 'resource';
                   5363:                 } else {
                   5364:                     $timersymb = &Apache::lonnet::symbread($item);
                   5365:                 }
                   5366:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5367:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5368:                 $triggered{$block} = {
                   5369:                                        start => $start,
                   5370:                                        end   => $end,
                   5371:                                        type  => $type,
                   5372:                                      };
                   5373:             }
                   5374:         }
                   5375:     } else {
                   5376:         foreach my $block (keys(%commblocks)) {
                   5377:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5378:                 my ($start,$end) = ($1,$2);
                   5379:                 if ($start <= time && $end >= time) {
                   5380:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5381:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5382:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5383:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5384:                                     push(@blockers,$block);
                   5385:                                 }
                   5386:                             }
                   5387:                         }
                   5388:                     }
                   5389:                 }
                   5390:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5391:                 my $item = $1;
                   5392:                 my $timersymb = $item; 
                   5393:                 my $type = 'map';
                   5394:                 if ($item eq 'course') {
                   5395:                     $type = 'course';
                   5396:                 } elsif ($item =~ /___\d+___/) {
                   5397:                     $type = 'resource';
                   5398:                 } else {
                   5399:                     $timersymb = &Apache::lonnet::symbread($item);
                   5400:                 }
                   5401:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5402:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5403:                 if ($start && $end) {
                   5404:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5405:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5406:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5407:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5408:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5409:                                         push(@blockers,$block);
                   5410:                                         $triggered{$block} = {
                   5411:                                                                start => $start,
                   5412:                                                                end   => $end,
                   5413:                                                                type  => $type,
                   5414:                                                              };
                   5415:                                     }
                   5416:                                 }
                   5417:                             }
1.1062    raeburn  5418:                         }
                   5419:                     }
1.490     raeburn  5420:                 }
1.1062    raeburn  5421:             }
                   5422:         }
                   5423:     }
                   5424:     foreach my $blocker (@blockers) {
                   5425:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5426:             &parse_block_record($commblocks{$blocker});
                   5427:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5428:         my ($start,$end,$triggertype);
                   5429:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5430:             ($start,$end) = ($1,$2);
                   5431:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5432:             $start = $triggered{$blocker}{'start'};
                   5433:             $end = $triggered{$blocker}{'end'};
                   5434:             $triggertype = $triggered{$blocker}{'type'};
                   5435:         }
                   5436:         if ($start) {
                   5437:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5438:             if ($triggertype) {
                   5439:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5440:             } else {
                   5441:                 push(@{$$setters{$course}{'triggers'}},0);
                   5442:             }
                   5443:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5444:                 $startblock = $start;
                   5445:                 if ($triggertype) {
                   5446:                     $triggerblock = $blocker;
1.474     raeburn  5447:                 }
                   5448:             }
1.1062    raeburn  5449:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5450:                $endblock = $end;
                   5451:                if ($triggertype) {
                   5452:                    $triggerblock = $blocker;
                   5453:                }
                   5454:             }
1.474     raeburn  5455:         }
                   5456:     }
1.1062    raeburn  5457:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5458: }
                   5459: 
                   5460: sub parse_block_record {
                   5461:     my ($record) = @_;
                   5462:     my ($setuname,$setudom,$title,$blocks);
                   5463:     if (ref($record) eq 'HASH') {
                   5464:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5465:         $title = &unescape($record->{'event'});
                   5466:         $blocks = $record->{'blocks'};
                   5467:     } else {
                   5468:         my @data = split(/:/,$record,3);
                   5469:         if (scalar(@data) eq 2) {
                   5470:             $title = $data[1];
                   5471:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5472:         } else {
                   5473:             ($setuname,$setudom,$title) = @data;
                   5474:         }
                   5475:         $blocks = { 'com' => 'on' };
                   5476:     }
                   5477:     return ($setuname,$setudom,$title,$blocks);
                   5478: }
                   5479: 
1.854     kalberla 5480: sub blocking_status {
1.1075.2.158  raeburn  5481:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5482:     my %setters;
1.890     droeschl 5483: 
1.1061    raeburn  5484: # check for active blocking
1.1075.2.158  raeburn  5485:     if ($clientip eq '') {
                   5486:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5487:     }
                   5488:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5489:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5490:     my $blocked = 0;
1.1075.2.158  raeburn  5491:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5492:         $blocked = 1;
                   5493:     }
1.890     droeschl 5494: 
1.1061    raeburn  5495: # caller just wants to know whether a block is active
                   5496:     if (!wantarray) { return $blocked; }
                   5497: 
                   5498: # build a link to a popup window containing the details
                   5499:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5500: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5501:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5502:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5503:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5504:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5505:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5506:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5507:         if ($symb) {
                   5508:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5509:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5510:         }
1.1062    raeburn  5511:     }
1.1061    raeburn  5512: 
                   5513:     my $output .= <<'END_MYBLOCK';
                   5514: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5515:     var options = "width=" + w + ",height=" + h + ",";
                   5516:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5517:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5518:     var newWin = window.open(url, wdwName, options);
                   5519:     newWin.focus();
                   5520: }
1.890     droeschl 5521: END_MYBLOCK
1.854     kalberla 5522: 
1.1061    raeburn  5523:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5524:   
1.1061    raeburn  5525:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5526:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5527:     my $class = 'LC_comblock';
1.1062    raeburn  5528:     if ($activity eq 'docs') {
                   5529:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5530:         $class = '';
1.1063    raeburn  5531:     } elsif ($activity eq 'printout') {
                   5532:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5533:     } elsif ($activity eq 'passwd') {
                   5534:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5535:     } elsif ($activity eq 'grades') {
                   5536:         $text = &mt('Gradebook Blocked');
                   5537:     } elsif ($activity eq 'search') {
                   5538:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5539:21):     } elsif ($activity eq 'alert') {
                   5540:21):         $text = &mt('Checking Critical Messages Blocked');
                   5541:21):     } elsif ($activity eq 'reinit') {
                   5542:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5543:     } elsif ($activity eq 'about') {
                   5544:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5545:     } elsif ($activity eq 'wishlist') {
                   5546:         $text = &mt('Access to Stored Links Blocked');
                   5547:     } elsif ($activity eq 'annotate') {
                   5548:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5549:     }
1.1061    raeburn  5550:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5551: <div class='$class'>
1.869     kalberla 5552:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5553:   title='$text'>
                   5554:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5555:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5556:   title='$text'>$text</a>
1.867     kalberla 5557: </div>
                   5558: 
                   5559: END_BLOCK
1.474     raeburn  5560: 
1.1061    raeburn  5561:     return ($blocked, $output);
1.854     kalberla 5562: }
1.490     raeburn  5563: 
1.60      matthew  5564: ###############################################
                   5565: 
1.682     raeburn  5566: sub check_ip_acc {
1.1075.2.105  raeburn  5567:     my ($acc,$clientip)=@_;
1.682     raeburn  5568:     &Apache::lonxml::debug("acc is $acc");
                   5569:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5570:         return 1;
                   5571:     }
                   5572:     my $allowed=0;
1.1075.2.144  raeburn  5573:     my $ip;
                   5574:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5575:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5576:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5577:     } else {
1.1075.2.150  raeburn  5578:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5579:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5580:     }
1.682     raeburn  5581: 
                   5582:     my $name;
1.1075.2.161.  .1(raebu 5583:21):     my %access = (
                   5584:21):                      allowfrom => 1,
                   5585:21):                      denyfrom  => 0,
                   5586:21):                  );
                   5587:21):     my @allows;
                   5588:21):     my @denies;
                   5589:21):     foreach my $item (split(',',$acc)) {
                   5590:21):         $item =~ s/^\s*//;
                   5591:21):         $item =~ s/\s*$//;
                   5592:21):         if ($item =~ /^\!(.+)$/) {
                   5593:21):             push(@denies,$1);
                   5594:21):         } else {
                   5595:21):             push(@allows,$item);
                   5596:21):         }
                   5597:21):     }
                   5598:21):     my $numdenies = scalar(@denies);
                   5599:21):     my $numallows = scalar(@allows);
                   5600:21):     my $count = 0;
                   5601:21):     foreach my $pattern (@denies,@allows) {
                   5602:21):         $count ++;
                   5603:21):         my $acctype = 'allowfrom';
                   5604:21):         if ($count <= $numdenies) {
                   5605:21):             $acctype = 'denyfrom';
                   5606:21):         }
1.682     raeburn  5607:         if ($pattern =~ /\*$/) {
                   5608:             #35.8.*
                   5609:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5610:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5611:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5612:             #35.8.3.[34-56]
                   5613:             my $low=$2;
                   5614:             my $high=$3;
                   5615:             $pattern=$1;
                   5616:             if ($ip =~ /^\Q$pattern\E/) {
                   5617:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5618:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5619:             }
                   5620:         } elsif ($pattern =~ /^\*/) {
                   5621:             #*.msu.edu
                   5622:             $pattern=~s/\*//;
                   5623:             if (!defined($name)) {
                   5624:                 use Socket;
                   5625:                 my $netaddr=inet_aton($ip);
                   5626:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5627:             }
1.1075.2.161.  .1(raebu 5628:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5629:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5630:             #127.0.0.1
1.1075.2.161.  .1(raebu 5631:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5632:         } else {
                   5633:             #some.name.com
                   5634:             if (!defined($name)) {
                   5635:                 use Socket;
                   5636:                 my $netaddr=inet_aton($ip);
                   5637:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5638:             }
1.1075.2.161.  .1(raebu 5639:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5640:21):         }
                   5641:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5642:21):     }
                   5643:21):     if ($allowed eq '') {
                   5644:21):         if ($numdenies && !$numallows) {
                   5645:21):             $allowed = 1;
                   5646:21):         } else {
                   5647:21):             $allowed = 0;
1.682     raeburn  5648:         }
                   5649:     }
                   5650:     return $allowed;
                   5651: }
                   5652: 
                   5653: ###############################################
                   5654: 
1.60      matthew  5655: =pod
                   5656: 
1.112     bowersj2 5657: =head1 Domain Template Functions
                   5658: 
                   5659: =over 4
                   5660: 
                   5661: =item * &determinedomain()
1.60      matthew  5662: 
                   5663: Inputs: $domain (usually will be undef)
                   5664: 
1.63      www      5665: Returns: Determines which domain should be used for designs
1.60      matthew  5666: 
                   5667: =cut
1.54      www      5668: 
1.60      matthew  5669: ###############################################
1.63      www      5670: sub determinedomain {
                   5671:     my $domain=shift;
1.531     albertel 5672:     if (! $domain) {
1.60      matthew  5673:         # Determine domain if we have not been given one
1.893     raeburn  5674:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5675:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5676:         if ($env{'request.role.domain'}) { 
                   5677:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5678:         }
                   5679:     }
1.63      www      5680:     return $domain;
                   5681: }
                   5682: ###############################################
1.517     raeburn  5683: 
1.518     albertel 5684: sub devalidate_domconfig_cache {
                   5685:     my ($udom)=@_;
                   5686:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5687: }
                   5688: 
                   5689: # ---------------------- Get domain configuration for a domain
                   5690: sub get_domainconf {
                   5691:     my ($udom) = @_;
                   5692:     my $cachetime=1800;
                   5693:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5694:     if (defined($cached)) { return %{$result}; }
                   5695: 
                   5696:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5697: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5698:     my (%designhash,%legacy);
1.518     albertel 5699:     if (keys(%domconfig) > 0) {
                   5700:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5701:             if (keys(%{$domconfig{'login'}})) {
                   5702:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5703:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5704:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5705:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5706:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5707:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5708:                                         if ($key eq 'loginvia') {
                   5709:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5710:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5711:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5712:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5713:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5714:                                                 } else {
                   5715:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5716:                                                 }
1.948     raeburn  5717:                                             }
1.1075.2.87  raeburn  5718:                                         } elsif ($key eq 'headtag') {
                   5719:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5720:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5721:                                             }
1.946     raeburn  5722:                                         }
1.1075.2.87  raeburn  5723:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5724:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5725:                                         }
1.946     raeburn  5726:                                     }
                   5727:                                 }
                   5728:                             }
1.1075.2.158  raeburn  5729:                         } elsif ($key eq 'saml') {
                   5730:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5731:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5732:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5733:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5734:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5735:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5736:                                         }
                   5737:                                     }
                   5738:                                 }
                   5739:                             }
1.946     raeburn  5740:                         } else {
                   5741:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5742:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5743:                                     $domconfig{'login'}{$key}{$img};
                   5744:                             }
1.699     raeburn  5745:                         }
                   5746:                     } else {
                   5747:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5748:                     }
1.632     raeburn  5749:                 }
                   5750:             } else {
                   5751:                 $legacy{'login'} = 1;
1.518     albertel 5752:             }
1.632     raeburn  5753:         } else {
                   5754:             $legacy{'login'} = 1;
1.518     albertel 5755:         }
                   5756:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5757:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5758:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5759:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5760:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5761:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5762:                         }
1.518     albertel 5763:                     }
                   5764:                 }
1.632     raeburn  5765:             } else {
                   5766:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5767:             }
1.632     raeburn  5768:         } else {
                   5769:             $legacy{'rolecolors'} = 1;
1.518     albertel 5770:         }
1.948     raeburn  5771:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5772:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5773:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5774:             }
                   5775:         }
1.632     raeburn  5776:         if (keys(%legacy) > 0) {
                   5777:             my %legacyhash = &get_legacy_domconf($udom);
                   5778:             foreach my $item (keys(%legacyhash)) {
                   5779:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5780:                     if ($legacy{'login'}) { 
                   5781:                         $designhash{$item} = $legacyhash{$item};
                   5782:                     }
                   5783:                 } else {
                   5784:                     if ($legacy{'rolecolors'}) {
                   5785:                         $designhash{$item} = $legacyhash{$item};
                   5786:                     }
1.518     albertel 5787:                 }
                   5788:             }
                   5789:         }
1.632     raeburn  5790:     } else {
                   5791:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5792:     }
                   5793:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5794: 				  $cachetime);
                   5795:     return %designhash;
                   5796: }
                   5797: 
1.632     raeburn  5798: sub get_legacy_domconf {
                   5799:     my ($udom) = @_;
                   5800:     my %legacyhash;
                   5801:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5802:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5803:     if (-e $designfile) {
1.1075.2.128  raeburn  5804:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5805:             while (my $line = <$fh>) {
                   5806:                 next if ($line =~ /^\#/);
                   5807:                 chomp($line);
                   5808:                 my ($key,$val)=(split(/\=/,$line));
                   5809:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5810:             }
                   5811:             close($fh);
                   5812:         }
                   5813:     }
1.1026    raeburn  5814:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5815:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5816:     }
                   5817:     return %legacyhash;
                   5818: }
                   5819: 
1.63      www      5820: =pod
                   5821: 
1.112     bowersj2 5822: =item * &domainlogo()
1.63      www      5823: 
                   5824: Inputs: $domain (usually will be undef)
                   5825: 
                   5826: Returns: A link to a domain logo, if the domain logo exists.
                   5827: If the domain logo does not exist, a description of the domain.
                   5828: 
                   5829: =cut
1.112     bowersj2 5830: 
1.63      www      5831: ###############################################
                   5832: sub domainlogo {
1.517     raeburn  5833:     my $domain = &determinedomain(shift);
1.518     albertel 5834:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5835:     # See if there is a logo
                   5836:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5837:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5838:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5839: 	    if ($imgsrc =~ m{^/res/}) {
                   5840: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5841: 		&Apache::lonnet::repcopy($local_name);
                   5842: 	    }
                   5843: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5844:22):         }
                   5845:22):         my $alttext = $domain;
                   5846:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5847:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5848:22):         }
                   5849:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5850:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5851:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5852:     } else {
1.60      matthew  5853:         return '';
1.59      www      5854:     }
                   5855: }
1.63      www      5856: ##############################################
                   5857: 
                   5858: =pod
                   5859: 
1.112     bowersj2 5860: =item * &designparm()
1.63      www      5861: 
                   5862: Inputs: $which parameter; $domain (usually will be undef)
                   5863: 
                   5864: Returns: value of designparamter $which
                   5865: 
                   5866: =cut
1.112     bowersj2 5867: 
1.397     albertel 5868: 
1.400     albertel 5869: ##############################################
1.397     albertel 5870: sub designparm {
                   5871:     my ($which,$domain)=@_;
                   5872:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5873:         return $env{'environment.color.'.$which};
1.96      www      5874:     }
1.63      www      5875:     $domain=&determinedomain($domain);
1.1016    raeburn  5876:     my %domdesign;
                   5877:     unless ($domain eq 'public') {
                   5878:         %domdesign = &get_domainconf($domain);
                   5879:     }
1.520     raeburn  5880:     my $output;
1.517     raeburn  5881:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5882:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5883:     } else {
1.520     raeburn  5884:         $output = $defaultdesign{$which};
                   5885:     }
                   5886:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5887:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5888:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5889:             if ($output =~ m{^/res/}) {
                   5890:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5891:                 &Apache::lonnet::repcopy($local_name);
                   5892:             }
1.520     raeburn  5893:             $output = &lonhttpdurl($output);
                   5894:         }
1.63      www      5895:     }
1.520     raeburn  5896:     return $output;
1.63      www      5897: }
1.59      www      5898: 
1.822     bisitz   5899: ##############################################
                   5900: =pod
                   5901: 
1.832     bisitz   5902: =item * &authorspace()
                   5903: 
1.1028    raeburn  5904: Inputs: $url (usually will be undef).
1.832     bisitz   5905: 
1.1075.2.40  raeburn  5906: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5907:          directory being viewed (or for which action is being taken). 
                   5908:          If $url is provided, and begins /priv/<domain>/<uname>
                   5909:          the path will be that portion of the $context argument.
                   5910:          Otherwise the path will be for the author space of the current
                   5911:          user when the current role is author, or for that of the 
                   5912:          co-author/assistant co-author space when the current role 
                   5913:          is co-author or assistant co-author.
1.832     bisitz   5914: 
                   5915: =cut
                   5916: 
                   5917: sub authorspace {
1.1028    raeburn  5918:     my ($url) = @_;
                   5919:     if ($url ne '') {
                   5920:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5921:            return $1;
                   5922:         }
                   5923:     }
1.832     bisitz   5924:     my $caname = '';
1.1024    www      5925:     my $cadom = '';
1.1028    raeburn  5926:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5927:         ($cadom,$caname) =
1.832     bisitz   5928:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5929:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5930:         $caname = $env{'user.name'};
1.1024    www      5931:         $cadom = $env{'user.domain'};
1.832     bisitz   5932:     }
1.1028    raeburn  5933:     if (($caname ne '') && ($cadom ne '')) {
                   5934:         return "/priv/$cadom/$caname/";
                   5935:     }
                   5936:     return;
1.832     bisitz   5937: }
                   5938: 
                   5939: ##############################################
                   5940: =pod
                   5941: 
1.822     bisitz   5942: =item * &head_subbox()
                   5943: 
                   5944: Inputs: $content (contains HTML code with page functions, etc.)
                   5945: 
                   5946: Returns: HTML div with $content
                   5947:          To be included in page header
                   5948: 
                   5949: =cut
                   5950: 
                   5951: sub head_subbox {
                   5952:     my ($content)=@_;
                   5953:     my $output =
1.993     raeburn  5954:         '<div class="LC_head_subbox">'
1.822     bisitz   5955:        .$content
                   5956:        .'</div>'
                   5957: }
                   5958: 
                   5959: ##############################################
                   5960: =pod
                   5961: 
                   5962: =item * &CSTR_pageheader()
                   5963: 
1.1026    raeburn  5964: Input: (optional) filename from which breadcrumb trail is built.
                   5965:        In most cases no input as needed, as $env{'request.filename'}
                   5966:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5967:22):        frameset flag
                   5968:22):        If page header is being requested for use in a frameset, then
                   5969:22):        the second (option) argument -- frameset will be true, and
                   5970:22):        the target attribute set for links should be target="_parent".
          .26(raeb 5971:-24):        If $title is supplied as the third arg, that will be used to
                   5972:-24):        the left of the breadcrumbs tail for the current path.
1.822     bisitz   5973: 
                   5974: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5975:          To be included on Authoring Space pages
1.822     bisitz   5976: 
                   5977: =cut
                   5978: 
                   5979: sub CSTR_pageheader {
1.1075.2.161.  .26(raeb 5980:-24):     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  5981:     if ($trailfile eq '') {
                   5982:         $trailfile = $env{'request.filename'};
                   5983:     }
                   5984: 
                   5985: # this is for resources; directories have customtitle, and crumbs
                   5986: # and select recent are created in lonpubdir.pm
                   5987: 
                   5988:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5989:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5990:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5991:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5992:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5993: 
                   5994:     my $parentpath = '';
                   5995:     my $lastitem = '';
                   5996:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5997:         $parentpath = $1;
                   5998:         $lastitem = $2;
                   5999:     } else {
                   6000:         $lastitem = $thisdisfn;
                   6001:     }
1.921     bisitz   6002: 
1.1075.2.161.  .26(raeb 6003:-24):     if ($title eq '') {
                   6004:-24):         $title = &mt('Authoring Space');
                   6005:-24):     }
                   6006:-24): 
          .6(raebu 6007:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6008:22):     if ($frameset) {
                   6009:22):         $target = ' target="_parent"';
                   6010:22):         $crumbtarget = '_parent';
          .17(raeb 6011:-23):     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   6012:-23):         $target = '';
                   6013:-23):         $crumbtarget = '';
          .6(raebu 6014:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   6015:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6016:22):         $crumbtarget = $env{'request.deeplink.target'};
                   6017:22):     }
                   6018:22): 
1.921     bisitz   6019:     my $output =
1.822     bisitz   6020:          '<div>'
                   6021:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.161.  .26(raeb 6022:-24):         .'<b>'.$title.'</b> '
          .6(raebu 6023:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6024:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6025: 
                   6026:     if ($lastitem) {
                   6027:         $output .=
                   6028:              '<span class="LC_filename">'
                   6029:             .$lastitem
                   6030:             .'</span>';
                   6031:     }
                   6032:     $output .=
                   6033:          '<br />'
1.1075.2.161.  .6(raebu 6034:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   6035:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6036:         .'</form>'
1.1075.2.161.  .6(raebu 6037:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   6038:         .'</div>';
1.921     bisitz   6039: 
                   6040:     return $output;
1.822     bisitz   6041: }
                   6042: 
1.1075.2.161.  .21(raeb 6043:-24): ##############################################
                   6044:-24): =pod
                   6045:-24): 
                   6046:-24): =item * &nocodemirror()
                   6047:-24): 
                   6048:-24): Input: None
                   6049:-24): 
                   6050:-24): Returns: 1 if CodeMirror is deactivated based on
                   6051:-24):          user's preference, or domain default,
                   6052:-24):          if user indicated use of default.
                   6053:-24): 
                   6054:-24): =cut
                   6055:-24): 
                   6056:-24): sub nocodemirror {
                   6057:-24):     my $nocodem = $env{'environment.nocodemirror'};
                   6058:-24):     unless ($nocodem) {
                   6059:-24):         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6060:-24):         if ($domdefs{'nocodemirror'}) {
                   6061:-24):             $nocodem = 'yes';
                   6062:-24):         }
                   6063:-24):     }
                   6064:-24):     if ($nocodem eq 'yes') {
                   6065:-24):         return 1;
                   6066:-24):     }
                   6067:-24):     return;
                   6068:-24): }
                   6069:-24): 
                   6070:-24): ##############################################
                   6071:-24): =pod
                   6072:-24): 
                   6073:-24): =item * &permitted_editors()
                   6074:-24): 
                   6075:-24): Input: $uri (optional)
                   6076:-24): 
                   6077:-24): Returns: %editors hash in which keys are editors
          .25(raeb 6078:-24):          permitted in current Authoring Space,
                   6079:-24):          or in current course for web pages
                   6080:-24):          created in a course.
                   6081:-24): 
          .21(raeb 6082:-24):          Value for each key is 1. Possible keys
          .25(raeb 6083:-24):          are: edit, xml, and daxe. 
                   6084:-24): 
                   6085:-24):          For a regular Authoring Space, if no specific
          .21(raeb 6086:-24):          set of editors has been set for the Author
                   6087:-24):          who owns the Authoring Space, then the
                   6088:-24):          domain default will be used.  If no domain
                   6089:-24):          default has been set, then the keys will be
                   6090:-24):          edit and xml.
                   6091:-24): 
          .25(raeb 6092:-24):          For a course author, or for web pages created
                   6093:-24):          in a course, if no specific set of editors has
                   6094:-24):          been set for the course, then the domain
                   6095:-24):          course default will be used. If no domain
                   6096:-24):          course default has been set, then the keys
                   6097:-24):          will be edit and xml.
                   6098:-24): 
          .21(raeb 6099:-24): =cut
                   6100:-24): 
                   6101:-24): sub permitted_editors {
                   6102:-24):     my ($uri) = @_;
          .25(raeb 6103:-24):     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
          .21(raeb 6104:-24):     if ($env{'request.role'} =~ m{^au\./}) {
                   6105:-24):         $is_author = 1;
                   6106:-24):     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6107:-24):         ($audom,$auname) = ($1,$2);
                   6108:-24):         if (($audom ne '') && ($auname ne '')) {
                   6109:-24):             if (($env{'user.domain'} eq $audom) &&
                   6110:-24):                 ($env{'user.name'} eq $auname)) {
                   6111:-24):                 $is_author = 1;
                   6112:-24):             } else {
                   6113:-24):                 $is_coauthor = 1;
                   6114:-24):             }
                   6115:-24):         }
                   6116:-24):     } elsif ($env{'request.course.id'}) {
          .25(raeb 6117:-24):         my ($cdom,$cnum);
                   6118:-24):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6119:-24):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6120:-24):         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
                   6121:-24):             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6122:-24):             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
                   6123:-24):             $is_course = 1;
                   6124:-24):         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
          .21(raeb 6125:-24):             ($audom,$auname) = ($1,$2);
                   6126:-24):         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6127:-24):             ($audom,$auname) = ($1,$2);
                   6128:-24):         } elsif (($uri eq '/daxesave') &&
          .25(raeb 6129:-24):                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6130:-24):                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6131:-24):             $is_course = 1;
                   6132:-24):         } elsif (($uri eq '/daxesave') &&
          .21(raeb 6133:-24):                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6134:-24):             ($audom,$auname) = ($1,$2);
                   6135:-24):         }
          .25(raeb 6136:-24):         unless ($is_course) {
                   6137:-24):             if (($audom ne '') && ($auname ne '')) {
                   6138:-24):                 if (($env{'user.domain'} eq $audom) &&
                   6139:-24):                     ($env{'user.name'} eq $auname)) {
                   6140:-24):                     $is_author = 1;
                   6141:-24):                 } else {
                   6142:-24):                     $is_coauthor = 1;
                   6143:-24):                 }
          .21(raeb 6144:-24):             }
                   6145:-24):         }
                   6146:-24):     }
                   6147:-24):     if ($is_author) {
                   6148:-24):         if (exists($env{'environment.editors'})) {
                   6149:-24):             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6150:-24):         } else {
                   6151:-24):             %editors = ( edit => 1,
                   6152:-24):                          xml => 1,
                   6153:-24):                        );
                   6154:-24):         }
                   6155:-24):     } elsif ($is_coauthor) {
                   6156:-24):         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6157:-24):             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6158:-24):         } else {
                   6159:-24):             %editors = ( edit => 1,
                   6160:-24):                          xml => 1,
                   6161:-24):                        );
                   6162:-24):         }
          .25(raeb 6163:-24):     } elsif ($is_course) {
                   6164:-24):         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6165:-24):             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6166:-24):         } else {
                   6167:-24):             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6168:-24):             if (exists($domdefaults{'crseditors'})) {
                   6169:-24):                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6170:-24):             } else {
                   6171:-24):                 %editors = ( edit => 1,
                   6172:-24):                              xml => 1,
                   6173:-24):                            );
                   6174:-24):             }
                   6175:-24):         }
          .21(raeb 6176:-24):     } else {
                   6177:-24):         %editors = ( edit => 1,
                   6178:-24):                      xml => 1,
                   6179:-24):                    );
                   6180:-24):     }
                   6181:-24):     return %editors;
                   6182:-24): }
                   6183:-24): 
1.60      matthew  6184: ###############################################
                   6185: ###############################################
                   6186: 
                   6187: =pod
                   6188: 
1.112     bowersj2 6189: =back
                   6190: 
1.549     albertel 6191: =head1 HTML Helpers
1.112     bowersj2 6192: 
                   6193: =over 4
                   6194: 
                   6195: =item * &bodytag()
1.60      matthew  6196: 
                   6197: Returns a uniform header for LON-CAPA web pages.
                   6198: 
                   6199: Inputs: 
                   6200: 
1.112     bowersj2 6201: =over 4
                   6202: 
                   6203: =item * $title, A title to be displayed on the page.
                   6204: 
                   6205: =item * $function, the current role (can be undef).
                   6206: 
                   6207: =item * $addentries, extra parameters for the <body> tag.
                   6208: 
                   6209: =item * $bodyonly, if defined, only return the <body> tag.
                   6210: 
                   6211: =item * $domain, if defined, force a given domain.
                   6212: 
                   6213: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6214:             text interface only)
1.60      matthew  6215: 
1.814     bisitz   6216: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6217:                      navigational links
1.317     albertel 6218: 
1.338     albertel 6219: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6220: 
1.1075.2.12  raeburn  6221: =item * $no_inline_link, if true and in remote mode, don't show the
                   6222:          'Switch To Inline Menu' link
                   6223: 
1.460     albertel 6224: =item * $args, optional argument valid values are
                   6225:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  6226:             use_absolute     -> for external resource or syllabus, this will
                   6227:                                 contain https://<hostname> if server uses
                   6228:                                 https (as per hosts.tab), but request is for http
                   6229:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6230: 
1.1075.2.15  raeburn  6231: =item * $advtoolsref, optional argument, ref to an array containing
                   6232:             inlineremote items to be added in "Functions" menu below
                   6233:             breadcrumbs.
                   6234: 
1.1075.2.161.  .1(raebu 6235:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   6236:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   6237:21):             the scope of use, i.e., launch was for access to a single, a map
                   6238:21):             or the entire course.
                   6239:21): 
                   6240:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6241:21):             context, this will contain the URL for the landing item in
                   6242:21):             the course, after launch from an LTI Consumer
                   6243:21): 
                   6244:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6245:21):             context, this will contain a reference to hash of items
                   6246:21):             to be included in the page header and/or inline menu.
                   6247:21): 
          .8(raebu 6248:22): =item * $menucoll, optional argument, if specific menu collection is in
                   6249:22):             effect, either set as the default for the course, or set for
                   6250:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   6251:22):             then $menucoll will be the number of that collection.
                   6252:22): 
                   6253:22): =item * $menuref, optional argument, reference to a hash, containing the
                   6254:22):             menu options included for the menu in effect, based on the
                   6255:22):             configuration for the numbered menu collection in use.
                   6256:22): 
                   6257:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6258:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6259:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   6260:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6261:22):             being called a second time.
                   6262:22): 
1.112     bowersj2 6263: =back
                   6264: 
1.60      matthew  6265: Returns: A uniform header for LON-CAPA web pages.  
                   6266: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6267: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6268: other decorations will be returned.
                   6269: 
                   6270: =cut
                   6271: 
1.54      www      6272: sub bodytag {
1.831     bisitz   6273:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 6274:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 6275:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6276: 
1.954     raeburn  6277:     my $public;
                   6278:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6279:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6280:         $public = 1;
                   6281:     }
1.460     albertel 6282:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  6283:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  6284:     my $hostname = $args->{'hostname'};
1.339     albertel 6285: 
1.183     matthew  6286:     $function = &get_users_function() if (!$function);
1.339     albertel 6287:     my $img =    &designparm($function.'.img',$domain);
                   6288:     my $font =   &designparm($function.'.font',$domain);
                   6289:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6290: 
1.803     bisitz   6291:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6292: 		   'bgcolor' => $pgbg,
1.339     albertel 6293: 		   'text'    => $font,
                   6294:                    'alink'   => &designparm($function.'.alink',$domain),
                   6295: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6296: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6297:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6298: 
1.63      www      6299:  # role and realm
1.1075.2.68  raeburn  6300:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6301:     if ($realm) {
                   6302:         $realm = '/'.$realm;
                   6303:     }
1.1075.2.159  raeburn  6304:     if ($role eq 'ca') {
1.479     albertel 6305:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6306:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6307:     } 
1.55      www      6308: # realm
1.1075.2.158  raeburn  6309:     my ($cid,$sec);
1.258     albertel 6310:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  6311:         $cid = $env{'request.course.id'};
                   6312:         if ($env{'request.course.sec'}) {
                   6313:             $sec = $env{'request.course.sec'};
                   6314:         }
                   6315:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6316:         if (&Apache::lonnet::is_course($1,$2)) {
                   6317:             $cid = $1.'_'.$2;
                   6318:             $sec = $3;
                   6319:         }
                   6320:     }
                   6321:     if ($cid) {
1.378     raeburn  6322:         if ($env{'request.role'} !~ /^cr/) {
                   6323:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6324:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6325:             if ($env{'request.role.desc'}) {
                   6326:                 $role = $env{'request.role.desc'};
                   6327:             } else {
                   6328:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6329:             }
1.1075.2.115  raeburn  6330:         } else {
                   6331:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6332:         }
1.1075.2.158  raeburn  6333:         if ($sec) {
                   6334:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6335:         }   
1.1075.2.158  raeburn  6336: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6337:     } else {
                   6338:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6339:     }
1.433     albertel 6340: 
1.359     albertel 6341:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6342: 
1.438     albertel 6343:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6344: 
1.101     www      6345: # construct main body tag
1.359     albertel 6346:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6347: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6348: 
1.1075.2.38  raeburn  6349:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6350: 
                   6351:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6352:         return $bodytag;
1.1075.2.38  raeburn  6353:     }
1.359     albertel 6354: 
1.954     raeburn  6355:     if ($public) {
1.433     albertel 6356: 	undef($role);
                   6357:     }
1.1075.2.158  raeburn  6358: 
1.1075.2.161.  .1(raebu 6359:21):     my $showcrstitle = 1;
                   6360:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6361:21):         if (ref($ltimenu) eq 'HASH') {
                   6362:21):             unless ($ltimenu->{'role'}) {
                   6363:21):                 undef($role);
                   6364:21):             }
                   6365:21):             unless ($ltimenu->{'coursetitle'}) {
                   6366:21):                 $realm='&nbsp;';
                   6367:21):                 $showcrstitle = 0;
                   6368:21):             }
                   6369:21):         }
                   6370:21):     } elsif (($cid) && ($menucoll)) {
                   6371:21):         if (ref($menuref) eq 'HASH') {
                   6372:21):             unless ($menuref->{'role'}) {
                   6373:21):                 undef($role);
                   6374:21):             }
                   6375:21):             unless ($menuref->{'crs'}) {
                   6376:21):                 $realm='&nbsp;';
                   6377:21):                 $showcrstitle = 0;
                   6378:21):             }
                   6379:21):         }
                   6380:21):     }
                   6381:21): 
1.762     bisitz   6382:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6383:     #
                   6384:     # Extra info if you are the DC
                   6385:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6386:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6387:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6388:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6389:         $dc_info =~ s/\s+$//;
1.359     albertel 6390:     }
                   6391: 
1.1075.2.161.  .1(raebu 6392:21):     my $crstype;
                   6393:21):     if ($cid) {
                   6394:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6395:21):     } elsif ($args->{'crstype'}) {
                   6396:21):         $crstype = $args->{'crstype'};
                   6397:21):     }
                   6398:21): 
1.1075.2.108  raeburn  6399:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6400: 
1.1075.2.13  raeburn  6401:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6402: 
1.1075.2.38  raeburn  6403: 
                   6404: 
1.1075.2.21  raeburn  6405:     my $funclist;
                   6406:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  6407:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  6408:                     Apache::lonmenu::serverform();
                   6409:         my $forbodytag;
                   6410:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6411:                                             $forcereg,$args->{'group'},
                   6412:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6413:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  6414:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6415:             $funclist = $forbodytag;
                   6416:         }
                   6417:     } else {
1.903     droeschl 6418: 
                   6419:         #    if ($env{'request.state'} eq 'construct') {
                   6420:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6421:         #    }
                   6422: 
1.1075.2.38  raeburn  6423:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6424:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6425: 
1.1075.2.161.  .23(raeb 6426:-24):         my $collapsible;
          .21(raeb 6427:-24):         if ($args->{'collapsible_header'} ne '') {
          .23(raeb 6428:-24):             $collapsible = 1;
                   6429:-24):             my ($menustate,$tiptext,$divclass);
                   6430:-24):             if ($args->{'start_collapsed'}) {
                   6431:-24):                 $menustate = 'collapsed';
                   6432:-24):                 $tiptext = 'display';
                   6433:-24):                 $divclass = 'hidden';
                   6434:-24):             } else {
                   6435:-24):                 $menustate = 'expanded';
                   6436:-24):                 $tiptext = 'hide';
                   6437:-24):                 $divclass = 'shown';
                   6438:-24):             }
                   6439:-24):             my $alttext = &mt('menu state: '.$menustate);
                   6440:-24):             my $tooltip = &mt($tiptext.' standard menus');
          .21(raeb 6441:-24):             $bodytag .= <<"END";
                   6442:-24): <div id="LC_expandingContainer" style="display:inline;">
                   6443:-24): <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
          .23(raeb 6444:-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>
                   6445:-24): <div class="LC_menus_content $divclass">
          .21(raeb 6446:-24): END
                   6447:-24):         }
          .1(raebu 6448:21):         unless ($args->{'no_primary_menu'}) {
          .4(raebu 6449:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6450:22):                                                               $args->{'links_disabled'},
          .21(raeb 6451:-24):                                                               $args->{'links_target'},
          .23(raeb 6452:-24):                                                               $collapsible);
          .1(raebu 6453:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6454:21):                 if ($dc_info) {
                   6455:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6456:21):                 }
                   6457:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6458:21):                                <em>$realm</em> $dc_info</div>|;
                   6459:21):                 return $bodytag;
1.1075.2.1  raeburn  6460:             }
1.894     droeschl 6461: 
1.1075.2.161.  .1(raebu 6462:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6463:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6464:21):             }
1.916     droeschl 6465: 
1.1075.2.161.  .1(raebu 6466:21):             $bodytag .= $right;
1.852     droeschl 6467: 
1.1075.2.161.  .1(raebu 6468:21):             if ($dc_info) {
                   6469:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6470:21):             }
                   6471:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6472:         }
1.916     droeschl 6473: 
1.1075.2.61  raeburn  6474:         #if directed to not display the secondary menu, don't.
                   6475:         if ($args->{'no_secondary_menu'}) {
                   6476:             return $bodytag;
                   6477:         }
1.903     droeschl 6478:         #don't show menus for public users
1.954     raeburn  6479:         if (!$public){
1.1075.2.161.  .1(raebu 6480:21):             unless ($args->{'no_inline_menu'}) {
                   6481:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6482:21):                                                             $args->{'no_primary_menu'},
                   6483:21):                                                             $menucoll,$menuref,
          .6(raebu 6484:22):                                                             $args->{'links_disabled'},
                   6485:22):                                                             $args->{'links_target'});
          .1(raebu 6486:21):             }
1.903     droeschl 6487:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6488:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6489:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6490:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6491:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6492:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6493:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6494:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6495:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6496:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6497:             } else {
1.1075.2.21  raeburn  6498:                 my $forbodytag;
                   6499:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6500:                                                     $forcereg,$args->{'group'},
                   6501:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6502:                                                     $advtoolsref,'',$hostname,
                   6503:                                                     \$forbodytag);
1.1075.2.21  raeburn  6504:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6505:                     $bodytag .= $forbodytag;
                   6506:                 }
1.920     raeburn  6507:             }
1.903     droeschl 6508:         }else{
                   6509:             # this is to seperate menu from content when there's no secondary
                   6510:             # menu. Especially needed for public accessible ressources.
                   6511:             $bodytag .= '<hr style="clear:both" />';
                   6512:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6513:         }
1.1075.2.161.  .21(raeb 6514:-24):         if ($args->{'collapsible_header'} ne '') {
                   6515:-24):             $bodytag .= $args->{'collapsible_header'}.
                   6516:-24):                         '<div id="LC_collapsible_separator"></div>'.
                   6517:-24):                         '</div></div>';
                   6518:-24):         }
1.235     raeburn  6519:         return $bodytag;
1.1075.2.12  raeburn  6520:     }
                   6521: 
                   6522: #
                   6523: # Top frame rendering, Remote is up
                   6524: #
                   6525: 
                   6526:     my $imgsrc = $img;
                   6527:     if ($img =~ /^\/adm/) {
                   6528:         $imgsrc = &lonhttpdurl($img);
                   6529:     }
                   6530:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   6531: 
1.1075.2.60  raeburn  6532:     my $help=($no_inline_link?''
                   6533:               :&Apache::loncommon::top_nav_help('Help'));
                   6534: 
1.1075.2.12  raeburn  6535:     # Explicit link to get inline menu
                   6536:     my $menu= ($no_inline_link?''
                   6537:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6538: 
                   6539:     if ($dc_info) {
                   6540:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6541:     }
                   6542: 
1.1075.2.38  raeburn  6543:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6544:     unless ($public) {
                   6545:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6546:                                 undef,'LC_menubuttons_link');
                   6547:     }
                   6548: 
1.1075.2.12  raeburn  6549:     unless ($env{'form.inhibitmenu'}) {
                   6550:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  6551:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  6552:                        <li>$help</li>
1.1075.2.12  raeburn  6553:                        <li>$menu</li>
                   6554:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6555:     }
1.1075.2.13  raeburn  6556:     if ($env{'request.state'} eq 'construct') {
                   6557:         if (!$public){
                   6558:             if ($env{'request.state'} eq 'construct') {
                   6559:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6560:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  6561:                             &Apache::lonhtmlcommon::scripttag('','end').
                   6562:                             &Apache::lonmenu::innerregister($forcereg,
                   6563:                                                             $args->{'bread_crumbs'});
                   6564:             }
                   6565:         }
                   6566:     }
1.1075.2.21  raeburn  6567:     return $bodytag."\n".$funclist;
1.182     matthew  6568: }
                   6569: 
1.917     raeburn  6570: sub dc_courseid_toggle {
                   6571:     my ($dc_info) = @_;
1.980     raeburn  6572:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6573:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6574:            &mt('(More ...)').'</a></span>'.
                   6575:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6576: }
                   6577: 
1.330     albertel 6578: sub make_attr_string {
                   6579:     my ($register,$attr_ref) = @_;
                   6580: 
                   6581:     if ($attr_ref && !ref($attr_ref)) {
                   6582: 	die("addentries Must be a hash ref ".
                   6583: 	    join(':',caller(1))." ".
                   6584: 	    join(':',caller(0))." ");
                   6585:     }
                   6586: 
                   6587:     if ($register) {
1.339     albertel 6588: 	my ($on_load,$on_unload);
                   6589: 	foreach my $key (keys(%{$attr_ref})) {
                   6590: 	    if      (lc($key) eq 'onload') {
                   6591: 		$on_load.=$attr_ref->{$key}.';';
                   6592: 		delete($attr_ref->{$key});
                   6593: 
                   6594: 	    } elsif (lc($key) eq 'onunload') {
                   6595: 		$on_unload.=$attr_ref->{$key}.';';
                   6596: 		delete($attr_ref->{$key});
                   6597: 	    }
                   6598: 	}
1.1075.2.12  raeburn  6599:         if ($env{'environment.remote'} eq 'on') {
                   6600:             $attr_ref->{'onload'}  =
                   6601:                 &Apache::lonmenu::loadevents().  $on_load;
                   6602:             $attr_ref->{'onunload'}=
                   6603:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6604:         } else {  
                   6605: 	    $attr_ref->{'onload'}  = $on_load;
                   6606: 	    $attr_ref->{'onunload'}= $on_unload;
                   6607:         }
1.330     albertel 6608:     }
1.339     albertel 6609: 
1.330     albertel 6610:     my $attr_string;
1.1075.2.56  raeburn  6611:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6612: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6613:     }
                   6614:     return $attr_string;
                   6615: }
                   6616: 
                   6617: 
1.182     matthew  6618: ###############################################
1.251     albertel 6619: ###############################################
                   6620: 
                   6621: =pod
                   6622: 
                   6623: =item * &endbodytag()
                   6624: 
                   6625: Returns a uniform footer for LON-CAPA web pages.
                   6626: 
1.635     raeburn  6627: Inputs: 1 - optional reference to an args hash
                   6628: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6629: a 'Continue' link is not displayed if the page contains an
                   6630: internal redirect in the <head></head> section,
                   6631: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6632: 
                   6633: =cut
                   6634: 
                   6635: sub endbodytag {
1.635     raeburn  6636:     my ($args) = @_;
1.1075.2.6  raeburn  6637:     my $endbodytag;
                   6638:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6639:         $endbodytag='</body>';
                   6640:     }
1.315     albertel 6641:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6642:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6643:22):             my ($endbodyjs,$idattr);
                   6644:22):             if ($env{'internal.head.to_opener'}) {
                   6645:22):                 my $linkid = 'LC_continue_link';
                   6646:22):                 $idattr = ' id="'.$linkid.'"';
                   6647:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6648:22):                 $endbodyjs=<<ENDJS;
                   6649:22): <script type="text/javascript">
                   6650:22): // <![CDATA[
                   6651:22): function ebFunction(evt) {
                   6652:22):     evt.preventDefault();
                   6653:22):     var dest = '$redirect_for_js';
                   6654:22):     if (window.opener != null && !window.opener.closed) {
                   6655:22):         window.opener.location.href=dest;
                   6656:22):         window.close();
                   6657:22):     } else {
                   6658:22):         window.location.href=dest;
                   6659:22):     }
                   6660:22):     return false;
                   6661:22): }
                   6662:22): 
                   6663:22): \$(document).ready(function () {
                   6664:22):   if (document.getElementById('$linkid')) {
                   6665:22):     var clickelem = document.getElementById('$linkid');
                   6666:22):     clickelem.addEventListener('click',ebFunction,false);
                   6667:22):   }
                   6668:22): });
                   6669:22): // ]]>
                   6670:22): </script>
                   6671:22): ENDJS
                   6672:22):             }
1.635     raeburn  6673: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6674:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6675: 	        &mt('Continue').'</a>'.
                   6676: 	        $endbodytag;
                   6677:         }
1.315     albertel 6678:     }
1.1075.2.161.  .19(raeb 6679:-23):     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   6680:-23):         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   6681:-23):     }
1.251     albertel 6682:     return $endbodytag;
                   6683: }
                   6684: 
1.352     albertel 6685: =pod
                   6686: 
                   6687: =item * &standard_css()
                   6688: 
                   6689: Returns a style sheet
                   6690: 
                   6691: Inputs: (all optional)
                   6692:             domain         -> force to color decorate a page for a specific
                   6693:                                domain
                   6694:             function       -> force usage of a specific rolish color scheme
                   6695:             bgcolor        -> override the default page bgcolor
                   6696: 
                   6697: =cut
                   6698: 
1.343     albertel 6699: sub standard_css {
1.345     albertel 6700:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6701:     $function  = &get_users_function() if (!$function);
                   6702:     my $img    = &designparm($function.'.img',   $domain);
                   6703:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6704:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6705:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6706: #second colour for later usage
1.345     albertel 6707:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6708:     my $pgbg_or_bgcolor =
                   6709: 	         $bgcolor ||
1.352     albertel 6710: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6711:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6712:     my $alink  = &designparm($function.'.alink', $domain);
                   6713:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6714:     my $link   = &designparm($function.'.link',  $domain);
                   6715: 
1.602     albertel 6716:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6717:     my $mono                 = 'monospace';
1.850     bisitz   6718:     my $data_table_head      = $sidebg;
                   6719:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6720:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6721:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6722:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6723:     my $mail_new             = '#FFBB77';
                   6724:     my $mail_new_hover       = '#DD9955';
                   6725:     my $mail_read            = '#BBBB77';
                   6726:     my $mail_read_hover      = '#999944';
                   6727:     my $mail_replied         = '#AAAA88';
                   6728:     my $mail_replied_hover   = '#888855';
                   6729:     my $mail_other           = '#99BBBB';
                   6730:     my $mail_other_hover     = '#669999';
1.391     albertel 6731:     my $table_header         = '#DDDDDD';
1.489     raeburn  6732:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6733:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6734:     my $button_hover         = '#BF2317';
1.392     albertel 6735: 
1.608     albertel 6736:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6737:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6738:                                              : '0 3px 0 4px';
1.448     albertel 6739: 
1.523     albertel 6740: 
1.343     albertel 6741:     return <<END;
1.947     droeschl 6742: 
                   6743: /* needed for iframe to allow 100% height in FF */
                   6744: body, html { 
                   6745:     margin: 0;
                   6746:     padding: 0 0.5%;
                   6747:     height: 99%; /* to avoid scrollbars */
                   6748: }
                   6749: 
1.795     www      6750: body {
1.911     bisitz   6751:   font-family: $sans;
                   6752:   line-height:130%;
                   6753:   font-size:0.83em;
                   6754:   color:$font;
1.795     www      6755: }
                   6756: 
1.959     onken    6757: a:focus,
                   6758: a:focus img {
1.795     www      6759:   color: red;
                   6760: }
1.698     harmsja  6761: 
1.911     bisitz   6762: form, .inline {
                   6763:   display: inline;
1.795     www      6764: }
1.721     harmsja  6765: 
1.1075.2.161.  .21(raeb 6766:-24): .LC_menus_content.shown{
          .24(raeb 6767:-24):   display: block;
          .21(raeb 6768:-24): }
                   6769:-24): 
                   6770:-24): .LC_menus_content.hidden {
                   6771:-24):   display: none;
                   6772:-24): }
                   6773:-24): 
1.795     www      6774: .LC_right {
1.911     bisitz   6775:   text-align:right;
1.795     www      6776: }
                   6777: 
                   6778: .LC_middle {
1.911     bisitz   6779:   vertical-align:middle;
1.795     www      6780: }
1.721     harmsja  6781: 
1.1075.2.38  raeburn  6782: .LC_floatleft {
                   6783:   float: left;
                   6784: }
                   6785: 
                   6786: .LC_floatright {
                   6787:   float: right;
                   6788: }
                   6789: 
1.911     bisitz   6790: .LC_400Box {
                   6791:   width:400px;
                   6792: }
1.721     harmsja  6793: 
1.1075.2.161.  .21(raeb 6794:-24): #LC_collapsible_separator {
                   6795:-24):     border: 1px solid black;
                   6796:-24):     width: 99.9%;
                   6797:-24):     height: 0px;
                   6798:-24): }
                   6799:-24): 
1.947     droeschl 6800: .LC_iframecontainer {
                   6801:     width: 98%;
                   6802:     margin: 0;
                   6803:     position: fixed;
                   6804:     top: 8.5em;
                   6805:     bottom: 0;
                   6806: }
                   6807: 
                   6808: .LC_iframecontainer iframe{
                   6809:     border: none;
                   6810:     width: 100%;
                   6811:     height: 100%;
                   6812: }
                   6813: 
1.778     bisitz   6814: .LC_filename {
                   6815:   font-family: $mono;
                   6816:   white-space:pre;
1.921     bisitz   6817:   font-size: 120%;
1.778     bisitz   6818: }
                   6819: 
                   6820: .LC_fileicon {
                   6821:   border: none;
                   6822:   height: 1.3em;
                   6823:   vertical-align: text-bottom;
                   6824:   margin-right: 0.3em;
                   6825:   text-decoration:none;
                   6826: }
                   6827: 
1.1008    www      6828: .LC_setting {
                   6829:   text-decoration:underline;
                   6830: }
                   6831: 
1.350     albertel 6832: .LC_error {
                   6833:   color: red;
                   6834: }
1.795     www      6835: 
1.1075.2.15  raeburn  6836: .LC_warning {
                   6837:   color: darkorange;
                   6838: }
                   6839: 
1.457     albertel 6840: .LC_diff_removed {
1.733     bisitz   6841:   color: red;
1.394     albertel 6842: }
1.532     albertel 6843: 
                   6844: .LC_info,
1.457     albertel 6845: .LC_success,
                   6846: .LC_diff_added {
1.350     albertel 6847:   color: green;
                   6848: }
1.795     www      6849: 
1.802     bisitz   6850: div.LC_confirm_box {
                   6851:   background-color: #FAFAFA;
                   6852:   border: 1px solid $lg_border_color;
                   6853:   margin-right: 0;
                   6854:   padding: 5px;
                   6855: }
                   6856: 
                   6857: div.LC_confirm_box .LC_error img,
                   6858: div.LC_confirm_box .LC_success img {
                   6859:   vertical-align: middle;
                   6860: }
                   6861: 
1.1075.2.108  raeburn  6862: .LC_maxwidth {
                   6863:   max-width: 100%;
                   6864:   height: auto;
                   6865: }
                   6866: 
                   6867: .LC_textsize_mobile {
                   6868:   \@media only screen and (max-device-width: 480px) {
                   6869:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6870:   }
                   6871: }
                   6872: 
1.440     albertel 6873: .LC_icon {
1.771     droeschl 6874:   border: none;
1.790     droeschl 6875:   vertical-align: middle;
1.771     droeschl 6876: }
                   6877: 
1.543     albertel 6878: .LC_docs_spacer {
                   6879:   width: 25px;
                   6880:   height: 1px;
1.771     droeschl 6881:   border: none;
1.543     albertel 6882: }
1.346     albertel 6883: 
1.532     albertel 6884: .LC_internal_info {
1.735     bisitz   6885:   color: #999999;
1.532     albertel 6886: }
                   6887: 
1.794     www      6888: .LC_discussion {
1.1050    www      6889:   background: $data_table_dark;
1.911     bisitz   6890:   border: 1px solid black;
                   6891:   margin: 2px;
1.794     www      6892: }
                   6893: 
                   6894: .LC_disc_action_left {
1.1050    www      6895:   background: $sidebg;
1.911     bisitz   6896:   text-align: left;
1.1050    www      6897:   padding: 4px;
                   6898:   margin: 2px;
1.794     www      6899: }
                   6900: 
                   6901: .LC_disc_action_right {
1.1050    www      6902:   background: $sidebg;
1.911     bisitz   6903:   text-align: right;
1.1050    www      6904:   padding: 4px;
                   6905:   margin: 2px;
1.794     www      6906: }
                   6907: 
                   6908: .LC_disc_new_item {
1.911     bisitz   6909:   background: white;
                   6910:   border: 2px solid red;
1.1050    www      6911:   margin: 4px;
                   6912:   padding: 4px;
1.794     www      6913: }
                   6914: 
                   6915: .LC_disc_old_item {
1.911     bisitz   6916:   background: white;
1.1050    www      6917:   margin: 4px;
                   6918:   padding: 4px;
1.794     www      6919: }
                   6920: 
1.458     albertel 6921: table.LC_pastsubmission {
                   6922:   border: 1px solid black;
                   6923:   margin: 2px;
                   6924: }
                   6925: 
1.924     bisitz   6926: table#LC_menubuttons {
1.345     albertel 6927:   width: 100%;
                   6928:   background: $pgbg;
1.392     albertel 6929:   border: 2px;
1.402     albertel 6930:   border-collapse: separate;
1.803     bisitz   6931:   padding: 0;
1.345     albertel 6932: }
1.392     albertel 6933: 
1.801     tempelho 6934: table#LC_title_bar a {
                   6935:   color: $fontmenu;
                   6936: }
1.836     bisitz   6937: 
1.807     droeschl 6938: table#LC_title_bar {
1.819     tempelho 6939:   clear: both;
1.836     bisitz   6940:   display: none;
1.807     droeschl 6941: }
                   6942: 
1.795     www      6943: table#LC_title_bar,
1.933     droeschl 6944: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6945: table#LC_title_bar.LC_with_remote {
1.359     albertel 6946:   width: 100%;
1.392     albertel 6947:   border-color: $pgbg;
                   6948:   border-style: solid;
                   6949:   border-width: $border;
1.379     albertel 6950:   background: $pgbg;
1.801     tempelho 6951:   color: $fontmenu;
1.392     albertel 6952:   border-collapse: collapse;
1.803     bisitz   6953:   padding: 0;
1.819     tempelho 6954:   margin: 0;
1.359     albertel 6955: }
1.795     www      6956: 
1.933     droeschl 6957: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6958:     margin: 0;
                   6959:     padding: 0;
1.933     droeschl 6960:     position: relative;
                   6961:     list-style: none;
1.913     droeschl 6962: }
1.933     droeschl 6963: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6964:     display: inline;
                   6965: }
1.933     droeschl 6966: 
                   6967: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6968:     padding: 0;
1.933     droeschl 6969:     margin: 0;
                   6970:     float: left;
1.913     droeschl 6971: }
1.933     droeschl 6972: .LC_breadcrumb_tools_tools {
                   6973:     padding: 0;
                   6974:     margin: 0;
1.913     droeschl 6975:     float: right;
                   6976: }
                   6977: 
1.359     albertel 6978: table#LC_title_bar td {
                   6979:   background: $tabbg;
                   6980: }
1.795     www      6981: 
1.911     bisitz   6982: table#LC_menubuttons img {
1.803     bisitz   6983:   border: none;
1.346     albertel 6984: }
1.795     www      6985: 
1.842     droeschl 6986: .LC_breadcrumbs_component {
1.911     bisitz   6987:   float: right;
                   6988:   margin: 0 1em;
1.357     albertel 6989: }
1.842     droeschl 6990: .LC_breadcrumbs_component img {
1.911     bisitz   6991:   vertical-align: middle;
1.777     tempelho 6992: }
1.795     www      6993: 
1.1075.2.108  raeburn  6994: .LC_breadcrumbs_hoverable {
                   6995:   background: $sidebg;
                   6996: }
                   6997: 
1.383     albertel 6998: td.LC_table_cell_checkbox {
                   6999:   text-align: center;
                   7000: }
1.795     www      7001: 
                   7002: .LC_fontsize_small {
1.911     bisitz   7003:   font-size: 70%;
1.705     tempelho 7004: }
                   7005: 
1.844     bisitz   7006: #LC_breadcrumbs {
1.911     bisitz   7007:   clear:both;
                   7008:   background: $sidebg;
                   7009:   border-bottom: 1px solid $lg_border_color;
                   7010:   line-height: 2.5em;
1.933     droeschl 7011:   overflow: hidden;
1.911     bisitz   7012:   margin: 0;
                   7013:   padding: 0;
1.995     raeburn  7014:   text-align: left;
1.819     tempelho 7015: }
1.862     bisitz   7016: 
1.1075.2.16  raeburn  7017: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7018:   clear:both;
                   7019:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7020:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  7021:   margin: 0 0 10px 0;
1.966     bisitz   7022:   padding: 3px;
1.995     raeburn  7023:   text-align: left;
1.822     bisitz   7024: }
                   7025: 
1.795     www      7026: .LC_fontsize_medium {
1.911     bisitz   7027:   font-size: 85%;
1.705     tempelho 7028: }
                   7029: 
1.795     www      7030: .LC_fontsize_large {
1.911     bisitz   7031:   font-size: 120%;
1.705     tempelho 7032: }
                   7033: 
1.346     albertel 7034: .LC_menubuttons_inline_text {
                   7035:   color: $font;
1.698     harmsja  7036:   font-size: 90%;
1.701     harmsja  7037:   padding-left:3px;
1.346     albertel 7038: }
                   7039: 
1.934     droeschl 7040: .LC_menubuttons_inline_text img{
                   7041:   vertical-align: middle;
                   7042: }
                   7043: 
1.1051    www      7044: li.LC_menubuttons_inline_text img {
1.951     onken    7045:   cursor:pointer;
1.1002    droeschl 7046:   text-decoration: none;
1.951     onken    7047: }
                   7048: 
1.526     www      7049: .LC_menubuttons_link {
                   7050:   text-decoration: none;
                   7051: }
1.795     www      7052: 
1.522     albertel 7053: .LC_menubuttons_category {
1.521     www      7054:   color: $font;
1.526     www      7055:   background: $pgbg;
1.521     www      7056:   font-size: larger;
                   7057:   font-weight: bold;
                   7058: }
                   7059: 
1.346     albertel 7060: td.LC_menubuttons_text {
1.911     bisitz   7061:   color: $font;
1.346     albertel 7062: }
1.706     harmsja  7063: 
1.346     albertel 7064: .LC_current_location {
                   7065:   background: $tabbg;
                   7066: }
1.795     www      7067: 
1.1075.2.134  raeburn  7068: td.LC_zero_height {
                   7069:   line-height: 0;
                   7070:   cellpadding: 0;
                   7071: }
                   7072: 
1.938     bisitz   7073: table.LC_data_table {
1.347     albertel 7074:   border: 1px solid #000000;
1.402     albertel 7075:   border-collapse: separate;
1.426     albertel 7076:   border-spacing: 1px;
1.610     albertel 7077:   background: $pgbg;
1.347     albertel 7078: }
1.795     www      7079: 
1.422     albertel 7080: .LC_data_table_dense {
                   7081:   font-size: small;
                   7082: }
1.795     www      7083: 
1.507     raeburn  7084: table.LC_nested_outer {
                   7085:   border: 1px solid #000000;
1.589     raeburn  7086:   border-collapse: collapse;
1.803     bisitz   7087:   border-spacing: 0;
1.507     raeburn  7088:   width: 100%;
                   7089: }
1.795     www      7090: 
1.879     raeburn  7091: table.LC_innerpickbox,
1.507     raeburn  7092: table.LC_nested {
1.803     bisitz   7093:   border: none;
1.589     raeburn  7094:   border-collapse: collapse;
1.803     bisitz   7095:   border-spacing: 0;
1.507     raeburn  7096:   width: 100%;
                   7097: }
1.795     www      7098: 
1.911     bisitz   7099: table.LC_data_table tr th,
                   7100: table.LC_calendar tr th,
1.879     raeburn  7101: table.LC_prior_tries tr th,
                   7102: table.LC_innerpickbox tr th {
1.349     albertel 7103:   font-weight: bold;
                   7104:   background-color: $data_table_head;
1.801     tempelho 7105:   color:$fontmenu;
1.701     harmsja  7106:   font-size:90%;
1.347     albertel 7107: }
1.795     www      7108: 
1.879     raeburn  7109: table.LC_innerpickbox tr th,
                   7110: table.LC_innerpickbox tr td {
                   7111:   vertical-align: top;
                   7112: }
                   7113: 
1.711     raeburn  7114: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7115:   background-color: #CCCCCC;
1.711     raeburn  7116:   font-weight: bold;
                   7117:   text-align: left;
                   7118: }
1.795     www      7119: 
1.912     bisitz   7120: table.LC_data_table tr.LC_odd_row > td {
                   7121:   background-color: $data_table_light;
                   7122:   padding: 2px;
                   7123:   vertical-align: top;
                   7124: }
                   7125: 
1.809     bisitz   7126: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7127:   background-color: $data_table_light;
1.912     bisitz   7128:   vertical-align: top;
                   7129: }
                   7130: 
                   7131: table.LC_data_table tr.LC_even_row > td {
                   7132:   background-color: $data_table_dark;
1.425     albertel 7133:   padding: 2px;
1.900     bisitz   7134:   vertical-align: top;
1.347     albertel 7135: }
1.795     www      7136: 
1.809     bisitz   7137: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7138:   background-color: $data_table_dark;
1.900     bisitz   7139:   vertical-align: top;
1.347     albertel 7140: }
1.795     www      7141: 
1.425     albertel 7142: table.LC_data_table tr.LC_data_table_highlight td {
                   7143:   background-color: $data_table_darker;
                   7144: }
1.795     www      7145: 
1.639     raeburn  7146: table.LC_data_table tr td.LC_leftcol_header {
                   7147:   background-color: $data_table_head;
                   7148:   font-weight: bold;
                   7149: }
1.795     www      7150: 
1.451     albertel 7151: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7152: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7153:   font-weight: bold;
                   7154:   font-style: italic;
                   7155:   text-align: center;
                   7156:   padding: 8px;
1.347     albertel 7157: }
1.795     www      7158: 
1.1075.2.30  raeburn  7159: table.LC_data_table tr.LC_empty_row td,
                   7160: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7161:   background-color: $sidebg;
                   7162: }
                   7163: 
                   7164: table.LC_nested tr.LC_empty_row td {
                   7165:   background-color: #FFFFFF;
                   7166: }
                   7167: 
1.890     droeschl 7168: table.LC_caption {
                   7169: }
                   7170: 
1.507     raeburn  7171: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7172:   padding: 4ex
                   7173: }
1.795     www      7174: 
1.507     raeburn  7175: table.LC_nested_outer tr th {
                   7176:   font-weight: bold;
1.801     tempelho 7177:   color:$fontmenu;
1.507     raeburn  7178:   background-color: $data_table_head;
1.701     harmsja  7179:   font-size: small;
1.507     raeburn  7180:   border-bottom: 1px solid #000000;
                   7181: }
1.795     www      7182: 
1.507     raeburn  7183: table.LC_nested_outer tr td.LC_subheader {
                   7184:   background-color: $data_table_head;
                   7185:   font-weight: bold;
                   7186:   font-size: small;
                   7187:   border-bottom: 1px solid #000000;
                   7188:   text-align: right;
1.451     albertel 7189: }
1.795     www      7190: 
1.507     raeburn  7191: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7192:   background-color: #CCCCCC;
1.451     albertel 7193:   font-weight: bold;
                   7194:   font-size: small;
1.507     raeburn  7195:   text-align: center;
                   7196: }
1.795     www      7197: 
1.589     raeburn  7198: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7199: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7200:   text-align: left;
1.451     albertel 7201: }
1.795     www      7202: 
1.507     raeburn  7203: table.LC_nested td {
1.735     bisitz   7204:   background-color: #FFFFFF;
1.451     albertel 7205:   font-size: small;
1.507     raeburn  7206: }
1.795     www      7207: 
1.507     raeburn  7208: table.LC_nested_outer tr th.LC_right_item,
                   7209: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7210: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7211: table.LC_nested tr td.LC_right_item {
1.451     albertel 7212:   text-align: right;
                   7213: }
                   7214: 
1.507     raeburn  7215: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7216:   background-color: #EEEEEE;
1.451     albertel 7217: }
                   7218: 
1.473     raeburn  7219: table.LC_createuser {
                   7220: }
                   7221: 
                   7222: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7223:   font-size: small;
1.473     raeburn  7224: }
                   7225: 
                   7226: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7227:   background-color: #CCCCCC;
1.473     raeburn  7228:   font-weight: bold;
                   7229:   text-align: center;
                   7230: }
                   7231: 
1.349     albertel 7232: table.LC_calendar {
                   7233:   border: 1px solid #000000;
                   7234:   border-collapse: collapse;
1.917     raeburn  7235:   width: 98%;
1.349     albertel 7236: }
1.795     www      7237: 
1.349     albertel 7238: table.LC_calendar_pickdate {
                   7239:   font-size: xx-small;
                   7240: }
1.795     www      7241: 
1.349     albertel 7242: table.LC_calendar tr td {
                   7243:   border: 1px solid #000000;
                   7244:   vertical-align: top;
1.917     raeburn  7245:   width: 14%;
1.349     albertel 7246: }
1.795     www      7247: 
1.349     albertel 7248: table.LC_calendar tr td.LC_calendar_day_empty {
                   7249:   background-color: $data_table_dark;
                   7250: }
1.795     www      7251: 
1.779     bisitz   7252: table.LC_calendar tr td.LC_calendar_day_current {
                   7253:   background-color: $data_table_highlight;
1.777     tempelho 7254: }
1.795     www      7255: 
1.938     bisitz   7256: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7257:   background-color: $mail_new;
                   7258: }
1.795     www      7259: 
1.938     bisitz   7260: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7261:   background-color: $mail_new_hover;
                   7262: }
1.795     www      7263: 
1.938     bisitz   7264: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7265:   background-color: $mail_read;
                   7266: }
1.795     www      7267: 
1.938     bisitz   7268: /*
                   7269: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7270:   background-color: $mail_read_hover;
                   7271: }
1.938     bisitz   7272: */
1.795     www      7273: 
1.938     bisitz   7274: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7275:   background-color: $mail_replied;
                   7276: }
1.795     www      7277: 
1.938     bisitz   7278: /*
                   7279: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7280:   background-color: $mail_replied_hover;
                   7281: }
1.938     bisitz   7282: */
1.795     www      7283: 
1.938     bisitz   7284: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7285:   background-color: $mail_other;
                   7286: }
1.795     www      7287: 
1.938     bisitz   7288: /*
                   7289: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7290:   background-color: $mail_other_hover;
                   7291: }
1.938     bisitz   7292: */
1.494     raeburn  7293: 
1.777     tempelho 7294: table.LC_data_table tr > td.LC_browser_file,
                   7295: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7296:   background: #AAEE77;
1.389     albertel 7297: }
1.795     www      7298: 
1.777     tempelho 7299: table.LC_data_table tr > td.LC_browser_file_locked,
                   7300: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7301:   background: #FFAA99;
1.387     albertel 7302: }
1.795     www      7303: 
1.777     tempelho 7304: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7305:   background: #888888;
1.779     bisitz   7306: }
1.795     www      7307: 
1.777     tempelho 7308: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7309: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7310:   background: #F8F866;
1.777     tempelho 7311: }
1.795     www      7312: 
1.696     bisitz   7313: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7314:   background: #E0E8FF;
1.387     albertel 7315: }
1.696     bisitz   7316: 
1.707     bisitz   7317: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7318:   /* background: #77FF77; */
1.707     bisitz   7319: }
1.795     www      7320: 
1.707     bisitz   7321: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7322:   border-right: 8px solid #FFFF77;
1.707     bisitz   7323: }
1.795     www      7324: 
1.707     bisitz   7325: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7326:   border-right: 8px solid #FFAA77;
1.707     bisitz   7327: }
1.795     www      7328: 
1.707     bisitz   7329: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7330:   border-right: 8px solid #FF7777;
1.707     bisitz   7331: }
1.795     www      7332: 
1.707     bisitz   7333: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7334:   border-right: 8px solid #AAFF77;
1.707     bisitz   7335: }
1.795     www      7336: 
1.707     bisitz   7337: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7338:   border-right: 8px solid #11CC55;
1.707     bisitz   7339: }
                   7340: 
1.388     albertel 7341: span.LC_current_location {
1.701     harmsja  7342:   font-size:larger;
1.388     albertel 7343:   background: $pgbg;
                   7344: }
1.387     albertel 7345: 
1.1029    www      7346: span.LC_current_nav_location {
                   7347:   font-weight:bold;
                   7348:   background: $sidebg;
                   7349: }
                   7350: 
1.395     albertel 7351: span.LC_parm_menu_item {
                   7352:   font-size: larger;
                   7353: }
1.795     www      7354: 
1.395     albertel 7355: span.LC_parm_scope_all {
                   7356:   color: red;
                   7357: }
1.795     www      7358: 
1.395     albertel 7359: span.LC_parm_scope_folder {
                   7360:   color: green;
                   7361: }
1.795     www      7362: 
1.395     albertel 7363: span.LC_parm_scope_resource {
                   7364:   color: orange;
                   7365: }
1.795     www      7366: 
1.395     albertel 7367: span.LC_parm_part {
                   7368:   color: blue;
                   7369: }
1.795     www      7370: 
1.911     bisitz   7371: span.LC_parm_folder,
                   7372: span.LC_parm_symb {
1.395     albertel 7373:   font-size: x-small;
                   7374:   font-family: $mono;
                   7375:   color: #AAAAAA;
                   7376: }
                   7377: 
1.977     bisitz   7378: ul.LC_parm_parmlist li {
                   7379:   display: inline-block;
                   7380:   padding: 0.3em 0.8em;
                   7381:   vertical-align: top;
                   7382:   width: 150px;
                   7383:   border-top:1px solid $lg_border_color;
                   7384: }
                   7385: 
1.795     www      7386: td.LC_parm_overview_level_menu,
                   7387: td.LC_parm_overview_map_menu,
                   7388: td.LC_parm_overview_parm_selectors,
                   7389: td.LC_parm_overview_restrictions  {
1.396     albertel 7390:   border: 1px solid black;
                   7391:   border-collapse: collapse;
                   7392: }
1.795     www      7393: 
1.396     albertel 7394: table.LC_parm_overview_restrictions td {
                   7395:   border-width: 1px 4px 1px 4px;
                   7396:   border-style: solid;
                   7397:   border-color: $pgbg;
                   7398:   text-align: center;
                   7399: }
1.795     www      7400: 
1.396     albertel 7401: table.LC_parm_overview_restrictions th {
                   7402:   background: $tabbg;
                   7403:   border-width: 1px 4px 1px 4px;
                   7404:   border-style: solid;
                   7405:   border-color: $pgbg;
                   7406: }
1.795     www      7407: 
1.398     albertel 7408: table#LC_helpmenu {
1.803     bisitz   7409:   border: none;
1.398     albertel 7410:   height: 55px;
1.803     bisitz   7411:   border-spacing: 0;
1.398     albertel 7412: }
                   7413: 
                   7414: table#LC_helpmenu fieldset legend {
                   7415:   font-size: larger;
                   7416: }
1.795     www      7417: 
1.397     albertel 7418: table#LC_helpmenu_links {
                   7419:   width: 100%;
                   7420:   border: 1px solid black;
                   7421:   background: $pgbg;
1.803     bisitz   7422:   padding: 0;
1.397     albertel 7423:   border-spacing: 1px;
                   7424: }
1.795     www      7425: 
1.397     albertel 7426: table#LC_helpmenu_links tr td {
                   7427:   padding: 1px;
                   7428:   background: $tabbg;
1.399     albertel 7429:   text-align: center;
                   7430:   font-weight: bold;
1.397     albertel 7431: }
1.396     albertel 7432: 
1.795     www      7433: table#LC_helpmenu_links a:link,
                   7434: table#LC_helpmenu_links a:visited,
1.397     albertel 7435: table#LC_helpmenu_links a:active {
                   7436:   text-decoration: none;
                   7437:   color: $font;
                   7438: }
1.795     www      7439: 
1.397     albertel 7440: table#LC_helpmenu_links a:hover {
                   7441:   text-decoration: underline;
                   7442:   color: $vlink;
                   7443: }
1.396     albertel 7444: 
1.417     albertel 7445: .LC_chrt_popup_exists {
                   7446:   border: 1px solid #339933;
                   7447:   margin: -1px;
                   7448: }
1.795     www      7449: 
1.417     albertel 7450: .LC_chrt_popup_up {
                   7451:   border: 1px solid yellow;
                   7452:   margin: -1px;
                   7453: }
1.795     www      7454: 
1.417     albertel 7455: .LC_chrt_popup {
                   7456:   border: 1px solid #8888FF;
                   7457:   background: #CCCCFF;
                   7458: }
1.795     www      7459: 
1.421     albertel 7460: table.LC_pick_box {
                   7461:   border-collapse: separate;
                   7462:   background: white;
                   7463:   border: 1px solid black;
                   7464:   border-spacing: 1px;
                   7465: }
1.795     www      7466: 
1.421     albertel 7467: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7468:   background: $sidebg;
1.421     albertel 7469:   font-weight: bold;
1.900     bisitz   7470:   text-align: left;
1.740     bisitz   7471:   vertical-align: top;
1.421     albertel 7472:   width: 184px;
                   7473:   padding: 8px;
                   7474: }
1.795     www      7475: 
1.579     raeburn  7476: table.LC_pick_box td.LC_pick_box_value {
                   7477:   text-align: left;
                   7478:   padding: 8px;
                   7479: }
1.795     www      7480: 
1.579     raeburn  7481: table.LC_pick_box td.LC_pick_box_select {
                   7482:   text-align: left;
                   7483:   padding: 8px;
                   7484: }
1.795     www      7485: 
1.424     albertel 7486: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7487:   padding: 0;
1.421     albertel 7488:   height: 1px;
                   7489:   background: black;
                   7490: }
1.795     www      7491: 
1.421     albertel 7492: table.LC_pick_box td.LC_pick_box_submit {
                   7493:   text-align: right;
                   7494: }
1.795     www      7495: 
1.579     raeburn  7496: table.LC_pick_box td.LC_evenrow_value {
                   7497:   text-align: left;
                   7498:   padding: 8px;
                   7499:   background-color: $data_table_light;
                   7500: }
1.795     www      7501: 
1.579     raeburn  7502: table.LC_pick_box td.LC_oddrow_value {
                   7503:   text-align: left;
                   7504:   padding: 8px;
                   7505:   background-color: $data_table_light;
                   7506: }
1.795     www      7507: 
1.579     raeburn  7508: span.LC_helpform_receipt_cat {
                   7509:   font-weight: bold;
                   7510: }
1.795     www      7511: 
1.424     albertel 7512: table.LC_group_priv_box {
                   7513:   background: white;
                   7514:   border: 1px solid black;
                   7515:   border-spacing: 1px;
                   7516: }
1.795     www      7517: 
1.424     albertel 7518: table.LC_group_priv_box td.LC_pick_box_title {
                   7519:   background: $tabbg;
                   7520:   font-weight: bold;
                   7521:   text-align: right;
                   7522:   width: 184px;
                   7523: }
1.795     www      7524: 
1.424     albertel 7525: table.LC_group_priv_box td.LC_groups_fixed {
                   7526:   background: $data_table_light;
                   7527:   text-align: center;
                   7528: }
1.795     www      7529: 
1.424     albertel 7530: table.LC_group_priv_box td.LC_groups_optional {
                   7531:   background: $data_table_dark;
                   7532:   text-align: center;
                   7533: }
1.795     www      7534: 
1.424     albertel 7535: table.LC_group_priv_box td.LC_groups_functionality {
                   7536:   background: $data_table_darker;
                   7537:   text-align: center;
                   7538:   font-weight: bold;
                   7539: }
1.795     www      7540: 
1.424     albertel 7541: table.LC_group_priv td {
                   7542:   text-align: left;
1.803     bisitz   7543:   padding: 0;
1.424     albertel 7544: }
                   7545: 
                   7546: .LC_navbuttons {
                   7547:   margin: 2ex 0ex 2ex 0ex;
                   7548: }
1.795     www      7549: 
1.423     albertel 7550: .LC_topic_bar {
                   7551:   font-weight: bold;
                   7552:   background: $tabbg;
1.918     wenzelju 7553:   margin: 1em 0em 1em 2em;
1.805     bisitz   7554:   padding: 3px;
1.918     wenzelju 7555:   font-size: 1.2em;
1.423     albertel 7556: }
1.795     www      7557: 
1.423     albertel 7558: .LC_topic_bar span {
1.918     wenzelju 7559:   left: 0.5em;
                   7560:   position: absolute;
1.423     albertel 7561:   vertical-align: middle;
1.918     wenzelju 7562:   font-size: 1.2em;
1.423     albertel 7563: }
1.795     www      7564: 
1.423     albertel 7565: table.LC_course_group_status {
                   7566:   margin: 20px;
                   7567: }
1.795     www      7568: 
1.423     albertel 7569: table.LC_status_selector td {
                   7570:   vertical-align: top;
                   7571:   text-align: center;
1.424     albertel 7572:   padding: 4px;
                   7573: }
1.795     www      7574: 
1.599     albertel 7575: div.LC_feedback_link {
1.616     albertel 7576:   clear: both;
1.829     kalberla 7577:   background: $sidebg;
1.779     bisitz   7578:   width: 100%;
1.829     kalberla 7579:   padding-bottom: 10px;
                   7580:   border: 1px $tabbg solid;
1.833     kalberla 7581:   height: 22px;
                   7582:   line-height: 22px;
                   7583:   padding-top: 5px;
                   7584: }
                   7585: 
                   7586: div.LC_feedback_link img {
                   7587:   height: 22px;
1.867     kalberla 7588:   vertical-align:middle;
1.829     kalberla 7589: }
                   7590: 
1.911     bisitz   7591: div.LC_feedback_link a {
1.829     kalberla 7592:   text-decoration: none;
1.489     raeburn  7593: }
1.795     www      7594: 
1.867     kalberla 7595: div.LC_comblock {
1.911     bisitz   7596:   display:inline;
1.867     kalberla 7597:   color:$font;
                   7598:   font-size:90%;
                   7599: }
                   7600: 
                   7601: div.LC_feedback_link div.LC_comblock {
                   7602:   padding-left:5px;
                   7603: }
                   7604: 
                   7605: div.LC_feedback_link div.LC_comblock a {
                   7606:   color:$font;
                   7607: }
                   7608: 
1.489     raeburn  7609: span.LC_feedback_link {
1.858     bisitz   7610:   /* background: $feedback_link_bg; */
1.599     albertel 7611:   font-size: larger;
                   7612: }
1.795     www      7613: 
1.599     albertel 7614: span.LC_message_link {
1.858     bisitz   7615:   /* background: $feedback_link_bg; */
1.599     albertel 7616:   font-size: larger;
                   7617:   position: absolute;
                   7618:   right: 1em;
1.489     raeburn  7619: }
1.421     albertel 7620: 
1.515     albertel 7621: table.LC_prior_tries {
1.524     albertel 7622:   border: 1px solid #000000;
                   7623:   border-collapse: separate;
                   7624:   border-spacing: 1px;
1.515     albertel 7625: }
1.523     albertel 7626: 
1.515     albertel 7627: table.LC_prior_tries td {
1.524     albertel 7628:   padding: 2px;
1.515     albertel 7629: }
1.523     albertel 7630: 
                   7631: .LC_answer_correct {
1.795     www      7632:   background: lightgreen;
                   7633:   color: darkgreen;
                   7634:   padding: 6px;
1.523     albertel 7635: }
1.795     www      7636: 
1.523     albertel 7637: .LC_answer_charged_try {
1.797     www      7638:   background: #FFAAAA;
1.795     www      7639:   color: darkred;
                   7640:   padding: 6px;
1.523     albertel 7641: }
1.795     www      7642: 
1.779     bisitz   7643: .LC_answer_not_charged_try,
1.523     albertel 7644: .LC_answer_no_grade,
                   7645: .LC_answer_late {
1.795     www      7646:   background: lightyellow;
1.523     albertel 7647:   color: black;
1.795     www      7648:   padding: 6px;
1.523     albertel 7649: }
1.795     www      7650: 
1.523     albertel 7651: .LC_answer_previous {
1.795     www      7652:   background: lightblue;
                   7653:   color: darkblue;
                   7654:   padding: 6px;
1.523     albertel 7655: }
1.795     www      7656: 
1.779     bisitz   7657: .LC_answer_no_message {
1.777     tempelho 7658:   background: #FFFFFF;
                   7659:   color: black;
1.795     www      7660:   padding: 6px;
1.779     bisitz   7661: }
1.795     www      7662: 
1.1075.2.140  raeburn  7663: .LC_answer_unknown,
                   7664: .LC_answer_warning {
1.779     bisitz   7665:   background: orange;
                   7666:   color: black;
1.795     www      7667:   padding: 6px;
1.777     tempelho 7668: }
1.795     www      7669: 
1.529     albertel 7670: span.LC_prior_numerical,
                   7671: span.LC_prior_string,
                   7672: span.LC_prior_custom,
                   7673: span.LC_prior_reaction,
                   7674: span.LC_prior_math {
1.925     bisitz   7675:   font-family: $mono;
1.523     albertel 7676:   white-space: pre;
                   7677: }
                   7678: 
1.525     albertel 7679: span.LC_prior_string {
1.925     bisitz   7680:   font-family: $mono;
1.525     albertel 7681:   white-space: pre;
                   7682: }
                   7683: 
1.523     albertel 7684: table.LC_prior_option {
                   7685:   width: 100%;
                   7686:   border-collapse: collapse;
                   7687: }
1.795     www      7688: 
1.911     bisitz   7689: table.LC_prior_rank,
1.795     www      7690: table.LC_prior_match {
1.528     albertel 7691:   border-collapse: collapse;
                   7692: }
1.795     www      7693: 
1.528     albertel 7694: table.LC_prior_option tr td,
                   7695: table.LC_prior_rank tr td,
                   7696: table.LC_prior_match tr td {
1.524     albertel 7697:   border: 1px solid #000000;
1.515     albertel 7698: }
                   7699: 
1.855     bisitz   7700: .LC_nobreak {
1.544     albertel 7701:   white-space: nowrap;
1.519     raeburn  7702: }
                   7703: 
1.576     raeburn  7704: span.LC_cusr_emph {
                   7705:   font-style: italic;
                   7706: }
                   7707: 
1.633     raeburn  7708: span.LC_cusr_subheading {
                   7709:   font-weight: normal;
                   7710:   font-size: 85%;
                   7711: }
                   7712: 
1.861     bisitz   7713: div.LC_docs_entry_move {
1.859     bisitz   7714:   border: 1px solid #BBBBBB;
1.545     albertel 7715:   background: #DDDDDD;
1.861     bisitz   7716:   width: 22px;
1.859     bisitz   7717:   padding: 1px;
                   7718:   margin: 0;
1.545     albertel 7719: }
                   7720: 
1.861     bisitz   7721: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7722: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7723:   font-size: x-small;
                   7724: }
1.795     www      7725: 
1.861     bisitz   7726: .LC_docs_entry_parameter {
                   7727:   white-space: nowrap;
                   7728: }
                   7729: 
1.544     albertel 7730: .LC_docs_copy {
1.545     albertel 7731:   color: #000099;
1.544     albertel 7732: }
1.795     www      7733: 
1.544     albertel 7734: .LC_docs_cut {
1.545     albertel 7735:   color: #550044;
1.544     albertel 7736: }
1.795     www      7737: 
1.544     albertel 7738: .LC_docs_rename {
1.545     albertel 7739:   color: #009900;
1.544     albertel 7740: }
1.795     www      7741: 
1.544     albertel 7742: .LC_docs_remove {
1.545     albertel 7743:   color: #990000;
                   7744: }
                   7745: 
1.1075.2.134  raeburn  7746: .LC_domprefs_email,
1.547     albertel 7747: .LC_docs_reinit_warn,
                   7748: .LC_docs_ext_edit {
                   7749:   font-size: x-small;
                   7750: }
                   7751: 
1.545     albertel 7752: table.LC_docs_adddocs td,
                   7753: table.LC_docs_adddocs th {
                   7754:   border: 1px solid #BBBBBB;
                   7755:   padding: 4px;
                   7756:   background: #DDDDDD;
1.543     albertel 7757: }
                   7758: 
1.584     albertel 7759: table.LC_sty_begin {
                   7760:   background: #BBFFBB;
                   7761: }
1.795     www      7762: 
1.584     albertel 7763: table.LC_sty_end {
                   7764:   background: #FFBBBB;
                   7765: }
                   7766: 
1.589     raeburn  7767: table.LC_double_column {
1.803     bisitz   7768:   border-width: 0;
1.589     raeburn  7769:   border-collapse: collapse;
                   7770:   width: 100%;
                   7771:   padding: 2px;
                   7772: }
                   7773: 
                   7774: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7775:   top: 2px;
1.589     raeburn  7776:   left: 2px;
                   7777:   width: 47%;
                   7778:   vertical-align: top;
                   7779: }
                   7780: 
                   7781: table.LC_double_column tr td.LC_right_col {
                   7782:   top: 2px;
1.779     bisitz   7783:   right: 2px;
1.589     raeburn  7784:   width: 47%;
                   7785:   vertical-align: top;
                   7786: }
                   7787: 
1.591     raeburn  7788: div.LC_left_float {
                   7789:   float: left;
                   7790:   padding-right: 5%;
1.597     albertel 7791:   padding-bottom: 4px;
1.591     raeburn  7792: }
                   7793: 
                   7794: div.LC_clear_float_header {
1.597     albertel 7795:   padding-bottom: 2px;
1.591     raeburn  7796: }
                   7797: 
                   7798: div.LC_clear_float_footer {
1.597     albertel 7799:   padding-top: 10px;
1.591     raeburn  7800:   clear: both;
                   7801: }
                   7802: 
1.597     albertel 7803: div.LC_grade_show_user {
1.941     bisitz   7804: /*  border-left: 5px solid $sidebg; */
                   7805:   border-top: 5px solid #000000;
                   7806:   margin: 50px 0 0 0;
1.936     bisitz   7807:   padding: 15px 0 5px 10px;
1.597     albertel 7808: }
1.795     www      7809: 
1.936     bisitz   7810: div.LC_grade_show_user_odd_row {
1.941     bisitz   7811: /*  border-left: 5px solid #000000; */
                   7812: }
                   7813: 
                   7814: div.LC_grade_show_user div.LC_Box {
                   7815:   margin-right: 50px;
1.597     albertel 7816: }
                   7817: 
                   7818: div.LC_grade_submissions,
                   7819: div.LC_grade_message_center,
1.936     bisitz   7820: div.LC_grade_info_links {
1.597     albertel 7821:   margin: 5px;
                   7822:   width: 99%;
                   7823:   background: #FFFFFF;
                   7824: }
1.795     www      7825: 
1.597     albertel 7826: div.LC_grade_submissions_header,
1.936     bisitz   7827: div.LC_grade_message_center_header {
1.705     tempelho 7828:   font-weight: bold;
                   7829:   font-size: large;
1.597     albertel 7830: }
1.795     www      7831: 
1.597     albertel 7832: div.LC_grade_submissions_body,
1.936     bisitz   7833: div.LC_grade_message_center_body {
1.597     albertel 7834:   border: 1px solid black;
                   7835:   width: 99%;
                   7836:   background: #FFFFFF;
                   7837: }
1.795     www      7838: 
1.613     albertel 7839: table.LC_scantron_action {
                   7840:   width: 100%;
                   7841: }
1.795     www      7842: 
1.613     albertel 7843: table.LC_scantron_action tr th {
1.698     harmsja  7844:   font-weight:bold;
                   7845:   font-style:normal;
1.613     albertel 7846: }
1.795     www      7847: 
1.779     bisitz   7848: .LC_edit_problem_header,
1.614     albertel 7849: div.LC_edit_problem_footer {
1.705     tempelho 7850:   font-weight: normal;
                   7851:   font-size:  medium;
1.602     albertel 7852:   margin: 2px;
1.1060    bisitz   7853:   background-color: $sidebg;
1.600     albertel 7854: }
1.795     www      7855: 
1.600     albertel 7856: div.LC_edit_problem_header,
1.602     albertel 7857: div.LC_edit_problem_header div,
1.614     albertel 7858: div.LC_edit_problem_footer,
                   7859: div.LC_edit_problem_footer div,
1.602     albertel 7860: div.LC_edit_problem_editxml_header,
                   7861: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7862:   z-index: 100;
1.600     albertel 7863: }
1.795     www      7864: 
1.600     albertel 7865: div.LC_edit_problem_header_title {
1.705     tempelho 7866:   font-weight: bold;
                   7867:   font-size: larger;
1.602     albertel 7868:   background: $tabbg;
                   7869:   padding: 3px;
1.1060    bisitz   7870:   margin: 0 0 5px 0;
1.602     albertel 7871: }
1.795     www      7872: 
1.602     albertel 7873: table.LC_edit_problem_header_title {
                   7874:   width: 100%;
1.600     albertel 7875:   background: $tabbg;
1.602     albertel 7876: }
                   7877: 
1.1075.2.112  raeburn  7878: div.LC_edit_actionbar {
                   7879:     background-color: $sidebg;
                   7880:     margin: 0;
                   7881:     padding: 0;
                   7882:     line-height: 200%;
1.602     albertel 7883: }
1.795     www      7884: 
1.1075.2.112  raeburn  7885: div.LC_edit_actionbar div{
                   7886:     padding: 0;
                   7887:     margin: 0;
                   7888:     display: inline-block;
1.600     albertel 7889: }
1.795     www      7890: 
1.1075.2.34  raeburn  7891: .LC_edit_opt {
                   7892:   padding-left: 1em;
                   7893:   white-space: nowrap;
                   7894: }
                   7895: 
1.1075.2.57  raeburn  7896: .LC_edit_problem_latexhelper{
                   7897:     text-align: right;
                   7898: }
                   7899: 
                   7900: #LC_edit_problem_colorful div{
                   7901:     margin-left: 40px;
                   7902: }
                   7903: 
1.1075.2.112  raeburn  7904: #LC_edit_problem_codemirror div{
                   7905:     margin-left: 0px;
                   7906: }
                   7907: 
1.911     bisitz   7908: img.stift {
1.803     bisitz   7909:   border-width: 0;
                   7910:   vertical-align: middle;
1.677     riegler  7911: }
1.680     riegler  7912: 
1.923     bisitz   7913: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7914:   vertical-align: top;
1.777     tempelho 7915: }
1.795     www      7916: 
1.716     raeburn  7917: div.LC_createcourse {
1.911     bisitz   7918:   margin: 10px 10px 10px 10px;
1.716     raeburn  7919: }
                   7920: 
1.917     raeburn  7921: .LC_dccid {
1.1075.2.38  raeburn  7922:   float: right;
1.917     raeburn  7923:   margin: 0.2em 0 0 0;
                   7924:   padding: 0;
                   7925:   font-size: 90%;
                   7926:   display:none;
                   7927: }
                   7928: 
1.897     wenzelju 7929: ol.LC_primary_menu a:hover,
1.721     harmsja  7930: ol#LC_MenuBreadcrumbs a:hover,
                   7931: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7932: ul#LC_secondary_menu a:hover,
1.721     harmsja  7933: .LC_FormSectionClearButton input:hover
1.795     www      7934: ul.LC_TabContent   li:hover a {
1.952     onken    7935:   color:$button_hover;
1.911     bisitz   7936:   text-decoration:none;
1.693     droeschl 7937: }
                   7938: 
1.779     bisitz   7939: h1 {
1.911     bisitz   7940:   padding: 0;
                   7941:   line-height:130%;
1.693     droeschl 7942: }
1.698     harmsja  7943: 
1.911     bisitz   7944: h2,
                   7945: h3,
                   7946: h4,
                   7947: h5,
                   7948: h6 {
                   7949:   margin: 5px 0 5px 0;
                   7950:   padding: 0;
                   7951:   line-height:130%;
1.693     droeschl 7952: }
1.795     www      7953: 
                   7954: .LC_hcell {
1.911     bisitz   7955:   padding:3px 15px 3px 15px;
                   7956:   margin: 0;
                   7957:   background-color:$tabbg;
                   7958:   color:$fontmenu;
                   7959:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7960: }
1.795     www      7961: 
1.840     bisitz   7962: .LC_Box > .LC_hcell {
1.911     bisitz   7963:   margin: 0 -10px 10px -10px;
1.835     bisitz   7964: }
                   7965: 
1.721     harmsja  7966: .LC_noBorder {
1.911     bisitz   7967:   border: 0;
1.698     harmsja  7968: }
1.693     droeschl 7969: 
1.721     harmsja  7970: .LC_FormSectionClearButton input {
1.911     bisitz   7971:   background-color:transparent;
                   7972:   border: none;
                   7973:   cursor:pointer;
                   7974:   text-decoration:underline;
1.693     droeschl 7975: }
1.763     bisitz   7976: 
                   7977: .LC_help_open_topic {
1.911     bisitz   7978:   color: #FFFFFF;
                   7979:   background-color: #EEEEFF;
                   7980:   margin: 1px;
                   7981:   padding: 4px;
                   7982:   border: 1px solid #000033;
                   7983:   white-space: nowrap;
                   7984:   /* vertical-align: middle; */
1.759     neumanie 7985: }
1.693     droeschl 7986: 
1.911     bisitz   7987: dl,
                   7988: ul,
                   7989: div,
                   7990: fieldset {
                   7991:   margin: 10px 10px 10px 0;
                   7992:   /* overflow: hidden; */
1.693     droeschl 7993: }
1.795     www      7994: 
1.1075.2.161.  .18(raeb 7995:-23): fieldset#LC_selectuser {
                   7996:-23):     margin: 0;
                   7997:-23):     padding: 0;
                   7998:-23): }
                   7999:-23): 
1.1075.2.90  raeburn  8000: article.geogebraweb div {
                   8001:     margin: 0;
                   8002: }
                   8003: 
1.838     bisitz   8004: fieldset > legend {
1.911     bisitz   8005:   font-weight: bold;
                   8006:   padding: 0 5px 0 5px;
1.838     bisitz   8007: }
                   8008: 
1.813     bisitz   8009: #LC_nav_bar {
1.911     bisitz   8010:   float: left;
1.995     raeburn  8011:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8012:   margin: 0 0 2px 0;
1.807     droeschl 8013: }
                   8014: 
1.916     droeschl 8015: #LC_realm {
                   8016:   margin: 0.2em 0 0 0;
                   8017:   padding: 0;
                   8018:   font-weight: bold;
                   8019:   text-align: center;
1.995     raeburn  8020:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8021: }
                   8022: 
1.911     bisitz   8023: #LC_nav_bar em {
                   8024:   font-weight: bold;
                   8025:   font-style: normal;
1.807     droeschl 8026: }
                   8027: 
1.897     wenzelju 8028: ol.LC_primary_menu {
1.934     droeschl 8029:   margin: 0;
1.1075.2.2  raeburn  8030:   padding: 0;
1.807     droeschl 8031: }
                   8032: 
1.852     droeschl 8033: ol#LC_PathBreadcrumbs {
1.911     bisitz   8034:   margin: 0;
1.693     droeschl 8035: }
                   8036: 
1.897     wenzelju 8037: ol.LC_primary_menu li {
1.1075.2.2  raeburn  8038:   color: RGB(80, 80, 80);
                   8039:   vertical-align: middle;
                   8040:   text-align: left;
                   8041:   list-style: none;
1.1075.2.112  raeburn  8042:   position: relative;
1.1075.2.2  raeburn  8043:   float: left;
1.1075.2.112  raeburn  8044:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8045:   line-height: 1.5em;
1.1075.2.2  raeburn  8046: }
                   8047: 
1.1075.2.113  raeburn  8048: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  8049: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  8050:   display: block;
                   8051:   margin: 0;
                   8052:   padding: 0 5px 0 10px;
                   8053:   text-decoration: none;
                   8054: }
                   8055: 
1.1075.2.112  raeburn  8056: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8057:   display: inline-block;
                   8058:   width: 95%;
                   8059:   text-align: left;
                   8060: }
                   8061: 
                   8062: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8063:   display: inline-block;
                   8064:   width: 5%;
                   8065:   float: right;
                   8066:   text-align: right;
                   8067:   font-size: 70%;
                   8068: }
                   8069: 
                   8070: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  8071:   display: none;
1.1075.2.112  raeburn  8072:   width: 15em;
1.1075.2.2  raeburn  8073:   background-color: $data_table_light;
1.1075.2.112  raeburn  8074:   position: absolute;
                   8075:   top: 100%;
                   8076: }
                   8077: 
                   8078: ol.LC_primary_menu ul ul {
                   8079:   left: 100%;
                   8080:   top: 0;
1.1075.2.2  raeburn  8081: }
                   8082: 
1.1075.2.112  raeburn  8083: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  8084:   display: block;
                   8085:   position: absolute;
                   8086:   margin: 0;
                   8087:   padding: 0;
1.1075.2.5  raeburn  8088:   z-index: 2;
1.1075.2.2  raeburn  8089: }
                   8090: 
                   8091: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  8092: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  8093:   font-size: 90%;
1.911     bisitz   8094:   vertical-align: top;
1.1075.2.2  raeburn  8095:   float: none;
1.1075.2.5  raeburn  8096:   border-left: 1px solid black;
                   8097:   border-right: 1px solid black;
1.1075.2.112  raeburn  8098: /* A dark bottom border to visualize different menu options;
                   8099: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8100:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  8101: }
                   8102: 
1.1075.2.112  raeburn  8103: ol.LC_primary_menu li li p:hover {
                   8104:   color:$button_hover;
                   8105:   text-decoration:none;
                   8106:   background-color:$data_table_dark;
1.1075.2.2  raeburn  8107: }
                   8108: 
                   8109: ol.LC_primary_menu li li a:hover {
                   8110:    color:$button_hover;
                   8111:    background-color:$data_table_dark;
1.693     droeschl 8112: }
                   8113: 
1.1075.2.112  raeburn  8114: /* Font-size equal to the size of the predecessors*/
                   8115: ol.LC_primary_menu li:hover li li {
                   8116:   font-size: 100%;
                   8117: }
                   8118: 
1.897     wenzelju 8119: ol.LC_primary_menu li img {
1.911     bisitz   8120:   vertical-align: bottom;
1.934     droeschl 8121:   height: 1.1em;
1.1075.2.3  raeburn  8122:   margin: 0.2em 0 0 0;
1.693     droeschl 8123: }
                   8124: 
1.897     wenzelju 8125: ol.LC_primary_menu a {
1.911     bisitz   8126:   color: RGB(80, 80, 80);
                   8127:   text-decoration: none;
1.693     droeschl 8128: }
1.795     www      8129: 
1.949     droeschl 8130: ol.LC_primary_menu a.LC_new_message {
                   8131:   font-weight:bold;
                   8132:   color: darkred;
                   8133: }
                   8134: 
1.975     raeburn  8135: ol.LC_docs_parameters {
                   8136:   margin-left: 0;
                   8137:   padding: 0;
                   8138:   list-style: none;
                   8139: }
                   8140: 
                   8141: ol.LC_docs_parameters li {
                   8142:   margin: 0;
                   8143:   padding-right: 20px;
                   8144:   display: inline;
                   8145: }
                   8146: 
1.976     raeburn  8147: ol.LC_docs_parameters li:before {
                   8148:   content: "\\002022 \\0020";
                   8149: }
                   8150: 
                   8151: li.LC_docs_parameters_title {
                   8152:   font-weight: bold;
                   8153: }
                   8154: 
                   8155: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8156:   content: "";
                   8157: }
                   8158: 
1.897     wenzelju 8159: ul#LC_secondary_menu {
1.1075.2.23  raeburn  8160:   clear: right;
1.911     bisitz   8161:   color: $fontmenu;
                   8162:   background: $tabbg;
                   8163:   list-style: none;
                   8164:   padding: 0;
                   8165:   margin: 0;
                   8166:   width: 100%;
1.995     raeburn  8167:   text-align: left;
1.1075.2.4  raeburn  8168:   float: left;
1.808     droeschl 8169: }
                   8170: 
1.897     wenzelju 8171: ul#LC_secondary_menu li {
1.911     bisitz   8172:   font-weight: bold;
                   8173:   line-height: 1.8em;
                   8174:   border-right: 1px solid black;
1.1075.2.4  raeburn  8175:   float: left;
                   8176: }
                   8177: 
                   8178: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8179:   background-color: $data_table_light;
                   8180: }
                   8181: 
                   8182: ul#LC_secondary_menu li a {
                   8183:   padding: 0 0.8em;
                   8184: }
                   8185: 
                   8186: ul#LC_secondary_menu li ul {
                   8187:   display: none;
                   8188: }
                   8189: 
                   8190: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8191:   display: block;
                   8192:   position: absolute;
                   8193:   margin: 0;
                   8194:   padding: 0;
                   8195:   list-style:none;
                   8196:   float: none;
                   8197:   background-color: $data_table_light;
1.1075.2.5  raeburn  8198:   z-index: 2;
1.1075.2.10  raeburn  8199:   margin-left: -1px;
1.1075.2.4  raeburn  8200: }
                   8201: 
                   8202: ul#LC_secondary_menu li ul li {
                   8203:   font-size: 90%;
                   8204:   vertical-align: top;
                   8205:   border-left: 1px solid black;
                   8206:   border-right: 1px solid black;
1.1075.2.33  raeburn  8207:   background-color: $data_table_light;
1.1075.2.4  raeburn  8208:   list-style:none;
                   8209:   float: none;
                   8210: }
                   8211: 
                   8212: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8213:   background-color: $data_table_dark;
1.807     droeschl 8214: }
                   8215: 
1.847     tempelho 8216: ul.LC_TabContent {
1.911     bisitz   8217:   display:block;
                   8218:   background: $sidebg;
                   8219:   border-bottom: solid 1px $lg_border_color;
                   8220:   list-style:none;
1.1020    raeburn  8221:   margin: -1px -10px 0 -10px;
1.911     bisitz   8222:   padding: 0;
1.693     droeschl 8223: }
                   8224: 
1.795     www      8225: ul.LC_TabContent li,
                   8226: ul.LC_TabContentBigger li {
1.911     bisitz   8227:   float:left;
1.741     harmsja  8228: }
1.795     www      8229: 
1.897     wenzelju 8230: ul#LC_secondary_menu li a {
1.911     bisitz   8231:   color: $fontmenu;
                   8232:   text-decoration: none;
1.693     droeschl 8233: }
1.795     www      8234: 
1.721     harmsja  8235: ul.LC_TabContent {
1.952     onken    8236:   min-height:20px;
1.721     harmsja  8237: }
1.795     www      8238: 
                   8239: ul.LC_TabContent li {
1.911     bisitz   8240:   vertical-align:middle;
1.959     onken    8241:   padding: 0 16px 0 10px;
1.911     bisitz   8242:   background-color:$tabbg;
                   8243:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8244:   border-left: solid 1px $font;
1.721     harmsja  8245: }
1.795     www      8246: 
1.847     tempelho 8247: ul.LC_TabContent .right {
1.911     bisitz   8248:   float:right;
1.847     tempelho 8249: }
                   8250: 
1.911     bisitz   8251: ul.LC_TabContent li a,
                   8252: ul.LC_TabContent li {
                   8253:   color:rgb(47,47,47);
                   8254:   text-decoration:none;
                   8255:   font-size:95%;
                   8256:   font-weight:bold;
1.952     onken    8257:   min-height:20px;
                   8258: }
                   8259: 
1.959     onken    8260: ul.LC_TabContent li a:hover,
                   8261: ul.LC_TabContent li a:focus {
1.952     onken    8262:   color: $button_hover;
1.959     onken    8263:   background:none;
                   8264:   outline:none;
1.952     onken    8265: }
                   8266: 
                   8267: ul.LC_TabContent li:hover {
                   8268:   color: $button_hover;
                   8269:   cursor:pointer;
1.721     harmsja  8270: }
1.795     www      8271: 
1.911     bisitz   8272: ul.LC_TabContent li.active {
1.952     onken    8273:   color: $font;
1.911     bisitz   8274:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8275:   border-bottom:solid 1px #FFFFFF;
                   8276:   cursor: default;
1.744     ehlerst  8277: }
1.795     www      8278: 
1.959     onken    8279: ul.LC_TabContent li.active a {
                   8280:   color:$font;
                   8281:   background:#FFFFFF;
                   8282:   outline: none;
                   8283: }
1.1047    raeburn  8284: 
                   8285: ul.LC_TabContent li.goback {
                   8286:   float: left;
                   8287:   border-left: none;
                   8288: }
                   8289: 
1.870     tempelho 8290: #maincoursedoc {
1.911     bisitz   8291:   clear:both;
1.870     tempelho 8292: }
                   8293: 
                   8294: ul.LC_TabContentBigger {
1.911     bisitz   8295:   display:block;
                   8296:   list-style:none;
                   8297:   padding: 0;
1.870     tempelho 8298: }
                   8299: 
1.795     www      8300: ul.LC_TabContentBigger li {
1.911     bisitz   8301:   vertical-align:bottom;
                   8302:   height: 30px;
                   8303:   font-size:110%;
                   8304:   font-weight:bold;
                   8305:   color: #737373;
1.841     tempelho 8306: }
                   8307: 
1.957     onken    8308: ul.LC_TabContentBigger li.active {
                   8309:   position: relative;
                   8310:   top: 1px;
                   8311: }
                   8312: 
1.870     tempelho 8313: ul.LC_TabContentBigger li a {
1.911     bisitz   8314:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8315:   height: 30px;
                   8316:   line-height: 30px;
                   8317:   text-align: center;
                   8318:   display: block;
                   8319:   text-decoration: none;
1.958     onken    8320:   outline: none;  
1.741     harmsja  8321: }
1.795     www      8322: 
1.870     tempelho 8323: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8324:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8325:   color:$font;
1.744     ehlerst  8326: }
1.795     www      8327: 
1.870     tempelho 8328: ul.LC_TabContentBigger li b {
1.911     bisitz   8329:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8330:   display: block;
                   8331:   float: left;
                   8332:   padding: 0 30px;
1.957     onken    8333:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8334: }
                   8335: 
1.956     onken    8336: ul.LC_TabContentBigger li:hover b {
                   8337:   color:$button_hover;
                   8338: }
                   8339: 
1.870     tempelho 8340: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8341:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8342:   color:$font;
1.957     onken    8343:   border: 0;
1.741     harmsja  8344: }
1.693     droeschl 8345: 
1.870     tempelho 8346: 
1.862     bisitz   8347: ul.LC_CourseBreadcrumbs {
                   8348:   background: $sidebg;
1.1020    raeburn  8349:   height: 2em;
1.862     bisitz   8350:   padding-left: 10px;
1.1020    raeburn  8351:   margin: 0;
1.862     bisitz   8352:   list-style-position: inside;
                   8353: }
                   8354: 
1.911     bisitz   8355: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8356: ol#LC_PathBreadcrumbs {
1.911     bisitz   8357:   padding-left: 10px;
                   8358:   margin: 0;
1.933     droeschl 8359:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8360: }
                   8361: 
1.911     bisitz   8362: ol#LC_MenuBreadcrumbs li,
                   8363: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8364: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8365:   display: inline;
1.933     droeschl 8366:   white-space: normal;  
1.693     droeschl 8367: }
                   8368: 
1.823     bisitz   8369: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8370: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8371:   text-decoration: none;
                   8372:   font-size:90%;
1.693     droeschl 8373: }
1.795     www      8374: 
1.969     droeschl 8375: ol#LC_MenuBreadcrumbs h1 {
                   8376:   display: inline;
                   8377:   font-size: 90%;
                   8378:   line-height: 2.5em;
                   8379:   margin: 0;
                   8380:   padding: 0;
                   8381: }
                   8382: 
1.795     www      8383: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8384:   text-decoration:none;
                   8385:   font-size:100%;
                   8386:   font-weight:bold;
1.693     droeschl 8387: }
1.795     www      8388: 
1.840     bisitz   8389: .LC_Box {
1.911     bisitz   8390:   border: solid 1px $lg_border_color;
                   8391:   padding: 0 10px 10px 10px;
1.746     neumanie 8392: }
1.795     www      8393: 
1.1020    raeburn  8394: .LC_DocsBox {
                   8395:   border: solid 1px $lg_border_color;
                   8396:   padding: 0 0 10px 10px;
                   8397: }
                   8398: 
1.795     www      8399: .LC_AboutMe_Image {
1.911     bisitz   8400:   float:left;
                   8401:   margin-right:10px;
1.747     neumanie 8402: }
1.795     www      8403: 
                   8404: .LC_Clear_AboutMe_Image {
1.911     bisitz   8405:   clear:left;
1.747     neumanie 8406: }
1.795     www      8407: 
1.721     harmsja  8408: dl.LC_ListStyleClean dt {
1.911     bisitz   8409:   padding-right: 5px;
                   8410:   display: table-header-group;
1.693     droeschl 8411: }
                   8412: 
1.721     harmsja  8413: dl.LC_ListStyleClean dd {
1.911     bisitz   8414:   display: table-row;
1.693     droeschl 8415: }
                   8416: 
1.721     harmsja  8417: .LC_ListStyleClean,
                   8418: .LC_ListStyleSimple,
                   8419: .LC_ListStyleNormal,
1.795     www      8420: .LC_ListStyleSpecial {
1.911     bisitz   8421:   /* display:block; */
                   8422:   list-style-position: inside;
                   8423:   list-style-type: none;
                   8424:   overflow: hidden;
                   8425:   padding: 0;
1.693     droeschl 8426: }
                   8427: 
1.721     harmsja  8428: .LC_ListStyleSimple li,
                   8429: .LC_ListStyleSimple dd,
                   8430: .LC_ListStyleNormal li,
                   8431: .LC_ListStyleNormal dd,
                   8432: .LC_ListStyleSpecial li,
1.795     www      8433: .LC_ListStyleSpecial dd {
1.911     bisitz   8434:   margin: 0;
                   8435:   padding: 5px 5px 5px 10px;
                   8436:   clear: both;
1.693     droeschl 8437: }
                   8438: 
1.721     harmsja  8439: .LC_ListStyleClean li,
                   8440: .LC_ListStyleClean dd {
1.911     bisitz   8441:   padding-top: 0;
                   8442:   padding-bottom: 0;
1.693     droeschl 8443: }
                   8444: 
1.721     harmsja  8445: .LC_ListStyleSimple dd,
1.795     www      8446: .LC_ListStyleSimple li {
1.911     bisitz   8447:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8448: }
                   8449: 
1.721     harmsja  8450: .LC_ListStyleSpecial li,
                   8451: .LC_ListStyleSpecial dd {
1.911     bisitz   8452:   list-style-type: none;
                   8453:   background-color: RGB(220, 220, 220);
                   8454:   margin-bottom: 4px;
1.693     droeschl 8455: }
                   8456: 
1.721     harmsja  8457: table.LC_SimpleTable {
1.911     bisitz   8458:   margin:5px;
                   8459:   border:solid 1px $lg_border_color;
1.795     www      8460: }
1.693     droeschl 8461: 
1.721     harmsja  8462: table.LC_SimpleTable tr {
1.911     bisitz   8463:   padding: 0;
                   8464:   border:solid 1px $lg_border_color;
1.693     droeschl 8465: }
1.795     www      8466: 
                   8467: table.LC_SimpleTable thead {
1.911     bisitz   8468:   background:rgb(220,220,220);
1.693     droeschl 8469: }
                   8470: 
1.721     harmsja  8471: div.LC_columnSection {
1.911     bisitz   8472:   display: block;
                   8473:   clear: both;
                   8474:   overflow: hidden;
                   8475:   margin: 0;
1.693     droeschl 8476: }
                   8477: 
1.721     harmsja  8478: div.LC_columnSection>* {
1.911     bisitz   8479:   float: left;
                   8480:   margin: 10px 20px 10px 0;
                   8481:   overflow:hidden;
1.693     droeschl 8482: }
1.721     harmsja  8483: 
1.795     www      8484: table em {
1.911     bisitz   8485:   font-weight: bold;
                   8486:   font-style: normal;
1.748     schulted 8487: }
1.795     www      8488: 
1.779     bisitz   8489: table.LC_tableBrowseRes,
1.795     www      8490: table.LC_tableOfContent {
1.911     bisitz   8491:   border:none;
                   8492:   border-spacing: 1px;
                   8493:   padding: 3px;
                   8494:   background-color: #FFFFFF;
                   8495:   font-size: 90%;
1.753     droeschl 8496: }
1.789     droeschl 8497: 
1.911     bisitz   8498: table.LC_tableOfContent {
                   8499:   border-collapse: collapse;
1.789     droeschl 8500: }
                   8501: 
1.771     droeschl 8502: table.LC_tableBrowseRes a,
1.768     schulted 8503: table.LC_tableOfContent a {
1.911     bisitz   8504:   background-color: transparent;
                   8505:   text-decoration: none;
1.753     droeschl 8506: }
                   8507: 
1.795     www      8508: table.LC_tableOfContent img {
1.911     bisitz   8509:   border: none;
                   8510:   height: 1.3em;
                   8511:   vertical-align: text-bottom;
                   8512:   margin-right: 0.3em;
1.753     droeschl 8513: }
1.757     schulted 8514: 
1.795     www      8515: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8516:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8517: }
                   8518: 
1.795     www      8519: a#LC_content_toolbar_everything {
1.911     bisitz   8520:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8521: }
                   8522: 
1.795     www      8523: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8524:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8525: }
                   8526: 
1.795     www      8527: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8528:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8529: }
                   8530: 
1.795     www      8531: a#LC_content_toolbar_changefolder {
1.911     bisitz   8532:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8533: }
                   8534: 
1.795     www      8535: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8536:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8537: }
                   8538: 
1.1043    raeburn  8539: a#LC_content_toolbar_edittoplevel {
                   8540:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8541: }
                   8542: 
1.1075.2.161.  .12(raeb 8543:-23): a#LC_content_toolbar_printout {
                   8544:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8545:-23): }
                   8546:-23): 
1.795     www      8547: ul#LC_toolbar li a:hover {
1.911     bisitz   8548:   background-position: bottom center;
1.757     schulted 8549: }
                   8550: 
1.795     www      8551: ul#LC_toolbar {
1.911     bisitz   8552:   padding: 0;
                   8553:   margin: 2px;
                   8554:   list-style:none;
                   8555:   position:relative;
                   8556:   background-color:white;
1.1075.2.9  raeburn  8557:   overflow: auto;
1.757     schulted 8558: }
                   8559: 
1.795     www      8560: ul#LC_toolbar li {
1.911     bisitz   8561:   border:1px solid white;
                   8562:   padding: 0;
                   8563:   margin: 0;
                   8564:   float: left;
                   8565:   display:inline;
                   8566:   vertical-align:middle;
1.1075.2.9  raeburn  8567:   white-space: nowrap;
1.911     bisitz   8568: }
1.757     schulted 8569: 
1.783     amueller 8570: 
1.795     www      8571: a.LC_toolbarItem {
1.911     bisitz   8572:   display:block;
                   8573:   padding: 0;
                   8574:   margin: 0;
                   8575:   height: 32px;
                   8576:   width: 32px;
                   8577:   color:white;
                   8578:   border: none;
                   8579:   background-repeat:no-repeat;
                   8580:   background-color:transparent;
1.757     schulted 8581: }
                   8582: 
1.915     droeschl 8583: ul.LC_funclist {
                   8584:     margin: 0;
                   8585:     padding: 0.5em 1em 0.5em 0;
                   8586: }
                   8587: 
1.933     droeschl 8588: ul.LC_funclist > li:first-child {
                   8589:     font-weight:bold; 
                   8590:     margin-left:0.8em;
                   8591: }
                   8592: 
1.915     droeschl 8593: ul.LC_funclist + ul.LC_funclist {
                   8594:     /* 
                   8595:        left border as a seperator if we have more than
                   8596:        one list 
                   8597:     */
                   8598:     border-left: 1px solid $sidebg;
                   8599:     /* 
                   8600:        this hides the left border behind the border of the 
                   8601:        outer box if element is wrapped to the next 'line' 
                   8602:     */
                   8603:     margin-left: -1px;
                   8604: }
                   8605: 
1.843     bisitz   8606: ul.LC_funclist li {
1.915     droeschl 8607:   display: inline;
1.782     bisitz   8608:   white-space: nowrap;
1.915     droeschl 8609:   margin: 0 0 0 25px;
                   8610:   line-height: 150%;
1.782     bisitz   8611: }
                   8612: 
1.974     wenzelju 8613: .LC_hidden {
                   8614:   display: none;
                   8615: }
                   8616: 
1.1030    www      8617: .LCmodal-overlay {
                   8618: 		position:fixed;
                   8619: 		top:0;
                   8620: 		right:0;
                   8621: 		bottom:0;
                   8622: 		left:0;
                   8623: 		height:100%;
                   8624: 		width:100%;
                   8625: 		margin:0;
                   8626: 		padding:0;
                   8627: 		background:#999;
                   8628: 		opacity:.75;
                   8629: 		filter: alpha(opacity=75);
                   8630: 		-moz-opacity: 0.75;
                   8631: 		z-index:101;
                   8632: }
                   8633: 
                   8634: * html .LCmodal-overlay {   
                   8635: 		position: absolute;
                   8636: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8637: }
                   8638: 
                   8639: .LCmodal-window {
                   8640: 		position:fixed;
                   8641: 		top:50%;
                   8642: 		left:50%;
                   8643: 		margin:0;
                   8644: 		padding:0;
                   8645: 		z-index:102;
                   8646: 	}
                   8647: 
                   8648: * html .LCmodal-window {
                   8649: 		position:absolute;
                   8650: }
                   8651: 
                   8652: .LCclose-window {
                   8653: 		position:absolute;
                   8654: 		width:32px;
                   8655: 		height:32px;
                   8656: 		right:8px;
                   8657: 		top:8px;
                   8658: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8659: 		text-indent:-99999px;
                   8660: 		overflow:hidden;
                   8661: 		cursor:pointer;
                   8662: }
                   8663: 
1.1075.2.158  raeburn  8664: .LCisDisabled {
                   8665:   cursor: not-allowed;
                   8666:   opacity: 0.5;
                   8667: }
                   8668: 
                   8669: a[aria-disabled="true"] {
                   8670:   color: currentColor;
                   8671:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8672:   pointer-events: none;
                   8673:   text-decoration: none;
                   8674: }
                   8675: 
1.1075.2.141  raeburn  8676: pre.LC_wordwrap {
                   8677:   white-space: pre-wrap;
                   8678:   white-space: -moz-pre-wrap;
                   8679:   white-space: -pre-wrap;
                   8680:   white-space: -o-pre-wrap;
                   8681:   word-wrap: break-word;
                   8682: }
                   8683: 
1.1075.2.17  raeburn  8684: /*
1.1075.2.161.  .21(raeb 8685:-24):   styles used for response display
                   8686:-24): */
                   8687:-24): div.LC_radiofoil, div.LC_rankfoil {
                   8688:-24):   margin: .5em 0em .5em 0em;
                   8689:-24): }
                   8690:-24): table.LC_itemgroup {
                   8691:-24):   margin-top: 1em;
                   8692:-24): }
                   8693:-24): 
                   8694:-24): /*
1.1075.2.17  raeburn  8695:   styles used by TTH when "Default set of options to pass to tth/m
                   8696:   when converting TeX" in course settings has been set
                   8697: 
                   8698:   option passed: -t
                   8699: 
                   8700: */
                   8701: 
                   8702: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8703: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8704: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8705: td div.norm {line-height:normal;}
                   8706: 
                   8707: /*
                   8708:   option passed -y3
                   8709: */
                   8710: 
                   8711: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8712: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8713: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8714: 
1.1075.2.161.  .21(raeb 8715:-24): /*
                   8716:-24):   sections with roles, for content only
                   8717:-24): */
                   8718:-24): section[class^="role-"] {
                   8719:-24):   padding-left: 10px;
                   8720:-24):   padding-right: 5px;
                   8721:-24):   margin-top: 8px;
                   8722:-24):   margin-bottom: 8px;
                   8723:-24):   border: 1px solid #2A4;
                   8724:-24):   border-radius: 5px;
                   8725:-24):   box-shadow: 0px 1px 1px #BBB;
                   8726:-24): }
                   8727:-24): section[class^="role-"]>h1 {
                   8728:-24):   position: relative;
                   8729:-24):   margin: 0px;
                   8730:-24):   padding-top: 10px;
                   8731:-24):   padding-left: 40px;
                   8732:-24): }
                   8733:-24): section[class^="role-"]>h1:before {
                   8734:-24):   position: absolute;
                   8735:-24):   left: -5px;
                   8736:-24):   top: 5px;
                   8737:-24): }
                   8738:-24): section.role-activity>h1:before {
                   8739:-24):   content:url('/adm/daxe/images/section_icons/activity.png');
                   8740:-24): }
                   8741:-24): section.role-advice>h1:before {
                   8742:-24):   content:url('/adm/daxe/images/section_icons/advice.png');
                   8743:-24): }
                   8744:-24): section.role-bibliography>h1:before {
                   8745:-24):   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8746:-24): }
                   8747:-24): section.role-citation>h1:before {
                   8748:-24):   content:url('/adm/daxe/images/section_icons/citation.png');
                   8749:-24): }
                   8750:-24): section.role-conclusion>h1:before {
                   8751:-24):   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8752:-24): }
                   8753:-24): section.role-definition>h1:before {
                   8754:-24):   content:url('/adm/daxe/images/section_icons/definition.png');
                   8755:-24): }
                   8756:-24): section.role-demonstration>h1:before {
                   8757:-24):   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8758:-24): }
                   8759:-24): section.role-example>h1:before {
                   8760:-24):   content:url('/adm/daxe/images/section_icons/example.png');
                   8761:-24): }
                   8762:-24): section.role-explanation>h1:before {
                   8763:-24):   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8764:-24): }
                   8765:-24): section.role-introduction>h1:before {
                   8766:-24):   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8767:-24): }
                   8768:-24): section.role-method>h1:before {
                   8769:-24):   content:url('/adm/daxe/images/section_icons/method.png');
                   8770:-24): }
                   8771:-24): section.role-more_information>h1:before {
                   8772:-24):   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8773:-24): }
                   8774:-24): section.role-objectives>h1:before {
                   8775:-24):   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8776:-24): }
                   8777:-24): section.role-prerequisites>h1:before {
                   8778:-24):   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8779:-24): }
                   8780:-24): section.role-remark>h1:before {
                   8781:-24):   content:url('/adm/daxe/images/section_icons/remark.png');
                   8782:-24): }
                   8783:-24): section.role-reminder>h1:before {
                   8784:-24):   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8785:-24): }
                   8786:-24): section.role-summary>h1:before {
                   8787:-24):   content:url('/adm/daxe/images/section_icons/summary.png');
                   8788:-24): }
                   8789:-24): section.role-syntax>h1:before {
                   8790:-24):   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8791:-24): }
                   8792:-24): section.role-warning>h1:before {
                   8793:-24):   content:url('/adm/daxe/images/section_icons/warning.png');
                   8794:-24): }
                   8795:-24): 
1.1075.2.121  raeburn  8796: #LC_minitab_header {
                   8797:   float:left;
                   8798:   width:100%;
                   8799:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8800:   font-size:93%;
                   8801:   line-height:normal;
                   8802:   margin: 0.5em 0 0.5em 0;
                   8803: }
                   8804: #LC_minitab_header ul {
                   8805:   margin:0;
                   8806:   padding:10px 10px 0;
                   8807:   list-style:none;
                   8808: }
                   8809: #LC_minitab_header li {
                   8810:   float:left;
                   8811:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8812:   margin:0;
                   8813:   padding:0 0 0 9px;
                   8814: }
                   8815: #LC_minitab_header a {
                   8816:   display:block;
                   8817:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8818:   padding:5px 15px 4px 6px;
                   8819: }
                   8820: #LC_minitab_header #LC_current_minitab {
                   8821:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8822: }
                   8823: #LC_minitab_header #LC_current_minitab a {
                   8824:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8825:   padding-bottom:5px;
                   8826: }
                   8827: 
                   8828: 
1.343     albertel 8829: END
                   8830: }
                   8831: 
1.306     albertel 8832: =pod
                   8833: 
                   8834: =item * &headtag()
                   8835: 
                   8836: Returns a uniform footer for LON-CAPA web pages.
                   8837: 
1.307     albertel 8838: Inputs: $title - optional title for the head
                   8839:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8840:         $args - optional arguments
1.319     albertel 8841:             force_register - if is true call registerurl so the remote is 
                   8842:                              informed
1.415     albertel 8843:             redirect       -> array ref of
                   8844:                                    1- seconds before redirect occurs
                   8845:                                    2- url to redirect to
                   8846:                                    3- whether the side effect should occur
1.315     albertel 8847:                            (side effect of setting 
                   8848:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8849:22):                                redirected to)
                   8850:22):                                    4- whether the redirect target should be
                   8851:22):                                       the opener of the current (pop-up)
                   8852:22):                                       window (side effect of setting
                   8853:22):                                       $env{'internal.head.to_opener'} to
                   8854:22):                                       1, if true.
          .10(raeb 8855:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8856:             domain         -> force to color decorate a page for a specific
                   8857:                                domain
                   8858:             function       -> force usage of a specific rolish color scheme
                   8859:             bgcolor        -> override the default page bgcolor
1.460     albertel 8860:             no_auto_mt_title
                   8861:                            -> prevent &mt()ing the title arg
1.464     albertel 8862: 
1.306     albertel 8863: =cut
                   8864: 
                   8865: sub headtag {
1.313     albertel 8866:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8867:     
1.363     albertel 8868:     my $function = $args->{'function'} || &get_users_function();
                   8869:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8870:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8871:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8872:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8873: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8874: 		   #time(),
1.418     albertel 8875: 		   $env{'environment.color.timestamp'},
1.363     albertel 8876: 		   $function,$domain,$bgcolor);
                   8877: 
1.369     www      8878:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8879: 
1.308     albertel 8880:     my $result =
                   8881: 	'<head>'.
1.1075.2.56  raeburn  8882: 	&font_settings($args);
1.319     albertel 8883: 
1.1075.2.72  raeburn  8884:     my $inhibitprint;
                   8885:     if ($args->{'print_suppress'}) {
                   8886:         $inhibitprint = &print_suppression();
                   8887:     }
1.1064    raeburn  8888: 
1.461     albertel 8889:     if (!$args->{'frameset'}) {
                   8890: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8891:     }
1.1075.2.12  raeburn  8892:     if ($args->{'force_register'}) {
                   8893:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8894:     }
1.436     albertel 8895:     if (!$args->{'no_nav_bar'} 
                   8896: 	&& !$args->{'only_body'}
                   8897: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8898: 	$result .= &help_menu_js($httphost);
1.1032    www      8899:         $result.=&modal_window();
1.1038    www      8900:         $result.=&togglebox_script();
1.1034    www      8901:         $result.=&wishlist_window();
1.1041    www      8902:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8903:     } else {
                   8904:         if ($args->{'add_modal'}) {
                   8905:            $result.=&modal_window();
                   8906:         }
                   8907:         if ($args->{'add_wishlist'}) {
                   8908:            $result.=&wishlist_window();
                   8909:         }
1.1038    www      8910:         if ($args->{'add_togglebox'}) {
                   8911:            $result.=&togglebox_script();
                   8912:         }
1.1041    www      8913:         if ($args->{'add_progressbar'}) {
                   8914:            $result.=&LCprogressbarUpdate_script();
                   8915:         }
1.436     albertel 8916:     }
1.314     albertel 8917:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8918:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8919:-22):         if (!$skip_enc_check) {
                   8920:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8921:-22):         }
1.414     albertel 8922: 	if (!$inhibit_continue) {
                   8923: 	    $env{'internal.head.redirect'} = $url;
                   8924: 	}
1.1075.2.161.  .9(raebu 8925:22):         $result.=<<"ADDMETA";
1.313     albertel 8926: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8927:22): ADDMETA
                   8928:22):         if ($to_opener) {
                   8929:22):             $env{'internal.head.to_opener'} = 1;
                   8930:22):             my $dest = &js_escape($url);
                   8931:22):             my $timeout = int($time * 1000);
                   8932:22):             $result .=<<"ENDJS";
                   8933:22): <script type="text/javascript">
                   8934:22): // <![CDATA[
                   8935:22): function LC_To_Opener() {
                   8936:22):     var dest = '$dest';
                   8937:22):     if (dest != '') {
                   8938:22):         if (window.opener != null && !window.opener.closed) {
                   8939:22):             window.opener.location.href=dest;
                   8940:22):             window.close();
                   8941:22):         } else {
                   8942:22):             window.location.href=dest;
                   8943:22):         }
                   8944:22):     }
                   8945:22): }
                   8946:22): \$(document).ready(function () {
                   8947:22):     setTimeout('LC_To_Opener()',$timeout);
                   8948:22): });
                   8949:22): // ]]>
                   8950:22): </script>
                   8951:22): ENDJS
                   8952:22):         } else {
                   8953:22):             $result.=<<"ADDMETA";
1.344     albertel 8954: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8955: ADDMETA
1.1075.2.161.  .9(raebu 8956:22):         }
1.1075.2.89  raeburn  8957:     } else {
                   8958:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8959:             my $requrl = $env{'request.uri'};
                   8960:             if ($requrl eq '') {
                   8961:                 $requrl = $ENV{'REQUEST_URI'};
                   8962:                 $requrl =~ s/\?.+$//;
                   8963:             }
                   8964:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8965:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8966:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8967:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8968:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8969:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8970:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8971:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8972:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8973:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8974:                             $offload = 1;
1.1075.2.151  raeburn  8975:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8976:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8977:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8978:                                     $offloadoth = 1;
                   8979:                                     $dom_in_use = $env{'user.domain'};
                   8980:                                 }
                   8981:                             }
1.1075.2.145  raeburn  8982:                         }
                   8983:                     }
                   8984:                     unless ($offload) {
                   8985:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8986:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8987:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8988:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8989:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8990:                                         $offload = 1;
1.1075.2.151  raeburn  8991:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8992:                                         $dom_in_use = $env{'user.domain'};
                   8993:                                     }
1.1075.2.89  raeburn  8994:                                 }
1.1075.2.145  raeburn  8995:                             }
                   8996:                         }
                   8997:                     }
                   8998:                     if ($offload) {
1.1075.2.158  raeburn  8999:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  9000:                         if (($newserver eq '') && ($offloadoth)) {
                   9001:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 9002:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  9003:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9004:                             }
                   9005:                         }
1.1075.2.145  raeburn  9006:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9007:                             my $numsec = 5;
                   9008:                             my $timeout = $numsec * 1000;
                   9009:                             my ($newurl,$locknum,%locks,$msg);
                   9010:                             if ($env{'request.role.adv'}) {
                   9011:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9012:                             }
                   9013:                             my $disable_submit = 0;
                   9014:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9015:                                 $disable_submit = 1;
                   9016:                             }
                   9017:                             if ($locknum) {
                   9018:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  9019:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  9020:                                        join(", ",sort(values(%locks)))."\n";
                   9021:                                 if (&show_course()) {
                   9022:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  9023:                                 } else {
1.1075.2.145  raeburn  9024:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   9025:                                 }
                   9026:                             } else {
                   9027:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9028:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9029:                                 }
                   9030:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9031:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9032:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9033:                                     $newurl .= '&role='.$env{'request.role'};
                   9034:                                 }
                   9035:                                 if ($env{'request.symb'}) {
                   9036:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9037:                                     if ($shownsymb =~ m{^/enc/}) {
                   9038:                                         my $reqdmajor = 2;
                   9039:                                         my $reqdminor = 11;
                   9040:                                         my $reqdsubminor = 3;
                   9041:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9042:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9043:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9044:                                         if (($major eq '' && $minor eq '') ||
                   9045:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9046:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9047:                                              ($reqdsubminor > $subminor))))) {
                   9048:                                             undef($shownsymb);
                   9049:                                         }
1.1075.2.89  raeburn  9050:                                     }
1.1075.2.145  raeburn  9051:                                     if ($shownsymb) {
                   9052:                                         &js_escape(\$shownsymb);
                   9053:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  9054:                                     }
1.1075.2.145  raeburn  9055:                                 } else {
                   9056:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9057:                                     &js_escape(\$shownurl);
                   9058:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  9059:                                 }
1.1075.2.145  raeburn  9060:                             }
                   9061:                             &js_escape(\$msg);
                   9062:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  9063: <meta http-equiv="pragma" content="no-cache" />
                   9064: <script type="text/javascript">
1.1075.2.92  raeburn  9065: // <![CDATA[
1.1075.2.89  raeburn  9066: function LC_Offload_Now() {
                   9067:     var dest = "$newurl";
                   9068:     if (dest != '') {
                   9069:         window.location.href="$newurl";
                   9070:     }
                   9071: }
1.1075.2.92  raeburn  9072: \$(document).ready(function () {
                   9073:     window.alert('$msg');
                   9074:     if ($disable_submit) {
1.1075.2.89  raeburn  9075:         \$(".LC_hwk_submit").prop("disabled", true);
                   9076:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  9077:     }
                   9078:     setTimeout('LC_Offload_Now()', $timeout);
                   9079: });
                   9080: // ]]>
1.1075.2.89  raeburn  9081: </script>
                   9082: OFFLOAD
                   9083:                         }
                   9084:                     }
                   9085:                 }
                   9086:             }
                   9087:         }
1.313     albertel 9088:     }
1.306     albertel 9089:     if (!defined($title)) {
                   9090: 	$title = 'The LearningOnline Network with CAPA';
                   9091:     }
1.460     albertel 9092:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.161.  .25(raeb 9093:-24):     if ($title =~ /^LON-CAPA\s+/) {
                   9094:-24):         $result .= '<title> '.$title.'</title>';
                   9095:-24):     } else {
                   9096:-24):         $result .= '<title> LON-CAPA '.$title.'</title>';  
                   9097:-24):     }
                   9098:-24):     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1075.2.61  raeburn  9099:     if (!$args->{'frameset'}) {
                   9100:         $result .= ' /';
                   9101:     }
                   9102:     $result .= '>'
1.1064    raeburn  9103:         .$inhibitprint
1.414     albertel 9104: 	.$head_extra;
1.1075.2.108  raeburn  9105:     my $clientmobile;
                   9106:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9107:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9108:     } else {
                   9109:         $clientmobile = $env{'browser.mobile'};
                   9110:     }
                   9111:     if ($clientmobile) {
1.1075.2.42  raeburn  9112:         $result .= '
                   9113: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9114: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9115:     }
1.1075.2.126  raeburn  9116:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9117:     return $result.'</head>';
1.306     albertel 9118: }
                   9119: 
                   9120: =pod
                   9121: 
1.340     albertel 9122: =item * &font_settings()
                   9123: 
                   9124: Returns neccessary <meta> to set the proper encoding
                   9125: 
1.1075.2.56  raeburn  9126: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9127: 
                   9128: =cut
                   9129: 
                   9130: sub font_settings {
1.1075.2.56  raeburn  9131:     my ($args) = @_;
1.340     albertel 9132:     my $headerstring='';
1.1075.2.56  raeburn  9133:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9134:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 9135: 	$headerstring.=
1.1075.2.61  raeburn  9136: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9137:         if (!$args->{'frameset'}) {
                   9138:             $headerstring.= ' /';
                   9139:         }
                   9140:         $headerstring .= '>'."\n";
1.340     albertel 9141:     }
                   9142:     return $headerstring;
                   9143: }
                   9144: 
1.341     albertel 9145: =pod
                   9146: 
1.1064    raeburn  9147: =item * &print_suppression()
                   9148: 
                   9149: In course context returns css which causes the body to be blank when media="print",
                   9150: if printout generation is unavailable for the current resource.
                   9151: 
                   9152: This could be because:
                   9153: 
                   9154: (a) printstartdate is in the future
                   9155: 
                   9156: (b) printenddate is in the past
                   9157: 
                   9158: (c) there is an active exam block with "printout"
                   9159: functionality blocked
                   9160: 
                   9161: Users with pav, pfo or evb privileges are exempt.
                   9162: 
                   9163: Inputs: none
                   9164: 
                   9165: =cut
                   9166: 
                   9167: 
                   9168: sub print_suppression {
                   9169:     my $noprint;
                   9170:     if ($env{'request.course.id'}) {
                   9171:         my $scope = $env{'request.course.id'};
                   9172:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9173:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9174:             return;
                   9175:         }
                   9176:         if ($env{'request.course.sec'} ne '') {
                   9177:             $scope .= "/$env{'request.course.sec'}";
                   9178:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9179:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9180:                 return;
1.1064    raeburn  9181:             }
                   9182:         }
                   9183:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9184:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  9185:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9186:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9187:         if ($blocked) {
                   9188:             my $checkrole = "cm./$cdom/$cnum";
                   9189:             if ($env{'request.course.sec'} ne '') {
                   9190:                 $checkrole .= "/$env{'request.course.sec'}";
                   9191:             }
                   9192:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9193:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9194:                 $noprint = 1;
                   9195:             }
                   9196:         }
                   9197:         unless ($noprint) {
                   9198:             my $symb = &Apache::lonnet::symbread();
                   9199:             if ($symb ne '') {
                   9200:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9201:                 if (ref($navmap)) {
                   9202:                     my $res = $navmap->getBySymb($symb);
                   9203:                     if (ref($res)) {
                   9204:                         if (!$res->resprintable()) {
                   9205:                             $noprint = 1;
                   9206:                         }
                   9207:                     }
                   9208:                 }
                   9209:             }
                   9210:         }
                   9211:         if ($noprint) {
                   9212:             return <<"ENDSTYLE";
                   9213: <style type="text/css" media="print">
                   9214:     body { display:none }
                   9215: </style>
                   9216: ENDSTYLE
                   9217:         }
                   9218:     }
                   9219:     return;
                   9220: }
                   9221: 
                   9222: =pod
                   9223: 
1.341     albertel 9224: =item * &xml_begin()
                   9225: 
                   9226: Returns the needed doctype and <html>
                   9227: 
                   9228: Inputs: none
                   9229: 
                   9230: =cut
                   9231: 
                   9232: sub xml_begin {
1.1075.2.61  raeburn  9233:     my ($is_frameset) = @_;
1.341     albertel 9234:     my $output='';
                   9235: 
                   9236:     if ($env{'browser.mathml'}) {
                   9237: 	$output='<?xml version="1.0"?>'
                   9238:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9239: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9240:             
                   9241: #	    .'<!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">] >'
                   9242: 	    .'<!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">'
                   9243:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9244: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  9245:     } elsif ($is_frameset) {
                   9246:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9247:                 '<html>'."\n";
1.341     albertel 9248:     } else {
1.1075.2.61  raeburn  9249: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9250:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9251:     }
                   9252:     return $output;
                   9253: }
1.340     albertel 9254: 
                   9255: =pod
                   9256: 
1.306     albertel 9257: =item * &start_page()
                   9258: 
                   9259: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9260: 
1.648     raeburn  9261: Inputs:
                   9262: 
                   9263: =over 4
                   9264: 
                   9265: $title - optional title for the page
                   9266: 
                   9267: $head_extra - optional extra HTML to incude inside the <head>
                   9268: 
                   9269: $args - additional optional args supported are:
                   9270: 
                   9271: =over 8
                   9272: 
                   9273:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9274:                                     arg on
1.814     bisitz   9275:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9276:              add_entries    -> additional attributes to add to the  <body>
                   9277:              domain         -> force to color decorate a page for a 
1.317     albertel 9278:                                     specific domain
1.648     raeburn  9279:              function       -> force usage of a specific rolish color
1.317     albertel 9280:                                     scheme
1.648     raeburn  9281:              redirect       -> see &headtag()
                   9282:              bgcolor        -> override the default page bg color
                   9283:              js_ready       -> return a string ready for being used in 
1.317     albertel 9284:                                     a javascript writeln
1.648     raeburn  9285:              html_encode    -> return a string ready for being used in 
1.320     albertel 9286:                                     a html attribute
1.648     raeburn  9287:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9288:                                     $forcereg arg
1.648     raeburn  9289:              frameset       -> if true will start with a <frameset>
1.330     albertel 9290:                                     rather than <body>
1.648     raeburn  9291:              skip_phases    -> hash ref of 
1.338     albertel 9292:                                     head -> skip the <html><head> generation
                   9293:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  9294:              no_inline_link -> if true and in remote mode, don't show the
                   9295:                                     'Switch To Inline Menu' link
1.648     raeburn  9296:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9297:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9298:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  9299:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9300:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  9301:              group          -> includes the current group, if page is for a
                   9302:                                specific group
1.1075.2.133  raeburn  9303:              use_absolute   -> for request for external resource or syllabus, this
                   9304:                                will contain https://<hostname> if server uses
                   9305:                                https (as per hosts.tab), but request is for http
                   9306:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  9307:              links_disabled -> Links in primary and secondary menus are disabled
                   9308:                                (Can enable them once page has loaded - see lonroles.pm
                   9309:                                for an example).
1.1075.2.161.  .6(raebu 9310:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9311: 
1.648     raeburn  9312: =back
1.460     albertel 9313: 
1.648     raeburn  9314: =back
1.562     albertel 9315: 
1.306     albertel 9316: =cut
                   9317: 
                   9318: sub start_page {
1.309     albertel 9319:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9320:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9321: 
1.315     albertel 9322:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 9323:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9324: 
1.338     albertel 9325:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  9326:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9327:     }
1.1075.2.161.  .1(raebu 9328:21): 
                   9329:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   9330:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9331:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9332:21):                 $args->{'no_primary_menu'} = 1;
                   9333:21):             }
                   9334:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9335:21):                 $args->{'no_inline_menu'} = 1;
                   9336:21):             }
                   9337:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9338:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9339:21):             }
                   9340:21):         } else {
                   9341:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9342:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9343:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9344:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9345:21):                     $args->{'no_primary_menu'} = 1;
                   9346:21):                 }
                   9347:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9348:21):                     $args->{'no_inline_menu'} = 1;
                   9349:21):                 }
                   9350:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9351:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9352:21):                 }
                   9353:21):             }
                   9354:21):         }
                   9355:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9356:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9357:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   9358:21):     } elsif ($env{'request.course.id'}) {
                   9359:21):         my $expiretime=600;
                   9360:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9361:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9362:21):         }
                   9363:21):         my ($deeplinkmenu,$menuref);
                   9364:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9365:21):         if ($menucoll) {
                   9366:21):             if (ref($menuref) eq 'HASH') {
                   9367:21):                 %menu = %{$menuref};
                   9368:21):             }
                   9369:21):             if ($menu{'top'} eq 'n') {
                   9370:21):                 $args->{'no_primary_menu'} = 1;
                   9371:21):             }
                   9372:21):             if ($menu{'inline'} eq 'n') {
                   9373:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   9374:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9375:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9376:21):                     my $crstype = &course_type();
                   9377:21):                     my $now = time;
                   9378:21):                     my $ccrole;
                   9379:21):                     if ($crstype eq 'Community') {
                   9380:21):                         $ccrole = 'co';
                   9381:21):                     } else {
                   9382:21):                         $ccrole = 'cc';
                   9383:21):                     }
                   9384:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9385:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9386:21):                         if ((($start) && ($start<0)) ||
                   9387:21):                             (($end) && ($end<$now))  ||
                   9388:21):                             (($start) && ($now<$start))) {
                   9389:21):                             $args->{'no_inline_menu'} = 1;
                   9390:21):                         }
                   9391:21):                     } else {
                   9392:21):                         $args->{'no_inline_menu'} = 1;
                   9393:21):                     }
                   9394:21):                 }
                   9395:21):             }
                   9396:21):         }
                   9397:21):     }
          .4(raebu 9398:22): 
          .8(raebu 9399:22):     my $showncrumbs;
1.338     albertel 9400:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9401: 	if ($args->{'frameset'}) {
                   9402: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9403: 						$args->{'add_entries'});
                   9404: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9405:         } else {
                   9406:             $result .=
                   9407:                 &bodytag($title, 
                   9408:                          $args->{'function'},       $args->{'add_entries'},
                   9409:                          $args->{'only_body'},      $args->{'domain'},
                   9410:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  9411:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 9412:21):                          $args,                     \@advtools,
          .8(raebu 9413:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   9414:         }
1.330     albertel 9415:     }
1.338     albertel 9416: 
1.315     albertel 9417:     if ($args->{'js_ready'}) {
1.713     kaisler  9418: 		$result = &js_ready($result);
1.315     albertel 9419:     }
1.320     albertel 9420:     if ($args->{'html_encode'}) {
1.713     kaisler  9421: 		$result = &html_encode($result);
                   9422:     }
                   9423: 
1.813     bisitz   9424:     # Preparation for new and consistent functionlist at top of screen
                   9425:     # if ($args->{'functionlist'}) {
                   9426:     #            $result .= &build_functionlist();
                   9427:     #}
                   9428: 
1.964     droeschl 9429:     # Don't add anything more if only_body wanted or in const space
                   9430:     return $result if    $args->{'only_body'} 
                   9431:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9432: 
                   9433:     #Breadcrumbs
1.758     kaisler  9434:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 9435:22):         unless ($showncrumbs) {
1.758     kaisler  9436: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9437: 		#if any br links exists, add them to the breadcrumbs
                   9438: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9439: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9440: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9441: 			}
                   9442: 		}
1.1075.2.19  raeburn  9443:                 # if @advtools array contains items add then to the breadcrumbs
                   9444:                 if (@advtools > 0) {
                   9445:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9446:                 }
1.1075.2.123  raeburn  9447:                 my $menulink;
                   9448:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 9449:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   9450:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  9451:                     $menulink = 0;
                   9452:                 } else {
                   9453:                     undef($menulink);
                   9454:                 }
1.1075.2.161.  .8(raebu 9455:22):                 my $linkprotout;
                   9456:22):                 if ($env{'request.deeplink.login'}) {
                   9457:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9458:22):                     if ($linkprotout) {
                   9459:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9460:22):                     }
                   9461:22):                 }
1.758     kaisler  9462: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9463: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  9464: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 9465:21): 		} else {
1.1075.2.123  raeburn  9466: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9467: 		}
1.1075.2.161.  .8(raebu 9468:22):         }
1.1075.2.24  raeburn  9469:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9470:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9471:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9472:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9473:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9474:     }
1.315     albertel 9475:     return $result;
1.306     albertel 9476: }
                   9477: 
                   9478: sub end_page {
1.315     albertel 9479:     my ($args) = @_;
                   9480:     $env{'internal.end_page'}++;
1.330     albertel 9481:     my $result;
1.335     albertel 9482:     if ($args->{'discussion'}) {
                   9483: 	my ($target,$parser);
                   9484: 	if (ref($args->{'discussion'})) {
                   9485: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9486: 				$args->{'discussion'}{'parser'});
                   9487: 	}
                   9488: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9489:     }
1.330     albertel 9490:     if ($args->{'frameset'}) {
                   9491: 	$result .= '</frameset>';
                   9492:     } else {
1.635     raeburn  9493: 	$result .= &endbodytag($args);
1.330     albertel 9494:     }
1.1075.2.6  raeburn  9495:     unless ($args->{'notbody'}) {
                   9496:         $result .= "\n</html>";
                   9497:     }
1.330     albertel 9498: 
1.315     albertel 9499:     if ($args->{'js_ready'}) {
1.317     albertel 9500: 	$result = &js_ready($result);
1.315     albertel 9501:     }
1.335     albertel 9502: 
1.320     albertel 9503:     if ($args->{'html_encode'}) {
                   9504: 	$result = &html_encode($result);
                   9505:     }
1.335     albertel 9506: 
1.315     albertel 9507:     return $result;
                   9508: }
                   9509: 
1.1075.2.161.  .1(raebu 9510:21): sub menucoll_in_effect {
                   9511:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9512:21):     if ($env{'request.course.id'}) {
                   9513:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9514:21):         if ($env{'request.deeplink.login'}) {
                   9515:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9516:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9517:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9518:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9519:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9520:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9521:21):                     if (ref($navmap)) {
                   9522:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9523:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9524:21):                                                           '0.deeplink');
                   9525:21):                     } else {
                   9526:21):                         $check_login_symb = 1;
                   9527:21):                     }
                   9528:21):                 } else {
                   9529:21):                     my $symb=&Apache::lonnet::symbread();
                   9530:21):                     if ($symb) {
                   9531:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9532:21):                     } else {
                   9533:21):                         $check_login_symb = 1;
                   9534:21):                     }
                   9535:21):                 }
                   9536:21):             } else {
                   9537:21):                 $check_login_symb = 1;
                   9538:21):             }
                   9539:21):             if ($check_login_symb) {
                   9540:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9541:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9542:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9543:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9544:21):                     if (ref($navmap)) {
                   9545:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9546:21):                     }
                   9547:21):                 } else {
                   9548:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9549:21):                 }
                   9550:21):             }
                   9551:21):             if ($deeplink ne '') {
          .6(raebu 9552:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9553:21):                 if ($display =~ /^\d+$/) {
                   9554:21):                     $deeplinkmenu = 1;
                   9555:21):                     $menucoll = $display;
                   9556:21):                 }
                   9557:21):             }
                   9558:21):         }
                   9559:21):         if ($menucoll) {
                   9560:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9561:21):         }
                   9562:21):     }
                   9563:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9564:21): }
                   9565:21): 
                   9566:21): sub deeplink_login_symb {
                   9567:21):     my ($cnum,$cdom) = @_;
                   9568:21):     my $login_symb;
                   9569:21):     if ($env{'request.deeplink.login'}) {
                   9570:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9571:21):     }
                   9572:21):     return $login_symb;
                   9573:21): }
                   9574:21): 
                   9575:21): sub symb_from_tinyurl {
                   9576:21):     my ($url,$cnum,$cdom) = @_;
                   9577:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9578:21):         my $key = $1;
                   9579:21):         my ($tinyurl,$login);
                   9580:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9581:21):         if (defined($cached)) {
                   9582:21):             $tinyurl = $result;
                   9583:21):         } else {
                   9584:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9585:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9586:21):             if ($currtiny{$key} ne '') {
                   9587:21):                 $tinyurl = $currtiny{$key};
                   9588:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9589:21):             }
                   9590:21):         }
                   9591:21):         if ($tinyurl ne '') {
                   9592:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9593:21):             if (wantarray) {
                   9594:21):                 return ($cnumreq,$symb);
                   9595:21):             } elsif ($cnumreq eq $cnum) {
                   9596:21):                 return $symb;
                   9597:21):             }
                   9598:21):         }
                   9599:21):     }
                   9600:21):     if (wantarray) {
                   9601:21):         return ();
                   9602:21):     } else {
                   9603:21):         return;
                   9604:21):     }
                   9605:21): }
                   9606:21): 
          .17(raeb 9607:-23): sub usable_exttools {
                   9608:-23):     my %tooltypes;
                   9609:-23):     if ($env{'request.course.id'}) {
                   9610:-23):         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9611:-23):            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9612:-23):                %tooltypes = (
                   9613:-23):                              crs => 1,
                   9614:-23):                              dom => 1,
                   9615:-23):                             );
                   9616:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9617:-23):                $tooltypes{'crs'} = 1;
                   9618:-23):            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9619:-23):                $tooltypes{'dom'} = 1;
                   9620:-23):            }
                   9621:-23):         } else {
                   9622:-23):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9623:-23):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9624:-23):             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9625:-23):             if ($crstype eq '') {
                   9626:-23):                 $crstype = 'course';
                   9627:-23):             }
                   9628:-23):             if ($crstype eq 'course') {
                   9629:-23):                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9630:-23):                     $crstype = 'official';
                   9631:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9632:-23):                     $crstype = 'textbook';
                   9633:-23):                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9634:-23):                     $crstype = 'lti';
                   9635:-23):                 } else {
                   9636:-23):                     $crstype = 'unofficial';
                   9637:-23):                 }
                   9638:-23):             }
                   9639:-23):             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9640:-23):             if ($domdefaults{$crstype.'domexttool'}) {
                   9641:-23):                 $tooltypes{'dom'} = 1;
                   9642:-23):             }
                   9643:-23):             if ($domdefaults{$crstype.'exttool'}) {
                   9644:-23):                 $tooltypes{'crs'} = 1;
                   9645:-23):             }
                   9646:-23):         }
                   9647:-23):     }
                   9648:-23):     return %tooltypes;
                   9649:-23): }
                   9650:-23): 
1.1034    www      9651: sub wishlist_window {
                   9652:     return(<<'ENDWISHLIST');
1.1046    raeburn  9653: <script type="text/javascript">
1.1034    www      9654: // <![CDATA[
                   9655: // <!-- BEGIN LON-CAPA Internal
                   9656: function set_wishlistlink(title, path) {
                   9657:     if (!title) {
                   9658:         title = document.title;
                   9659:         title = title.replace(/^LON-CAPA /,'');
                   9660:     }
1.1075.2.65  raeburn  9661:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9662:     title = title.replace("'","\\\'");
1.1034    www      9663:     if (!path) {
                   9664:         path = location.pathname;
                   9665:     }
1.1075.2.65  raeburn  9666:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9667:     path = path.replace("'","\\\'");
1.1034    www      9668:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9669:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9670: }
                   9671: // END LON-CAPA Internal -->
                   9672: // ]]>
                   9673: </script>
                   9674: ENDWISHLIST
                   9675: }
                   9676: 
1.1030    www      9677: sub modal_window {
                   9678:     return(<<'ENDMODAL');
1.1046    raeburn  9679: <script type="text/javascript">
1.1030    www      9680: // <![CDATA[
                   9681: // <!-- BEGIN LON-CAPA Internal
                   9682: var modalWindow = {
                   9683: 	parent:"body",
                   9684: 	windowId:null,
                   9685: 	content:null,
                   9686: 	width:null,
                   9687: 	height:null,
                   9688: 	close:function()
                   9689: 	{
                   9690: 	        $(".LCmodal-window").remove();
                   9691: 	        $(".LCmodal-overlay").remove();
                   9692: 	},
                   9693: 	open:function()
                   9694: 	{
                   9695: 		var modal = "";
                   9696: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9697: 		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;\">";
                   9698: 		modal += this.content;
                   9699: 		modal += "</div>";	
                   9700: 
                   9701: 		$(this.parent).append(modal);
                   9702: 
                   9703: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9704: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9705: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9706: 	}
                   9707: };
1.1075.2.42  raeburn  9708: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9709: 	{
1.1075.2.119  raeburn  9710:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9711: 		modalWindow.windowId = "myModal";
                   9712: 		modalWindow.width = width;
                   9713: 		modalWindow.height = height;
1.1075.2.80  raeburn  9714: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9715: 		modalWindow.open();
1.1075.2.87  raeburn  9716: 	};
1.1030    www      9717: // END LON-CAPA Internal -->
                   9718: // ]]>
                   9719: </script>
                   9720: ENDMODAL
                   9721: }
                   9722: 
                   9723: sub modal_link {
1.1075.2.42  raeburn  9724:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9725:     unless ($width) { $width=480; }
                   9726:     unless ($height) { $height=400; }
1.1031    www      9727:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9728:     unless ($transparency) { $transparency='true'; }
                   9729: 
1.1074    raeburn  9730:     my $target_attr;
                   9731:     if (defined($target)) {
                   9732:         $target_attr = 'target="'.$target.'"';
                   9733:     }
                   9734:     return <<"ENDLINK";
1.1075.2.143  raeburn  9735: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9736: ENDLINK
1.1030    www      9737: }
                   9738: 
1.1032    www      9739: sub modal_adhoc_script {
1.1075.2.155  raeburn  9740:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9741:     my $mathjax;
                   9742:     if ($possmathjax) {
                   9743:         $mathjax = <<'ENDJAX';
                   9744:                if (typeof MathJax == 'object') {
                   9745:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9746:                }
                   9747: ENDJAX
                   9748:     }
1.1032    www      9749:     return (<<ENDADHOC);
1.1046    raeburn  9750: <script type="text/javascript">
1.1032    www      9751: // <![CDATA[
                   9752:         var $funcname = function()
                   9753:         {
                   9754:                 modalWindow.windowId = "myModal";
                   9755:                 modalWindow.width = $width;
                   9756:                 modalWindow.height = $height;
                   9757:                 modalWindow.content = '$content';
                   9758:                 modalWindow.open();
1.1075.2.155  raeburn  9759:                 $mathjax
1.1032    www      9760:         };  
                   9761: // ]]>
                   9762: </script>
                   9763: ENDADHOC
                   9764: }
                   9765: 
1.1041    www      9766: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9767:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9768:     my $innerwidth=$width-20;
                   9769:     $content=&js_ready(
1.1042    www      9770:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9771:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9772:                  $content.
1.1041    www      9773:                  &end_scrollbox().
1.1075.2.42  raeburn  9774:                  &end_page()
1.1041    www      9775:              );
1.1075.2.155  raeburn  9776:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9777: }
                   9778: 
                   9779: sub modal_adhoc_window {
1.1075.2.155  raeburn  9780:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9781:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9782:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9783: }
                   9784: 
                   9785: sub modal_adhoc_launch {
                   9786:     my ($funcname,$width,$height,$content)=@_;
                   9787:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9788: <script type="text/javascript">
                   9789: // <![CDATA[
                   9790: $funcname();
                   9791: // ]]>
                   9792: </script>
                   9793: ENDLAUNCH
                   9794: }
                   9795: 
                   9796: sub modal_adhoc_close {
                   9797:     return (<<ENDCLOSE);
                   9798: <script type="text/javascript">
                   9799: // <![CDATA[
                   9800: modalWindow.close();
                   9801: // ]]>
                   9802: </script>
                   9803: ENDCLOSE
                   9804: }
                   9805: 
1.1038    www      9806: sub togglebox_script {
                   9807:    return(<<ENDTOGGLE);
                   9808: <script type="text/javascript"> 
                   9809: // <![CDATA[
                   9810: function LCtoggleDisplay(id,hidetext,showtext) {
                   9811:    link = document.getElementById(id + "link").childNodes[0];
                   9812:    with (document.getElementById(id).style) {
                   9813:       if (display == "none" ) {
                   9814:           display = "inline";
                   9815:           link.nodeValue = hidetext;
                   9816:         } else {
                   9817:           display = "none";
                   9818:           link.nodeValue = showtext;
                   9819:        }
                   9820:    }
                   9821: }
                   9822: // ]]>
                   9823: </script>
                   9824: ENDTOGGLE
                   9825: }
                   9826: 
1.1039    www      9827: sub start_togglebox {
                   9828:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9829:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9830:     unless ($showtext) { $showtext=&mt('show'); }
                   9831:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9832:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9833:     return &start_data_table().
                   9834:            &start_data_table_header_row().
                   9835:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9836:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9837:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9838:            &end_data_table_header_row().
                   9839:            '<tr id="'.$id.'" style="display:none""><td>';
                   9840: }
                   9841: 
                   9842: sub end_togglebox {
                   9843:     return '</td></tr>'.&end_data_table();
                   9844: }
                   9845: 
1.1041    www      9846: sub LCprogressbar_script {
1.1075.2.130  raeburn  9847:    my ($id,$number_to_do)=@_;
                   9848:    if ($number_to_do) {
                   9849:        return(<<ENDPROGRESS);
1.1041    www      9850: <script type="text/javascript">
                   9851: // <![CDATA[
1.1045    www      9852: \$('#progressbar$id').progressbar({
1.1041    www      9853:   value: 0,
                   9854:   change: function(event, ui) {
                   9855:     var newVal = \$(this).progressbar('option', 'value');
                   9856:     \$('.pblabel', this).text(LCprogressTxt);
                   9857:   }
                   9858: });
                   9859: // ]]>
                   9860: </script>
                   9861: ENDPROGRESS
1.1075.2.130  raeburn  9862:    } else {
                   9863:        return(<<ENDPROGRESS);
                   9864: <script type="text/javascript">
                   9865: // <![CDATA[
                   9866: \$('#progressbar$id').progressbar({
                   9867:   value: false,
                   9868:   create: function(event, ui) {
                   9869:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9870:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9871:   }
                   9872: });
                   9873: // ]]>
                   9874: </script>
                   9875: ENDPROGRESS
                   9876:    }
1.1041    www      9877: }
                   9878: 
                   9879: sub LCprogressbarUpdate_script {
                   9880:    return(<<ENDPROGRESSUPDATE);
                   9881: <style type="text/css">
                   9882: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9883: .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      9884: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9885: </style>
                   9886: <script type="text/javascript">
                   9887: // <![CDATA[
1.1045    www      9888: var LCprogressTxt='---';
                   9889: 
1.1075.2.130  raeburn  9890: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9891:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9892:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9893:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9894:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9895:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9896:    } else {
                   9897:        \$('#progressbar'+id).progressbar('value',percent);
                   9898:    }
1.1041    www      9899: }
                   9900: // ]]>
                   9901: </script>
                   9902: ENDPROGRESSUPDATE
                   9903: }
                   9904: 
1.1042    www      9905: my $LClastpercent;
1.1045    www      9906: my $LCidcnt;
                   9907: my $LCcurrentid;
1.1042    www      9908: 
1.1041    www      9909: sub LCprogressbar {
1.1075.2.130  raeburn  9910:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9911:     $LClastpercent=0;
1.1045    www      9912:     $LCidcnt++;
                   9913:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9914:     my ($starting,$content);
                   9915:     if ($number_to_do) {
                   9916:         $starting=&mt('Starting');
                   9917:         $content=(<<ENDPROGBAR);
                   9918: $preamble
1.1045    www      9919:   <div id="progressbar$LCcurrentid">
1.1041    www      9920:     <span class="pblabel">$starting</span>
                   9921:   </div>
                   9922: ENDPROGBAR
1.1075.2.130  raeburn  9923:     } else {
                   9924:         $starting=&mt('Loading...');
                   9925:         $LClastpercent='false';
                   9926:         $content=(<<ENDPROGBAR);
                   9927: $preamble
                   9928:   <div id="progressbar$LCcurrentid">
                   9929:       <div class="progress-label">$starting</div>
                   9930:   </div>
                   9931: ENDPROGBAR
                   9932:     }
                   9933:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9934: }
                   9935: 
                   9936: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9937:     my ($r,$val,$text,$number_to_do)=@_;
                   9938:     if ($number_to_do) {
                   9939:         unless ($val) { 
                   9940:             if ($LClastpercent) {
                   9941:                 $val=$LClastpercent;
                   9942:             } else {
                   9943:                 $val=0;
                   9944:             }
                   9945:         }
                   9946:         if ($val<0) { $val=0; }
                   9947:         if ($val>100) { $val=0; }
                   9948:         $LClastpercent=$val;
                   9949:         unless ($text) { $text=$val.'%'; }
                   9950:     } else {
                   9951:         $val = 'false';
1.1042    www      9952:     }
1.1041    www      9953:     $text=&js_ready($text);
1.1044    www      9954:     &r_print($r,<<ENDUPDATE);
1.1041    www      9955: <script type="text/javascript">
                   9956: // <![CDATA[
1.1075.2.130  raeburn  9957: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9958: // ]]>
                   9959: </script>
                   9960: ENDUPDATE
1.1035    www      9961: }
                   9962: 
1.1042    www      9963: sub LCprogressbarClose {
                   9964:     my ($r)=@_;
                   9965:     $LClastpercent=0;
1.1044    www      9966:     &r_print($r,<<ENDCLOSE);
1.1042    www      9967: <script type="text/javascript">
                   9968: // <![CDATA[
1.1045    www      9969: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9970: // ]]>
                   9971: </script>
                   9972: ENDCLOSE
1.1044    www      9973: }
                   9974: 
                   9975: sub r_print {
                   9976:     my ($r,$to_print)=@_;
                   9977:     if ($r) {
                   9978:       $r->print($to_print);
                   9979:       $r->rflush();
                   9980:     } else {
                   9981:       print($to_print);
                   9982:     }
1.1042    www      9983: }
                   9984: 
1.320     albertel 9985: sub html_encode {
                   9986:     my ($result) = @_;
                   9987: 
1.322     albertel 9988:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9989:     
                   9990:     return $result;
                   9991: }
1.1044    www      9992: 
1.317     albertel 9993: sub js_ready {
                   9994:     my ($result) = @_;
                   9995: 
1.323     albertel 9996:     $result =~ s/[\n\r]/ /xmsg;
                   9997:     $result =~ s/\\/\\\\/xmsg;
                   9998:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9999:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10000:     
                   10001:     return $result;
                   10002: }
                   10003: 
1.315     albertel 10004: sub validate_page {
                   10005:     if (  exists($env{'internal.start_page'})
1.316     albertel 10006: 	  &&     $env{'internal.start_page'} > 1) {
                   10007: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10008: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10009: 				 $ENV{'request.filename'});
1.315     albertel 10010:     }
                   10011:     if (  exists($env{'internal.end_page'})
1.316     albertel 10012: 	  &&     $env{'internal.end_page'} > 1) {
                   10013: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10014: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10015: 				 $env{'request.filename'});
1.315     albertel 10016:     }
                   10017:     if (     exists($env{'internal.start_page'})
                   10018: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10019: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10020: 				 $env{'request.filename'});
1.315     albertel 10021:     }
                   10022:     if (   ! exists($env{'internal.start_page'})
                   10023: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10024: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10025: 				 $env{'request.filename'});
1.315     albertel 10026:     }
1.306     albertel 10027: }
1.315     albertel 10028: 
1.996     www      10029: 
                   10030: sub start_scrollbox {
1.1075.2.56  raeburn  10031:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10032:     unless ($outerwidth) { $outerwidth='520px'; }
                   10033:     unless ($width) { $width='500px'; }
                   10034:     unless ($height) { $height='200px'; }
1.1075    raeburn  10035:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10036:     if ($id ne '') {
1.1075.2.42  raeburn  10037:         $table_id = ' id="table_'.$id.'"';
                   10038:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10039:     }
1.1075    raeburn  10040:     if ($bgcolor ne '') {
                   10041:         $tdcol = "background-color: $bgcolor;";
                   10042:     }
1.1075.2.42  raeburn  10043:     my $nicescroll_js;
                   10044:     if ($env{'browser.mobile'}) {
                   10045:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10046:     }
1.1075    raeburn  10047:     return <<"END";
1.1075.2.42  raeburn  10048: $nicescroll_js
                   10049: 
                   10050: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  10051: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  10052: END
1.996     www      10053: }
                   10054: 
                   10055: sub end_scrollbox {
1.1036    www      10056:     return '</div></td></tr></table>';
1.996     www      10057: }
                   10058: 
1.1075.2.42  raeburn  10059: sub nicescroll_javascript {
                   10060:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10061:     my %options;
                   10062:     if (ref($cursor) eq 'HASH') {
                   10063:         %options = %{$cursor};
                   10064:     }
                   10065:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10066:         $options{'railalign'} = 'left';
                   10067:     }
                   10068:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10069:         my $function  = &get_users_function();
                   10070:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   10071:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10072:             $options{'cursorcolor'} = '#00F';
                   10073:         }
                   10074:     }
                   10075:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10076:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   10077:             $options{'cursoropacity'}='1.0';
                   10078:         }
                   10079:     } else {
                   10080:         $options{'cursoropacity'}='1.0';
                   10081:     }
                   10082:     if ($options{'cursorfixedheight'} eq 'none') {
                   10083:         delete($options{'cursorfixedheight'});
                   10084:     } else {
                   10085:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10086:     }
                   10087:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10088:         delete($options{'railoffset'});
                   10089:     }
                   10090:     my @niceoptions;
                   10091:     while (my($key,$value) = each(%options)) {
                   10092:         if ($value =~ /^\{.+\}$/) {
                   10093:             push(@niceoptions,$key.':'.$value);
                   10094:         } else {
                   10095:             push(@niceoptions,$key.':"'.$value.'"');
                   10096:         }
                   10097:     }
                   10098:     my $nicescroll_js = '
                   10099: $(document).ready(
                   10100:       function() {
                   10101:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10102:       }
                   10103: );
                   10104: ';
                   10105:     if ($framecheck) {
                   10106:         $nicescroll_js .= '
                   10107: function expand_div(caller) {
                   10108:     if (top === self) {
                   10109:         document.getElementById("'.$id.'").style.width = "auto";
                   10110:         document.getElementById("'.$id.'").style.height = "auto";
                   10111:     } else {
                   10112:         try {
                   10113:             if (parent.frames) {
                   10114:                 if (parent.frames.length > 1) {
                   10115:                     var framesrc = parent.frames[1].location.href;
                   10116:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10117:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10118:                         document.getElementById("'.$id.'").style.width = "auto";
                   10119:                         document.getElementById("'.$id.'").style.height = "auto";
                   10120:                     }
                   10121:                 }
                   10122:             }
                   10123:         } catch (e) {
                   10124:             return;
                   10125:         }
                   10126:     }
                   10127:     return;
                   10128: }
                   10129: ';
                   10130:     }
                   10131:     if ($needjsready) {
                   10132:         $nicescroll_js = '
                   10133: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10134:     } else {
                   10135:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10136:     }
                   10137:     return $nicescroll_js;
                   10138: }
                   10139: 
1.318     albertel 10140: sub simple_error_page {
1.1075.2.49  raeburn  10141:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 10142:22):     my %displayargs;
1.1075.2.49  raeburn  10143:     if (ref($args) eq 'HASH') {
                   10144:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 10145:22):         if ($args->{'only_body'}) {
                   10146:22):             $displayargs{'only_body'} = 1;
                   10147:22):         }
                   10148:22):         if ($args->{'no_nav_bar'}) {
                   10149:22):             $displayargs{'no_nav_bar'} = 1;
                   10150:22):         }
1.1075.2.49  raeburn  10151:     } else {
                   10152:         $msg = &mt($msg);
                   10153:     }
                   10154: 
1.318     albertel 10155:     my $page =
1.1075.2.161.  .4(raebu 10156:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  10157: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10158: 	&Apache::loncommon::end_page();
                   10159:     if (ref($r)) {
                   10160: 	$r->print($page);
1.327     albertel 10161: 	return;
1.318     albertel 10162:     }
                   10163:     return $page;
                   10164: }
1.347     albertel 10165: 
                   10166: {
1.610     albertel 10167:     my @row_count;
1.961     onken    10168: 
                   10169:     sub start_data_table_count {
                   10170:         unshift(@row_count, 0);
                   10171:         return;
                   10172:     }
                   10173: 
                   10174:     sub end_data_table_count {
                   10175:         shift(@row_count);
                   10176:         return;
                   10177:     }
                   10178: 
1.347     albertel 10179:     sub start_data_table {
1.1018    raeburn  10180: 	my ($add_class,$id) = @_;
1.422     albertel 10181: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10182:         my $table_id;
                   10183:         if (defined($id)) {
                   10184:             $table_id = ' id="'.$id.'"';
                   10185:         }
1.961     onken    10186: 	&start_data_table_count();
1.1018    raeburn  10187: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10188:     }
                   10189: 
                   10190:     sub end_data_table {
1.961     onken    10191: 	&end_data_table_count();
1.389     albertel 10192: 	return '</table>'."\n";;
1.347     albertel 10193:     }
                   10194: 
                   10195:     sub start_data_table_row {
1.974     wenzelju 10196: 	my ($add_class, $id) = @_;
1.610     albertel 10197: 	$row_count[0]++;
                   10198: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10199: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10200:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10201:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10202:     }
1.471     banghart 10203:     
                   10204:     sub continue_data_table_row {
1.974     wenzelju 10205: 	my ($add_class, $id) = @_;
1.610     albertel 10206: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10207: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10208:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10209:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10210:     }
1.347     albertel 10211: 
                   10212:     sub end_data_table_row {
1.389     albertel 10213: 	return '</tr>'."\n";;
1.347     albertel 10214:     }
1.367     www      10215: 
1.421     albertel 10216:     sub start_data_table_empty_row {
1.707     bisitz   10217: #	$row_count[0]++;
1.421     albertel 10218: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10219:     }
                   10220: 
                   10221:     sub end_data_table_empty_row {
                   10222: 	return '</tr>'."\n";;
                   10223:     }
                   10224: 
1.367     www      10225:     sub start_data_table_header_row {
1.389     albertel 10226: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10227:     }
                   10228: 
                   10229:     sub end_data_table_header_row {
1.389     albertel 10230: 	return '</tr>'."\n";;
1.367     www      10231:     }
1.890     droeschl 10232: 
                   10233:     sub data_table_caption {
                   10234:         my $caption = shift;
                   10235:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10236:     }
1.347     albertel 10237: }
                   10238: 
1.548     albertel 10239: =pod
                   10240: 
                   10241: =item * &inhibit_menu_check($arg)
                   10242: 
                   10243: Checks for a inhibitmenu state and generates output to preserve it
                   10244: 
                   10245: Inputs:         $arg - can be any of
                   10246:                      - undef - in which case the return value is a string 
                   10247:                                to add  into arguments list of a uri
                   10248:                      - 'input' - in which case the return value is a HTML
                   10249:                                  <form> <input> field of type hidden to
                   10250:                                  preserve the value
                   10251:                      - a url - in which case the return value is the url with
                   10252:                                the neccesary cgi args added to preserve the
                   10253:                                inhibitmenu state
                   10254:                      - a ref to a url - no return value, but the string is
                   10255:                                         updated to include the neccessary cgi
                   10256:                                         args to preserve the inhibitmenu state
                   10257: 
                   10258: =cut
                   10259: 
                   10260: sub inhibit_menu_check {
                   10261:     my ($arg) = @_;
                   10262:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10263:     if ($arg eq 'input') {
                   10264: 	if ($env{'form.inhibitmenu'}) {
                   10265: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10266: 	} else {
                   10267: 	    return
                   10268: 	}
                   10269:     }
                   10270:     if ($env{'form.inhibitmenu'}) {
                   10271: 	if (ref($arg)) {
                   10272: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10273: 	} elsif ($arg eq '') {
                   10274: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10275: 	} else {
                   10276: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10277: 	}
                   10278:     }
                   10279:     if (!ref($arg)) {
                   10280: 	return $arg;
                   10281:     }
                   10282: }
                   10283: 
1.251     albertel 10284: ###############################################
1.182     matthew  10285: 
                   10286: =pod
                   10287: 
1.549     albertel 10288: =back
                   10289: 
                   10290: =head1 User Information Routines
                   10291: 
                   10292: =over 4
                   10293: 
1.405     albertel 10294: =item * &get_users_function()
1.182     matthew  10295: 
                   10296: Used by &bodytag to determine the current users primary role.
                   10297: Returns either 'student','coordinator','admin', or 'author'.
                   10298: 
                   10299: =cut
                   10300: 
                   10301: ###############################################
                   10302: sub get_users_function {
1.815     tempelho 10303:     my $function = 'norole';
1.818     tempelho 10304:     if ($env{'request.role'}=~/^(st)/) {
                   10305:         $function='student';
                   10306:     }
1.907     raeburn  10307:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10308:         $function='coordinator';
                   10309:     }
1.258     albertel 10310:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10311:         $function='admin';
                   10312:     }
1.826     bisitz   10313:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10314:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10315:         $function='author';
                   10316:     }
                   10317:     return $function;
1.54      www      10318: }
1.99      www      10319: 
                   10320: ###############################################
                   10321: 
1.233     raeburn  10322: =pod
                   10323: 
1.821     raeburn  10324: =item * &show_course()
                   10325: 
                   10326: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10327: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10328: 
                   10329: Inputs:
                   10330: None
                   10331: 
                   10332: Outputs:
                   10333: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10334: 
                   10335: =cut
                   10336: 
                   10337: ###############################################
                   10338: sub show_course {
                   10339:     my $course = !$env{'user.adv'};
                   10340:     if (!$env{'user.adv'}) {
                   10341:         foreach my $env (keys(%env)) {
                   10342:             next if ($env !~ m/^user\.priv\./);
                   10343:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10344:                 $course = 0;
                   10345:                 last;
                   10346:             }
                   10347:         }
                   10348:     }
                   10349:     return $course;
                   10350: }
                   10351: 
                   10352: ###############################################
                   10353: 
                   10354: =pod
                   10355: 
1.542     raeburn  10356: =item * &check_user_status()
1.274     raeburn  10357: 
                   10358: Determines current status of supplied role for a
                   10359: specific user. Roles can be active, previous or future.
                   10360: 
                   10361: Inputs: 
                   10362: user's domain, user's username, course's domain,
1.375     raeburn  10363: course's number, optional section ID.
1.274     raeburn  10364: 
                   10365: Outputs:
                   10366: role status: active, previous or future. 
                   10367: 
                   10368: =cut
                   10369: 
                   10370: sub check_user_status {
1.412     raeburn  10371:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10372:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  10373:     my @uroles = keys(%userinfo);
1.274     raeburn  10374:     my $srchstr;
                   10375:     my $active_chk = 'none';
1.412     raeburn  10376:     my $now = time;
1.274     raeburn  10377:     if (@uroles > 0) {
1.908     raeburn  10378:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10379:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10380:         } else {
1.412     raeburn  10381:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10382:         }
                   10383:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10384:             my $role_end = 0;
                   10385:             my $role_start = 0;
                   10386:             $active_chk = 'active';
1.412     raeburn  10387:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10388:                 $role_end = $1;
                   10389:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10390:                     $role_start = $1;
1.274     raeburn  10391:                 }
                   10392:             }
                   10393:             if ($role_start > 0) {
1.412     raeburn  10394:                 if ($now < $role_start) {
1.274     raeburn  10395:                     $active_chk = 'future';
                   10396:                 }
                   10397:             }
                   10398:             if ($role_end > 0) {
1.412     raeburn  10399:                 if ($now > $role_end) {
1.274     raeburn  10400:                     $active_chk = 'previous';
                   10401:                 }
                   10402:             }
                   10403:         }
                   10404:     }
                   10405:     return $active_chk;
                   10406: }
                   10407: 
                   10408: ###############################################
                   10409: 
                   10410: =pod
                   10411: 
1.405     albertel 10412: =item * &get_sections()
1.233     raeburn  10413: 
                   10414: Determines all the sections for a course including
                   10415: sections with students and sections containing other roles.
1.419     raeburn  10416: Incoming parameters: 
                   10417: 
                   10418: 1. domain
                   10419: 2. course number 
                   10420: 3. reference to array containing roles for which sections should 
                   10421: be gathered (optional).
                   10422: 4. reference to array containing status types for which sections 
                   10423: should be gathered (optional).
                   10424: 
                   10425: If the third argument is undefined, sections are gathered for any role. 
                   10426: If the fourth argument is undefined, sections are gathered for any status.
                   10427: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10428:  
1.374     raeburn  10429: Returns section hash (keys are section IDs, values are
                   10430: number of users in each section), subject to the
1.419     raeburn  10431: optional roles filter, optional status filter 
1.233     raeburn  10432: 
                   10433: =cut
                   10434: 
                   10435: ###############################################
                   10436: sub get_sections {
1.419     raeburn  10437:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10438:     if (!defined($cdom) || !defined($cnum)) {
                   10439:         my $cid =  $env{'request.course.id'};
                   10440: 
                   10441: 	return if (!defined($cid));
                   10442: 
                   10443:         $cdom = $env{'course.'.$cid.'.domain'};
                   10444:         $cnum = $env{'course.'.$cid.'.num'};
                   10445:     }
                   10446: 
                   10447:     my %sectioncount;
1.419     raeburn  10448:     my $now = time;
1.240     albertel 10449: 
1.1075.2.33  raeburn  10450:     my $check_students = 1;
                   10451:     my $only_students = 0;
                   10452:     if (ref($possible_roles) eq 'ARRAY') {
                   10453:         if (grep(/^st$/,@{$possible_roles})) {
                   10454:             if (@{$possible_roles} == 1) {
                   10455:                 $only_students = 1;
                   10456:             }
                   10457:         } else {
                   10458:             $check_students = 0;
                   10459:         }
                   10460:     }
                   10461: 
                   10462:     if ($check_students) {
1.276     albertel 10463: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10464: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10465: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10466:         my $start_index = &Apache::loncoursedata::CL_START();
                   10467:         my $end_index = &Apache::loncoursedata::CL_END();
                   10468:         my $status;
1.366     albertel 10469: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10470: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10471: 				                     $data->[$status_index],
                   10472:                                                      $data->[$start_index],
                   10473:                                                      $data->[$end_index]);
                   10474:             if ($stu_status eq 'Active') {
                   10475:                 $status = 'active';
                   10476:             } elsif ($end < $now) {
                   10477:                 $status = 'previous';
                   10478:             } elsif ($start > $now) {
                   10479:                 $status = 'future';
                   10480:             } 
                   10481: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10482:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10483:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10484: 		    $sectioncount{$section}++;
                   10485:                 }
1.240     albertel 10486: 	    }
                   10487: 	}
                   10488:     }
1.1075.2.33  raeburn  10489:     if ($only_students) {
                   10490:         return %sectioncount;
                   10491:     }
1.240     albertel 10492:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10493:     foreach my $user (sort(keys(%courseroles))) {
                   10494: 	if ($user !~ /^(\w{2})/) { next; }
                   10495: 	my ($role) = ($user =~ /^(\w{2})/);
                   10496: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10497: 	my ($section,$status);
1.240     albertel 10498: 	if ($role eq 'cr' &&
                   10499: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10500: 	    $section=$1;
                   10501: 	}
                   10502: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10503: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10504:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10505:         if ($end == -1 && $start == -1) {
                   10506:             next; #deleted role
                   10507:         }
                   10508:         if (!defined($possible_status)) { 
                   10509:             $sectioncount{$section}++;
                   10510:         } else {
                   10511:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10512:                 $status = 'active';
                   10513:             } elsif ($end < $now) {
                   10514:                 $status = 'future';
                   10515:             } elsif ($start > $now) {
                   10516:                 $status = 'previous';
                   10517:             }
                   10518:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10519:                 $sectioncount{$section}++;
                   10520:             }
                   10521:         }
1.233     raeburn  10522:     }
1.366     albertel 10523:     return %sectioncount;
1.233     raeburn  10524: }
                   10525: 
1.274     raeburn  10526: ###############################################
1.294     raeburn  10527: 
                   10528: =pod
1.405     albertel 10529: 
                   10530: =item * &get_course_users()
                   10531: 
1.275     raeburn  10532: Retrieves usernames:domains for users in the specified course
                   10533: with specific role(s), and access status. 
                   10534: 
                   10535: Incoming parameters:
1.277     albertel 10536: 1. course domain
                   10537: 2. course number
                   10538: 3. access status: users must have - either active, 
1.275     raeburn  10539: previous, future, or all.
1.277     albertel 10540: 4. reference to array of permissible roles
1.288     raeburn  10541: 5. reference to array of section restrictions (optional)
                   10542: 6. reference to results object (hash of hashes).
                   10543: 7. reference to optional userdata hash
1.609     raeburn  10544: 8. reference to optional statushash
1.630     raeburn  10545: 9. flag if privileged users (except those set to unhide in
                   10546:    course settings) should be excluded    
1.609     raeburn  10547: Keys of top level results hash are roles.
1.275     raeburn  10548: Keys of inner hashes are username:domain, with 
                   10549: values set to access type.
1.288     raeburn  10550: Optional userdata hash returns an array with arguments in the 
                   10551: same order as loncoursedata::get_classlist() for student data.
                   10552: 
1.609     raeburn  10553: Optional statushash returns
                   10554: 
1.288     raeburn  10555: Entries for end, start, section and status are blank because
                   10556: of the possibility of multiple values for non-student roles.
                   10557: 
1.275     raeburn  10558: =cut
1.405     albertel 10559: 
1.275     raeburn  10560: ###############################################
1.405     albertel 10561: 
1.275     raeburn  10562: sub get_course_users {
1.630     raeburn  10563:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10564:     my %idx = ();
1.419     raeburn  10565:     my %seclists;
1.288     raeburn  10566: 
                   10567:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10568:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10569:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10570:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10571:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10572:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10573:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10574:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10575: 
1.290     albertel 10576:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10577:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10578:         my $now = time;
1.277     albertel 10579:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10580:             my $match = 0;
1.412     raeburn  10581:             my $secmatch = 0;
1.419     raeburn  10582:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10583:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10584:             if ($section eq '') {
                   10585:                 $section = 'none';
                   10586:             }
1.291     albertel 10587:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10588:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10589:                     $secmatch = 1;
                   10590:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10591:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10592:                         $secmatch = 1;
                   10593:                     }
                   10594:                 } else {  
1.419     raeburn  10595: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10596: 		        $secmatch = 1;
                   10597:                     }
1.290     albertel 10598: 		}
1.412     raeburn  10599:                 if (!$secmatch) {
                   10600:                     next;
                   10601:                 }
1.419     raeburn  10602:             }
1.275     raeburn  10603:             if (defined($$types{'active'})) {
1.288     raeburn  10604:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10605:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10606:                     $match = 1;
1.275     raeburn  10607:                 }
                   10608:             }
                   10609:             if (defined($$types{'previous'})) {
1.609     raeburn  10610:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10611:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10612:                     $match = 1;
1.275     raeburn  10613:                 }
                   10614:             }
                   10615:             if (defined($$types{'future'})) {
1.609     raeburn  10616:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10617:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10618:                     $match = 1;
1.275     raeburn  10619:                 }
                   10620:             }
1.609     raeburn  10621:             if ($match) {
                   10622:                 push(@{$seclists{$student}},$section);
                   10623:                 if (ref($userdata) eq 'HASH') {
                   10624:                     $$userdata{$student} = $$classlist{$student};
                   10625:                 }
                   10626:                 if (ref($statushash) eq 'HASH') {
                   10627:                     $statushash->{$student}{'st'}{$section} = $status;
                   10628:                 }
1.288     raeburn  10629:             }
1.275     raeburn  10630:         }
                   10631:     }
1.412     raeburn  10632:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10633:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10634:         my $now = time;
1.609     raeburn  10635:         my %displaystatus = ( previous => 'Expired',
                   10636:                               active   => 'Active',
                   10637:                               future   => 'Future',
                   10638:                             );
1.1075.2.36  raeburn  10639:         my (%nothide,@possdoms);
1.630     raeburn  10640:         if ($hidepriv) {
                   10641:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10642:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10643:                 if ($user !~ /:/) {
                   10644:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10645:                 } else {
                   10646:                     $nothide{$user} = 1;
                   10647:                 }
                   10648:             }
1.1075.2.36  raeburn  10649:             my @possdoms = ($cdom);
                   10650:             if ($coursehash{'checkforpriv'}) {
                   10651:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10652:             }
1.630     raeburn  10653:         }
1.439     raeburn  10654:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10655:             my $match = 0;
1.412     raeburn  10656:             my $secmatch = 0;
1.439     raeburn  10657:             my $status;
1.412     raeburn  10658:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10659:             $user =~ s/:$//;
1.439     raeburn  10660:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10661:             if ($end == -1 || $start == -1) {
                   10662:                 next;
                   10663:             }
                   10664:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10665:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10666:                 my ($uname,$udom) = split(/:/,$user);
                   10667:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10668:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10669:                         $secmatch = 1;
                   10670:                     } elsif ($usec eq '') {
1.420     albertel 10671:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10672:                             $secmatch = 1;
                   10673:                         }
                   10674:                     } else {
                   10675:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10676:                             $secmatch = 1;
                   10677:                         }
                   10678:                     }
                   10679:                     if (!$secmatch) {
                   10680:                         next;
                   10681:                     }
1.288     raeburn  10682:                 }
1.419     raeburn  10683:                 if ($usec eq '') {
                   10684:                     $usec = 'none';
                   10685:                 }
1.275     raeburn  10686:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10687:                     if ($hidepriv) {
1.1075.2.36  raeburn  10688:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10689:                             (!$nothide{$uname.':'.$udom})) {
                   10690:                             next;
                   10691:                         }
                   10692:                     }
1.503     raeburn  10693:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10694:                         $status = 'previous';
                   10695:                     } elsif ($start > $now) {
                   10696:                         $status = 'future';
                   10697:                     } else {
                   10698:                         $status = 'active';
                   10699:                     }
1.277     albertel 10700:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10701:                         if ($status eq $type) {
1.420     albertel 10702:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10703:                                 push(@{$$users{$role}{$user}},$type);
                   10704:                             }
1.288     raeburn  10705:                             $match = 1;
                   10706:                         }
                   10707:                     }
1.419     raeburn  10708:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10709:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10710: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10711:                         }
1.420     albertel 10712:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10713:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10714:                         }
1.609     raeburn  10715:                         if (ref($statushash) eq 'HASH') {
                   10716:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10717:                         }
1.275     raeburn  10718:                     }
                   10719:                 }
                   10720:             }
                   10721:         }
1.290     albertel 10722:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10723:             if ((defined($cdom)) && (defined($cnum))) {
                   10724:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10725:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10726:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10727:                     next if ($owner eq '');
                   10728:                     my ($ownername,$ownerdom);
                   10729:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10730:                         $ownername = $1;
                   10731:                         $ownerdom = $2;
                   10732:                     } else {
                   10733:                         $ownername = $owner;
                   10734:                         $ownerdom = $cdom;
                   10735:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10736:                     }
                   10737:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10738:                     if (defined($userdata) && 
1.609     raeburn  10739: 			!exists($$userdata{$owner})) {
                   10740: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10741:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10742:                             push(@{$seclists{$owner}},'none');
                   10743:                         }
                   10744:                         if (ref($statushash) eq 'HASH') {
                   10745:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10746:                         }
1.290     albertel 10747: 		    }
1.279     raeburn  10748:                 }
                   10749:             }
                   10750:         }
1.419     raeburn  10751:         foreach my $user (keys(%seclists)) {
                   10752:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10753:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10754:         }
1.275     raeburn  10755:     }
                   10756:     return;
                   10757: }
                   10758: 
1.288     raeburn  10759: sub get_user_info {
                   10760:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10761:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10762: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10763:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10764:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10765:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10766:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10767:     return;
                   10768: }
1.275     raeburn  10769: 
1.472     raeburn  10770: ###############################################
                   10771: 
                   10772: =pod
                   10773: 
                   10774: =item * &get_user_quota()
                   10775: 
1.1075.2.41  raeburn  10776: Retrieves quota assigned for storage of user files.
                   10777: Default is to report quota for portfolio files.
1.472     raeburn  10778: 
                   10779: Incoming parameters:
                   10780: 1. user's username
                   10781: 2. user's domain
1.1075.2.41  raeburn  10782: 3. quota name - portfolio, author, or course
                   10783:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10784: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10785:    course
1.472     raeburn  10786: 
                   10787: Returns:
1.1075.2.58  raeburn  10788: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10789: 2. (Optional) Type of setting: custom or default
                   10790:    (individually assigned or default for user's 
                   10791:    institutional status).
                   10792: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10793:    or student - types as defined in localenroll::inst_usertypes 
                   10794:    for user's domain, which determines default quota for user.
                   10795: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10796: 
                   10797: If a value has been stored in the user's environment, 
1.536     raeburn  10798: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10799: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10800: 
                   10801: =cut
                   10802: 
                   10803: ###############################################
                   10804: 
                   10805: 
                   10806: sub get_user_quota {
1.1075.2.42  raeburn  10807:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10808:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10809:     if (!defined($udom)) {
                   10810:         $udom = $env{'user.domain'};
                   10811:     }
                   10812:     if (!defined($uname)) {
                   10813:         $uname = $env{'user.name'};
                   10814:     }
                   10815:     if (($udom eq '' || $uname eq '') ||
                   10816:         ($udom eq 'public') && ($uname eq 'public')) {
                   10817:         $quota = 0;
1.536     raeburn  10818:         $quotatype = 'default';
                   10819:         $defquota = 0; 
1.472     raeburn  10820:     } else {
1.536     raeburn  10821:         my $inststatus;
1.1075.2.41  raeburn  10822:         if ($quotaname eq 'course') {
                   10823:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10824:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10825:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10826:             } else {
                   10827:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10828:                 $quota = $cenv{'internal.uploadquota'};
                   10829:             }
1.536     raeburn  10830:         } else {
1.1075.2.41  raeburn  10831:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10832:                 if ($quotaname eq 'author') {
                   10833:                     $quota = $env{'environment.authorquota'};
                   10834:                 } else {
                   10835:                     $quota = $env{'environment.portfolioquota'};
                   10836:                 }
                   10837:                 $inststatus = $env{'environment.inststatus'};
                   10838:             } else {
                   10839:                 my %userenv = 
                   10840:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10841:                                          'authorquota','inststatus'],$udom,$uname);
                   10842:                 my ($tmp) = keys(%userenv);
                   10843:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10844:                     if ($quotaname eq 'author') {
                   10845:                         $quota = $userenv{'authorquota'};
                   10846:                     } else {
                   10847:                         $quota = $userenv{'portfolioquota'};
                   10848:                     }
                   10849:                     $inststatus = $userenv{'inststatus'};
                   10850:                 } else {
                   10851:                     undef(%userenv);
                   10852:                 }
                   10853:             }
                   10854:         }
                   10855:         if ($quota eq '' || wantarray) {
                   10856:             if ($quotaname eq 'course') {
                   10857:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10858:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10859:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10860:                     $defquota = $domdefs{$crstype.'quota'};
                   10861:                 }
                   10862:                 if ($defquota eq '') {
                   10863:                     $defquota = 500;
                   10864:                 }
1.1075.2.41  raeburn  10865:             } else {
                   10866:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10867:             }
                   10868:             if ($quota eq '') {
                   10869:                 $quota = $defquota;
                   10870:                 $quotatype = 'default';
                   10871:             } else {
                   10872:                 $quotatype = 'custom';
                   10873:             }
1.472     raeburn  10874:         }
                   10875:     }
1.536     raeburn  10876:     if (wantarray) {
                   10877:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10878:     } else {
                   10879:         return $quota;
                   10880:     }
1.472     raeburn  10881: }
                   10882: 
                   10883: ###############################################
                   10884: 
                   10885: =pod
                   10886: 
                   10887: =item * &default_quota()
                   10888: 
1.536     raeburn  10889: Retrieves default quota assigned for storage of user portfolio files,
                   10890: given an (optional) user's institutional status.
1.472     raeburn  10891: 
                   10892: Incoming parameters:
1.1075.2.42  raeburn  10893: 
1.472     raeburn  10894: 1. domain
1.536     raeburn  10895: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10896:    status types (e.g., faculty, staff, student etc.)
                   10897:    which apply to the user for whom the default is being retrieved.
                   10898:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10899:    default quota will be returned.
                   10900: 3.  quota name - portfolio, author, or course
                   10901:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10902: 
                   10903: Returns:
1.1075.2.42  raeburn  10904: 
1.1075.2.58  raeburn  10905: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10906: 2. (Optional) institutional type which determined the value of the
                   10907:    default quota.
1.472     raeburn  10908: 
                   10909: If a value has been stored in the domain's configuration db,
                   10910: it will return that, otherwise it returns 20 (for backwards 
                   10911: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10912: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10913: 
1.536     raeburn  10914: If the user's status includes multiple types (e.g., staff and student),
                   10915: the largest default quota which applies to the user determines the
                   10916: default quota returned.
                   10917: 
1.472     raeburn  10918: =cut
                   10919: 
                   10920: ###############################################
                   10921: 
                   10922: 
                   10923: sub default_quota {
1.1075.2.41  raeburn  10924:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10925:     my ($defquota,$settingstatus);
                   10926:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10927:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10928:     my $key = 'defaultquota';
                   10929:     if ($quotaname eq 'author') {
                   10930:         $key = 'authorquota';
                   10931:     }
1.622     raeburn  10932:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10933:         if ($inststatus ne '') {
1.765     raeburn  10934:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10935:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10936:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10937:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10938:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10939:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10940:                             $settingstatus = $item;
1.1075.2.41  raeburn  10941:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10942:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10943:                             $settingstatus = $item;
                   10944:                         }
                   10945:                     }
1.1075.2.41  raeburn  10946:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10947:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10948:                         if ($defquota eq '') {
                   10949:                             $defquota = $quotahash{'quotas'}{$item};
                   10950:                             $settingstatus = $item;
                   10951:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10952:                             $defquota = $quotahash{'quotas'}{$item};
                   10953:                             $settingstatus = $item;
                   10954:                         }
1.536     raeburn  10955:                     }
                   10956:                 }
                   10957:             }
                   10958:         }
                   10959:         if ($defquota eq '') {
1.1075.2.41  raeburn  10960:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10961:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10962:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10963:                 $defquota = $quotahash{'quotas'}{'default'};
                   10964:             }
1.536     raeburn  10965:             $settingstatus = 'default';
1.1075.2.42  raeburn  10966:             if ($defquota eq '') {
                   10967:                 if ($quotaname eq 'author') {
                   10968:                     $defquota = 500;
                   10969:                 }
                   10970:             }
1.536     raeburn  10971:         }
                   10972:     } else {
                   10973:         $settingstatus = 'default';
1.1075.2.41  raeburn  10974:         if ($quotaname eq 'author') {
                   10975:             $defquota = 500;
                   10976:         } else {
                   10977:             $defquota = 20;
                   10978:         }
1.536     raeburn  10979:     }
                   10980:     if (wantarray) {
                   10981:         return ($defquota,$settingstatus);
1.472     raeburn  10982:     } else {
1.536     raeburn  10983:         return $defquota;
1.472     raeburn  10984:     }
                   10985: }
                   10986: 
1.1075.2.41  raeburn  10987: ###############################################
                   10988: 
                   10989: =pod
                   10990: 
1.1075.2.42  raeburn  10991: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  10992: 
                   10993: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  10994: of existing file within authoring space will cause quota for the authoring
                   10995: space to be exceeded.
                   10996: 
                   10997: Same, if upload of a file directly to a course/community via Course Editor
                   10998: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  10999: 
1.1075.2.61  raeburn  11000: Inputs: 7 
1.1075.2.42  raeburn  11001: 1. username or coursenum
1.1075.2.41  raeburn  11002: 2. domain
1.1075.2.42  raeburn  11003: 3. context ('author' or 'course')
1.1075.2.41  raeburn  11004: 4. filename of file for which action is being requested
                   11005: 5. filesize (kB) of file
                   11006: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  11007: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  11008: 
                   11009: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   11010:          otherwise return null.
                   11011: 
1.1075.2.42  raeburn  11012: =back
                   11013: 
1.1075.2.41  raeburn  11014: =cut
                   11015: 
1.1075.2.42  raeburn  11016: sub excess_filesize_warning {
1.1075.2.59  raeburn  11017:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  11018:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  11019:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  11020:     if ($context eq 'author') {
                   11021:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11022:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11023:     } else {
                   11024:         foreach my $subdir ('docs','supplemental') {
                   11025:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11026:         }
                   11027:     }
1.1075.2.41  raeburn  11028:     $disk_quota = int($disk_quota * 1000);
                   11029:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  11030:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  11031:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  11032:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11033:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  11034:                             $disk_quota,$current_disk_usage).
                   11035:                '</p>';
                   11036:     }
                   11037:     return;
                   11038: }
                   11039: 
                   11040: ###############################################
                   11041: 
                   11042: 
1.384     raeburn  11043: sub get_secgrprole_info {
                   11044:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11045:     my %sections_count = &get_sections($cdom,$cnum);
                   11046:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11047:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11048:     my @groups = sort(keys(%curr_groups));
                   11049:     my $allroles = [];
                   11050:     my $rolehash;
                   11051:     my $accesshash = {
                   11052:                      active => 'Currently has access',
                   11053:                      future => 'Will have future access',
                   11054:                      previous => 'Previously had access',
                   11055:                   };
                   11056:     if ($needroles) {
                   11057:         $rolehash = {'all' => 'all'};
1.385     albertel 11058:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11059: 	if (&Apache::lonnet::error(%user_roles)) {
                   11060: 	    undef(%user_roles);
                   11061: 	}
                   11062:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11063:             my ($role)=split(/\:/,$item,2);
                   11064:             if ($role eq 'cr') { next; }
                   11065:             if ($role =~ /^cr/) {
                   11066:                 $$rolehash{$role} = (split('/',$role))[3];
                   11067:             } else {
                   11068:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11069:             }
                   11070:         }
                   11071:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11072:             push(@{$allroles},$key);
                   11073:         }
                   11074:         push (@{$allroles},'st');
                   11075:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11076:     }
                   11077:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11078: }
                   11079: 
1.555     raeburn  11080: sub user_picker {
1.1075.2.127  raeburn  11081:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11082:     my $currdom = $dom;
1.1075.2.114  raeburn  11083:     my @alldoms = &Apache::lonnet::all_domains();
                   11084:     if (@alldoms == 1) {
                   11085:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11086:                                                ['directorysrch'],$alldoms[0]);
                   11087:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11088:         my $showdom = $domdesc;
                   11089:         if ($showdom eq '') {
                   11090:             $showdom = $dom;
                   11091:         }
                   11092:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11093:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11094:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11095:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11096:             }
                   11097:         }
                   11098:     }
1.555     raeburn  11099:     my %curr_selected = (
                   11100:                         srchin => 'dom',
1.580     raeburn  11101:                         srchby => 'lastname',
1.555     raeburn  11102:                       );
                   11103:     my $srchterm;
1.625     raeburn  11104:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11105:         if ($srch->{'srchby'} ne '') {
                   11106:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11107:         }
                   11108:         if ($srch->{'srchin'} ne '') {
                   11109:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11110:         }
                   11111:         if ($srch->{'srchtype'} ne '') {
                   11112:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11113:         }
                   11114:         if ($srch->{'srchdomain'} ne '') {
                   11115:             $currdom = $srch->{'srchdomain'};
                   11116:         }
                   11117:         $srchterm = $srch->{'srchterm'};
                   11118:     }
1.1075.2.98  raeburn  11119:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11120:                     'usr'       => 'Search criteria',
1.563     raeburn  11121:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11122:                     'uname'     => 'username',
                   11123:                     'lastname'  => 'last name',
1.555     raeburn  11124:                     'lastfirst' => 'last name, first name',
1.558     albertel 11125:                     'crs'       => 'in this course',
1.576     raeburn  11126:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11127:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11128:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11129:                     'exact'     => 'is',
                   11130:                     'contains'  => 'contains',
1.569     raeburn  11131:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  11132:                                        );
                   11133:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11134:                     'youm'      => "You must include some text to search for.",
                   11135:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11136:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11137:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11138:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11139:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11140:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11141:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11142:                                        );
1.1075.2.98  raeburn  11143:     &html_escape(\%html_lt);
                   11144:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  11145:     my $domform;
1.1075.2.126  raeburn  11146:     my $allow_blank = 1;
1.1075.2.115  raeburn  11147:     if ($fixeddom) {
1.1075.2.126  raeburn  11148:         $allow_blank = 0;
                   11149:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  11150:     } else {
1.1075.2.126  raeburn  11151:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  11152:     }
1.563     raeburn  11153:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11154: 
                   11155:     my @srchins = ('crs','dom','alc','instd');
                   11156: 
                   11157:     foreach my $option (@srchins) {
                   11158:         # FIXME 'alc' option unavailable until 
                   11159:         #       loncreateuser::print_user_query_page()
                   11160:         #       has been completed.
                   11161:         next if ($option eq 'alc');
1.880     raeburn  11162:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11163:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  11164:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11165:         if ($curr_selected{'srchin'} eq $option) {
                   11166:             $srchinsel .= ' 
1.1075.2.98  raeburn  11167:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11168:         } else {
                   11169:             $srchinsel .= '
1.1075.2.98  raeburn  11170:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11171:         }
1.555     raeburn  11172:     }
1.563     raeburn  11173:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11174: 
                   11175:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11176:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11177:         if ($curr_selected{'srchby'} eq $option) {
                   11178:             $srchbysel .= '
1.1075.2.98  raeburn  11179:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11180:         } else {
                   11181:             $srchbysel .= '
1.1075.2.98  raeburn  11182:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11183:          }
                   11184:     }
                   11185:     $srchbysel .= "\n  </select>\n";
                   11186: 
                   11187:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11188:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11189:         if ($curr_selected{'srchtype'} eq $option) {
                   11190:             $srchtypesel .= '
1.1075.2.98  raeburn  11191:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11192:         } else {
                   11193:             $srchtypesel .= '
1.1075.2.98  raeburn  11194:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11195:         }
                   11196:     }
                   11197:     $srchtypesel .= "\n  </select>\n";
                   11198: 
1.558     albertel 11199:     my ($newuserscript,$new_user_create);
1.994     raeburn  11200:     my $context_dom = $env{'request.role.domain'};
                   11201:     if ($context eq 'requestcrs') {
                   11202:         if ($env{'form.coursedom'} ne '') { 
                   11203:             $context_dom = $env{'form.coursedom'};
                   11204:         }
                   11205:     }
1.556     raeburn  11206:     if ($forcenewuser) {
1.576     raeburn  11207:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11208:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11209:                 if ($cancreate) {
                   11210:                     $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>';
                   11211:                 } else {
1.799     bisitz   11212:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11213:                     my %usertypetext = (
                   11214:                         official   => 'institutional',
                   11215:                         unofficial => 'non-institutional',
                   11216:                     );
1.799     bisitz   11217:                     $new_user_create = '<p class="LC_warning">'
                   11218:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11219:                                       .' '
                   11220:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11221:                                           ,'<a href="'.$helplink.'">','</a>')
                   11222:                                       .'</p><br />';
1.627     raeburn  11223:                 }
1.576     raeburn  11224:             }
                   11225:         }
                   11226: 
1.556     raeburn  11227:         $newuserscript = <<"ENDSCRIPT";
                   11228: 
1.570     raeburn  11229: function setSearch(createnew,callingForm) {
1.556     raeburn  11230:     if (createnew == 1) {
1.570     raeburn  11231:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11232:             if (callingForm.srchby.options[i].value == 'uname') {
                   11233:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11234:             }
                   11235:         }
1.570     raeburn  11236:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11237:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11238: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11239:             }
                   11240:         }
1.570     raeburn  11241:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11242:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11243:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11244:             }
                   11245:         }
1.570     raeburn  11246:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11247:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11248:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11249:             }
                   11250:         }
                   11251:     }
                   11252: }
                   11253: ENDSCRIPT
1.558     albertel 11254: 
1.556     raeburn  11255:     }
                   11256: 
1.555     raeburn  11257:     my $output = <<"END_BLOCK";
1.556     raeburn  11258: <script type="text/javascript">
1.824     bisitz   11259: // <![CDATA[
1.570     raeburn  11260: function validateEntry(callingForm) {
1.558     albertel 11261: 
1.556     raeburn  11262:     var checkok = 1;
1.558     albertel 11263:     var srchin;
1.570     raeburn  11264:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11265: 	if ( callingForm.srchin[i].checked ) {
                   11266: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11267: 	}
                   11268:     }
                   11269: 
1.570     raeburn  11270:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11271:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11272:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11273:     var srchterm =  callingForm.srchterm.value;
                   11274:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11275:     var msg = "";
                   11276: 
                   11277:     if (srchterm == "") {
                   11278:         checkok = 0;
1.1075.2.98  raeburn  11279:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11280:     }
                   11281: 
1.569     raeburn  11282:     if (srchtype== 'begins') {
                   11283:         if (srchterm.length < 2) {
                   11284:             checkok = 0;
1.1075.2.98  raeburn  11285:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11286:         }
                   11287:     }
                   11288: 
1.556     raeburn  11289:     if (srchtype== 'contains') {
                   11290:         if (srchterm.length < 3) {
                   11291:             checkok = 0;
1.1075.2.98  raeburn  11292:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11293:         }
                   11294:     }
                   11295:     if (srchin == 'instd') {
                   11296:         if (srchdomain == '') {
                   11297:             checkok = 0;
1.1075.2.98  raeburn  11298:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11299:         }
                   11300:     }
                   11301:     if (srchin == 'dom') {
                   11302:         if (srchdomain == '') {
                   11303:             checkok = 0;
1.1075.2.98  raeburn  11304:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11305:         }
                   11306:     }
                   11307:     if (srchby == 'lastfirst') {
                   11308:         if (srchterm.indexOf(",") == -1) {
                   11309:             checkok = 0;
1.1075.2.98  raeburn  11310:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11311:         }
                   11312:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11313:             checkok = 0;
1.1075.2.98  raeburn  11314:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11315:         }
                   11316:     }
                   11317:     if (checkok == 0) {
1.1075.2.98  raeburn  11318:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11319:         return;
                   11320:     }
                   11321:     if (checkok == 1) {
1.570     raeburn  11322:         callingForm.submit();
1.556     raeburn  11323:     }
                   11324: }
                   11325: 
                   11326: $newuserscript
                   11327: 
1.824     bisitz   11328: // ]]>
1.556     raeburn  11329: </script>
1.558     albertel 11330: 
                   11331: $new_user_create
                   11332: 
1.555     raeburn  11333: END_BLOCK
1.558     albertel 11334: 
1.876     raeburn  11335:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  11336:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11337:                $domform.
                   11338:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  11339:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11340:                $srchbysel.
                   11341:                $srchtypesel. 
                   11342:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11343:                $srchinsel.
                   11344:                &Apache::lonhtmlcommon::row_closure(1). 
                   11345:                &Apache::lonhtmlcommon::end_pick_box().
                   11346:                '<br />';
1.1075.2.114  raeburn  11347:     return ($output,1);
1.555     raeburn  11348: }
                   11349: 
1.612     raeburn  11350: sub user_rule_check {
1.615     raeburn  11351:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  11352:     my ($response,%inst_response);
1.612     raeburn  11353:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  11354:         if (keys(%{$usershash}) > 1) {
                   11355:             my (%by_username,%by_id,%userdoms);
                   11356:             my $checkid;
1.612     raeburn  11357:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  11358:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11359:                     $checkid = 1;
                   11360:                 }
                   11361:             }
                   11362:             foreach my $user (keys(%{$usershash})) {
                   11363:                 my ($uname,$udom) = split(/:/,$user);
                   11364:                 if ($checkid) {
                   11365:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11366:                         if ($usershash->{$user}->{'id'} ne '') {
                   11367:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   11368:                             $userdoms{$udom} = 1;
                   11369:                             if (ref($inst_results) eq 'HASH') {
                   11370:                                 $inst_results->{$uname.':'.$udom} = {};
                   11371:                             }
                   11372:                         }
                   11373:                     }
                   11374:                 } else {
                   11375:                     $by_username{$udom}{$uname} = 1;
                   11376:                     $userdoms{$udom} = 1;
                   11377:                     if (ref($inst_results) eq 'HASH') {
                   11378:                         $inst_results->{$uname.':'.$udom} = {};
                   11379:                     }
                   11380:                 }
                   11381:             }
                   11382:             foreach my $udom (keys(%userdoms)) {
                   11383:                 if (!$got_rules->{$udom}) {
                   11384:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11385:                                                              ['usercreation'],$udom);
                   11386:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11387:                         foreach my $item ('username','id') {
                   11388:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11389:                                 $$curr_rules{$udom}{$item} =
                   11390:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   11391:                             }
                   11392:                         }
                   11393:                     }
                   11394:                     $got_rules->{$udom} = 1;
                   11395:                 }
                   11396:             }
                   11397:             if ($checkid) {
                   11398:                 foreach my $udom (keys(%by_id)) {
                   11399:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11400:                     if ($outcome eq 'ok') {
                   11401:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11402:                             my $uname = $by_id{$udom}{$id};
                   11403:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11404:                         }
                   11405:                         if (ref($results) eq 'HASH') {
                   11406:                             foreach my $uname (keys(%{$results})) {
                   11407:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11408:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11409:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11410:                                 }
                   11411:                             }
                   11412:                         }
                   11413:                     }
1.612     raeburn  11414:                 }
1.615     raeburn  11415:             } else {
1.1075.2.99  raeburn  11416:                 foreach my $udom (keys(%by_username)) {
                   11417:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11418:                     if ($outcome eq 'ok') {
                   11419:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11420:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11421:                         }
                   11422:                         if (ref($results) eq 'HASH') {
                   11423:                             foreach my $uname (keys(%{$results})) {
                   11424:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11425:                             }
                   11426:                         }
                   11427:                     }
                   11428:                 }
1.612     raeburn  11429:             }
1.1075.2.99  raeburn  11430:         } elsif (keys(%{$usershash}) == 1) {
                   11431:             my $user = (keys(%{$usershash}))[0];
                   11432:             my ($uname,$udom) = split(/:/,$user);
                   11433:             if (($udom ne '') && ($uname ne '')) {
                   11434:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11435:                     if (ref($checks) eq 'HASH') {
                   11436:                         if (defined($checks->{'username'})) {
                   11437:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   11438:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11439:                         } elsif (defined($checks->{'id'})) {
                   11440:                             if ($usershash->{$user}->{'id'} ne '') {
                   11441:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11442:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11443:                                                                   $usershash->{$user}->{'id'});
                   11444:                             } else {
                   11445:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11446:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11447:                             }
                   11448:                         }
                   11449:                     } else {
                   11450:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11451:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11452:                        return;
                   11453:                     }
                   11454:                     if (!$got_rules->{$udom}) {
                   11455:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11456:                                                                  ['usercreation'],$udom);
                   11457:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11458:                             foreach my $item ('username','id') {
                   11459:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11460:                                    $$curr_rules{$udom}{$item} =
                   11461:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11462:                                 }
                   11463:                             }
1.585     raeburn  11464:                         }
1.1075.2.99  raeburn  11465:                         $got_rules->{$udom} = 1;
1.585     raeburn  11466:                     }
                   11467:                 }
1.1075.2.99  raeburn  11468:             } else {
                   11469:                 return;
                   11470:             }
                   11471:         } else {
                   11472:             return;
                   11473:         }
                   11474:         foreach my $user (keys(%{$usershash})) {
                   11475:             my ($uname,$udom) = split(/:/,$user);
                   11476:             next if (($udom eq '') || ($uname eq ''));
                   11477:             my $id;
                   11478:             if (ref($inst_results) eq 'HASH') {
                   11479:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11480:                     $id = $inst_results->{$user}->{'id'};
                   11481:                 }
                   11482:             }
                   11483:             if ($id eq '') {
                   11484:                 if (ref($usershash->{$user})) {
                   11485:                     $id = $usershash->{$user}->{'id'};
                   11486:                 }
1.585     raeburn  11487:             }
1.612     raeburn  11488:             foreach my $item (keys(%{$checks})) {
                   11489:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11490:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11491:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  11492:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11493:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11494:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11495:                                 if ($rule_check{$rule}) {
                   11496:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  11497:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11498:                                         if (ref($inst_results) eq 'HASH') {
                   11499:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11500:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11501:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  11502:                                                 } elsif ($item eq 'id') {
                   11503:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11504:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11505:                                                     }
1.615     raeburn  11506:                                                 }
1.612     raeburn  11507:                                             }
                   11508:                                         }
1.615     raeburn  11509:                                     }
                   11510:                                     last;
1.585     raeburn  11511:                                 }
                   11512:                             }
                   11513:                         }
                   11514:                     }
                   11515:                 }
                   11516:             }
                   11517:         }
                   11518:     }
1.612     raeburn  11519:     return;
                   11520: }
                   11521: 
                   11522: sub user_rule_formats {
                   11523:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11524:     my %text = ( 
                   11525:                  'username' => 'Usernames',
                   11526:                  'id'       => 'IDs',
                   11527:                );
                   11528:     my $output;
                   11529:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11530:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11531:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11532:             $output = '<br />'.
                   11533:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11534:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11535:                       ' <ul>';
1.612     raeburn  11536:             foreach my $rule (@{$ruleorder}) {
                   11537:                 if (ref($curr_rules) eq 'ARRAY') {
                   11538:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11539:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11540:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11541:                                         $rules->{$rule}{'desc'}.'</li>';
                   11542:                         }
                   11543:                     }
                   11544:                 }
                   11545:             }
                   11546:             $output .= '</ul>';
                   11547:         }
                   11548:     }
                   11549:     return $output;
                   11550: }
                   11551: 
                   11552: sub instrule_disallow_msg {
1.615     raeburn  11553:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11554:     my $response;
                   11555:     my %text = (
                   11556:                   item   => 'username',
                   11557:                   items  => 'usernames',
                   11558:                   match  => 'matches',
                   11559:                   do     => 'does',
                   11560:                   action => 'a username',
                   11561:                   one    => 'one',
                   11562:                );
                   11563:     if ($count > 1) {
                   11564:         $text{'item'} = 'usernames';
                   11565:         $text{'match'} ='match';
                   11566:         $text{'do'} = 'do';
                   11567:         $text{'action'} = 'usernames',
                   11568:         $text{'one'} = 'ones';
                   11569:     }
                   11570:     if ($checkitem eq 'id') {
                   11571:         $text{'items'} = 'IDs';
                   11572:         $text{'item'} = 'ID';
                   11573:         $text{'action'} = 'an ID';
1.615     raeburn  11574:         if ($count > 1) {
                   11575:             $text{'item'} = 'IDs';
                   11576:             $text{'action'} = 'IDs';
                   11577:         }
1.612     raeburn  11578:     }
1.674     bisitz   11579:     $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  11580:     if ($mode eq 'upload') {
                   11581:         if ($checkitem eq 'username') {
                   11582:             $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'}.");
                   11583:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11584:             $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  11585:         }
1.669     raeburn  11586:     } elsif ($mode eq 'selfcreate') {
                   11587:         if ($checkitem eq 'id') {
                   11588:             $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.");
                   11589:         }
1.615     raeburn  11590:     } else {
                   11591:         if ($checkitem eq 'username') {
                   11592:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11593:         } elsif ($checkitem eq 'id') {
                   11594:             $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.");
                   11595:         }
1.612     raeburn  11596:     }
                   11597:     return $response;
1.585     raeburn  11598: }
                   11599: 
1.624     raeburn  11600: sub personal_data_fieldtitles {
                   11601:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11602:                         id => 'Student/Employee ID',
                   11603:                         permanentemail => 'E-mail address',
                   11604:                         lastname => 'Last Name',
                   11605:                         firstname => 'First Name',
                   11606:                         middlename => 'Middle Name',
                   11607:                         generation => 'Generation',
                   11608:                         gen => 'Generation',
1.765     raeburn  11609:                         inststatus => 'Affiliation',
1.624     raeburn  11610:                    );
                   11611:     return %fieldtitles;
                   11612: }
                   11613: 
1.642     raeburn  11614: sub sorted_inst_types {
                   11615:     my ($dom) = @_;
1.1075.2.70  raeburn  11616:     my ($usertypes,$order);
                   11617:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11618:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11619:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11620:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11621:     } else {
                   11622:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11623:     }
1.642     raeburn  11624:     my $othertitle = &mt('All users');
                   11625:     if ($env{'request.course.id'}) {
1.668     raeburn  11626:         $othertitle  = &mt('Any users');
1.642     raeburn  11627:     }
                   11628:     my @types;
                   11629:     if (ref($order) eq 'ARRAY') {
                   11630:         @types = @{$order};
                   11631:     }
                   11632:     if (@types == 0) {
                   11633:         if (ref($usertypes) eq 'HASH') {
                   11634:             @types = sort(keys(%{$usertypes}));
                   11635:         }
                   11636:     }
                   11637:     if (keys(%{$usertypes}) > 0) {
                   11638:         $othertitle = &mt('Other users');
                   11639:     }
                   11640:     return ($othertitle,$usertypes,\@types);
                   11641: }
                   11642: 
1.645     raeburn  11643: sub get_institutional_codes {
1.1075.2.157  raeburn  11644:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11645: # Get complete list of course sections to update
                   11646:     my @currsections = ();
                   11647:     my @currxlists = ();
1.1075.2.157  raeburn  11648:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11649:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11650:     my $crskey = $crs.':'.$coursecode;
                   11651:     @{$unclutteredsec{$crskey}} = ();
                   11652:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11653: 
                   11654:     if ($$settings{'internal.sectionnums'} ne '') {
                   11655:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11656:     }
                   11657: 
                   11658:     if ($$settings{'internal.crosslistings'} ne '') {
                   11659:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11660:     }
                   11661: 
                   11662:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11663:         foreach my $xl (@currxlists) {
                   11664:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11665:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11666:                     push(@{$allcourses},$1);
1.645     raeburn  11667:                     $$LC_code{$1} = $2;
                   11668:                 }
                   11669:             }
                   11670:         }
                   11671:     }
1.1075.2.157  raeburn  11672: 
1.645     raeburn  11673:     if (@currsections > 0) {
1.1075.2.157  raeburn  11674:         foreach my $sec (@currsections) {
                   11675:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11676:                 my $instsec = $1;
1.645     raeburn  11677:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11678:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11679:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11680:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11681:                 }
                   11682:             }
                   11683:         }
                   11684:     }
                   11685: 
                   11686:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11687:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11688:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11689:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11690:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11691:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11692:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11693:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11694:                 }
                   11695:             }
                   11696:         }
                   11697:     }
                   11698:     return;
                   11699: }
                   11700: 
1.971     raeburn  11701: sub get_standard_codeitems {
                   11702:     return ('Year','Semester','Department','Number','Section');
                   11703: }
                   11704: 
1.112     bowersj2 11705: =pod
                   11706: 
1.780     raeburn  11707: =head1 Slot Helpers
                   11708: 
                   11709: =over 4
                   11710: 
                   11711: =item * sorted_slots()
                   11712: 
1.1040    raeburn  11713: Sorts an array of slot names in order of an optional sort key,
                   11714: default sort is by slot start time (earliest first). 
1.780     raeburn  11715: 
                   11716: Inputs:
                   11717: 
                   11718: =over 4
                   11719: 
                   11720: slotsarr  - Reference to array of unsorted slot names.
                   11721: 
                   11722: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11723: 
1.1040    raeburn  11724: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11725: 
1.549     albertel 11726: =back
                   11727: 
1.780     raeburn  11728: Returns:
                   11729: 
                   11730: =over 4
                   11731: 
1.1040    raeburn  11732: sorted   - An array of slot names sorted by a specified sort key 
                   11733:            (default sort key is start time of the slot).
1.780     raeburn  11734: 
                   11735: =back
                   11736: 
                   11737: =cut
                   11738: 
                   11739: 
                   11740: sub sorted_slots {
1.1040    raeburn  11741:     my ($slotsarr,$slots,$sortkey) = @_;
                   11742:     if ($sortkey eq '') {
                   11743:         $sortkey = 'starttime';
                   11744:     }
1.780     raeburn  11745:     my @sorted;
                   11746:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11747:         @sorted =
                   11748:             sort {
                   11749:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11750:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11751:                      }
                   11752:                      if (ref($slots->{$a})) { return -1;}
                   11753:                      if (ref($slots->{$b})) { return 1;}
                   11754:                      return 0;
                   11755:                  } @{$slotsarr};
                   11756:     }
                   11757:     return @sorted;
                   11758: }
                   11759: 
1.1040    raeburn  11760: =pod
                   11761: 
                   11762: =item * get_future_slots()
                   11763: 
                   11764: Inputs:
                   11765: 
                   11766: =over 4
                   11767: 
                   11768: cnum - course number
                   11769: 
                   11770: cdom - course domain
                   11771: 
                   11772: now - current UNIX time
                   11773: 
                   11774: symb - optional symb
                   11775: 
                   11776: =back
                   11777: 
                   11778: Returns:
                   11779: 
                   11780: =over 4
                   11781: 
                   11782: sorted_reservable - ref to array of student_schedulable slots currently 
                   11783:                     reservable, ordered by end date of reservation period.
                   11784: 
                   11785: reservable_now - ref to hash of student_schedulable slots currently
                   11786:                  reservable.
                   11787: 
                   11788:     Keys in inner hash are:
                   11789:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11790:     (b) endreserve: end date of reservation period.
                   11791:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11792:         selected.
1.1040    raeburn  11793: 
                   11794: sorted_future - ref to array of student_schedulable slots reservable in
                   11795:                 the future, ordered by start date of reservation period.
                   11796: 
                   11797: future_reservable - ref to hash of student_schedulable slots reservable
                   11798:                     in the future.
                   11799: 
                   11800:     Keys in inner hash are:
                   11801:     (a) symb: either blank or symb to which slot use is restricted.
                   11802:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11803:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11804:         selected.
1.1040    raeburn  11805: 
                   11806: =back
                   11807: 
                   11808: =cut
                   11809: 
                   11810: sub get_future_slots {
                   11811:     my ($cnum,$cdom,$now,$symb) = @_;
                   11812:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11813:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11814:     foreach my $slot (keys(%slots)) {
                   11815:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11816:         if ($symb) {
                   11817:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11818:                      ($slots{$slot}->{'symb'} ne $symb));
                   11819:         }
                   11820:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11821:             ($slots{$slot}->{'endtime'} > $now)) {
                   11822:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11823:                 my $userallowed = 0;
                   11824:                 if ($slots{$slot}->{'allowedsections'}) {
                   11825:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11826:                     if (!defined($env{'request.role.sec'})
                   11827:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11828:                         $userallowed=1;
                   11829:                     } else {
                   11830:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11831:                             $userallowed=1;
                   11832:                         }
                   11833:                     }
                   11834:                     unless ($userallowed) {
                   11835:                         if (defined($env{'request.course.groups'})) {
                   11836:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11837:                             foreach my $group (@groups) {
                   11838:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11839:                                     $userallowed=1;
                   11840:                                     last;
                   11841:                                 }
                   11842:                             }
                   11843:                         }
                   11844:                     }
                   11845:                 }
                   11846:                 if ($slots{$slot}->{'allowedusers'}) {
                   11847:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11848:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11849:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11850:                         $userallowed = 1;
                   11851:                     }
                   11852:                 }
                   11853:                 next unless($userallowed);
                   11854:             }
                   11855:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11856:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11857:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11858:             my $uniqueperiod;
                   11859:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11860:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11861:             }
1.1040    raeburn  11862:             if (($startreserve < $now) &&
                   11863:                 (!$endreserve || $endreserve > $now)) {
                   11864:                 my $lastres = $endreserve;
                   11865:                 if (!$lastres) {
                   11866:                     $lastres = $slots{$slot}->{'starttime'};
                   11867:                 }
                   11868:                 $reservable_now{$slot} = {
                   11869:                                            symb       => $symb,
1.1075.2.104  raeburn  11870:                                            endreserve => $lastres,
                   11871:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11872:                                          };
                   11873:             } elsif (($startreserve > $now) &&
                   11874:                      (!$endreserve || $endreserve > $startreserve)) {
                   11875:                 $future_reservable{$slot} = {
                   11876:                                               symb         => $symb,
1.1075.2.104  raeburn  11877:                                               startreserve => $startreserve,
                   11878:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11879:                                             };
                   11880:             }
                   11881:         }
                   11882:     }
                   11883:     my @unsorted_reservable = keys(%reservable_now);
                   11884:     if (@unsorted_reservable > 0) {
                   11885:         @sorted_reservable = 
                   11886:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11887:     }
                   11888:     my @unsorted_future = keys(%future_reservable);
                   11889:     if (@unsorted_future > 0) {
                   11890:         @sorted_future =
                   11891:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11892:     }
                   11893:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11894: }
1.780     raeburn  11895: 
                   11896: =pod
                   11897: 
1.1057    foxr     11898: =back
                   11899: 
1.549     albertel 11900: =head1 HTTP Helpers
                   11901: 
                   11902: =over 4
                   11903: 
1.648     raeburn  11904: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11905: 
1.258     albertel 11906: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11907: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11908: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11909: 
                   11910: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11911: $possible_names is an ref to an array of form element names.  As an example:
                   11912: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11913: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11914: 
                   11915: =cut
1.1       albertel 11916: 
1.6       albertel 11917: sub get_unprocessed_cgi {
1.25      albertel 11918:   my ($query,$possible_names)= @_;
1.26      matthew  11919:   # $Apache::lonxml::debug=1;
1.356     albertel 11920:   foreach my $pair (split(/&/,$query)) {
                   11921:     my ($name, $value) = split(/=/,$pair);
1.369     www      11922:     $name = &unescape($name);
1.25      albertel 11923:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11924:       $value =~ tr/+/ /;
                   11925:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11926:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11927:     }
1.16      harris41 11928:   }
1.6       albertel 11929: }
                   11930: 
1.112     bowersj2 11931: =pod
                   11932: 
1.648     raeburn  11933: =item * &cacheheader() 
1.112     bowersj2 11934: 
                   11935: returns cache-controlling header code
                   11936: 
                   11937: =cut
                   11938: 
1.7       albertel 11939: sub cacheheader {
1.258     albertel 11940:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11941:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11942:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11943:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11944:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11945:     return $output;
1.7       albertel 11946: }
                   11947: 
1.112     bowersj2 11948: =pod
                   11949: 
1.648     raeburn  11950: =item * &no_cache($r) 
1.112     bowersj2 11951: 
                   11952: specifies header code to not have cache
                   11953: 
                   11954: =cut
                   11955: 
1.9       albertel 11956: sub no_cache {
1.216     albertel 11957:     my ($r) = @_;
                   11958:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11959: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11960:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11961:     $r->no_cache(1);
                   11962:     $r->header_out("Expires" => $date);
                   11963:     $r->header_out("Pragma" => "no-cache");
1.123     www      11964: }
                   11965: 
                   11966: sub content_type {
1.181     albertel 11967:     my ($r,$type,$charset) = @_;
1.299     foxr     11968:     if ($r) {
                   11969: 	#  Note that printout.pl calls this with undef for $r.
                   11970: 	&no_cache($r);
                   11971:     }
1.258     albertel 11972:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11973:     unless ($charset) {
                   11974: 	$charset=&Apache::lonlocal::current_encoding;
                   11975:     }
                   11976:     if ($charset) { $type.='; charset='.$charset; }
                   11977:     if ($r) {
                   11978: 	$r->content_type($type);
                   11979:     } else {
                   11980: 	print("Content-type: $type\n\n");
                   11981:     }
1.9       albertel 11982: }
1.25      albertel 11983: 
1.112     bowersj2 11984: =pod
                   11985: 
1.648     raeburn  11986: =item * &add_to_env($name,$value) 
1.112     bowersj2 11987: 
1.258     albertel 11988: adds $name to the %env hash with value
1.112     bowersj2 11989: $value, if $name already exists, the entry is converted to an array
                   11990: reference and $value is added to the array.
                   11991: 
                   11992: =cut
                   11993: 
1.25      albertel 11994: sub add_to_env {
                   11995:   my ($name,$value)=@_;
1.258     albertel 11996:   if (defined($env{$name})) {
                   11997:     if (ref($env{$name})) {
1.25      albertel 11998:       #already have multiple values
1.258     albertel 11999:       push(@{ $env{$name} },$value);
1.25      albertel 12000:     } else {
                   12001:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12002:       my $first=$env{$name};
                   12003:       undef($env{$name});
                   12004:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12005:     }
                   12006:   } else {
1.258     albertel 12007:     $env{$name}=$value;
1.25      albertel 12008:   }
1.31      albertel 12009: }
1.149     albertel 12010: 
                   12011: =pod
                   12012: 
1.648     raeburn  12013: =item * &get_env_multiple($name) 
1.149     albertel 12014: 
1.258     albertel 12015: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12016: values may be defined and end up as an array ref.
                   12017: 
                   12018: returns an array of values
                   12019: 
                   12020: =cut
                   12021: 
                   12022: sub get_env_multiple {
                   12023:     my ($name) = @_;
                   12024:     my @values;
1.258     albertel 12025:     if (defined($env{$name})) {
1.149     albertel 12026:         # exists is it an array
1.258     albertel 12027:         if (ref($env{$name})) {
                   12028:             @values=@{ $env{$name} };
1.149     albertel 12029:         } else {
1.258     albertel 12030:             $values[0]=$env{$name};
1.149     albertel 12031:         }
                   12032:     }
                   12033:     return(@values);
                   12034: }
                   12035: 
1.660     raeburn  12036: sub ask_for_embedded_content {
                   12037:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12038:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  12039:         %currsubfile,%unused,$rem);
1.1071    raeburn  12040:     my $counter = 0;
                   12041:     my $numnew = 0;
1.987     raeburn  12042:     my $numremref = 0;
                   12043:     my $numinvalid = 0;
                   12044:     my $numpathchg = 0;
                   12045:     my $numexisting = 0;
1.1071    raeburn  12046:     my $numunused = 0;
                   12047:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  12048:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12049:     my $heading = &mt('Upload embedded files');
                   12050:     my $buttontext = &mt('Upload');
                   12051: 
1.1075.2.11  raeburn  12052:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  12053:         if ($actionurl eq '/adm/dependencies') {
                   12054:             $navmap = Apache::lonnavmaps::navmap->new();
                   12055:         }
                   12056:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12057:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  12058:     }
1.1075.2.35  raeburn  12059:     if (($actionurl eq '/adm/portfolio') ||
                   12060:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12061:         my $current_path='/';
                   12062:         if ($env{'form.currentpath'}) {
                   12063:             $current_path = $env{'form.currentpath'};
                   12064:         }
                   12065:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  12066:             $udom = $cdom;
                   12067:             $uname = $cnum;
1.984     raeburn  12068:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12069:         } else {
                   12070:             $udom = $env{'user.domain'};
                   12071:             $uname = $env{'user.name'};
                   12072:             $url = '/userfiles/portfolio';
                   12073:         }
1.987     raeburn  12074:         $toplevel = $url.'/';
1.984     raeburn  12075:         $url .= $current_path;
                   12076:         $getpropath = 1;
1.987     raeburn  12077:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12078:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12079:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12080:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12081:         $toplevel = $url;
1.984     raeburn  12082:         if ($rest ne '') {
1.987     raeburn  12083:             $url .= $rest;
                   12084:         }
                   12085:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12086:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12087:             $url = $args->{'docs_url'};
                   12088:             $toplevel = $url;
1.1075.2.11  raeburn  12089:             if ($args->{'context'} eq 'paste') {
                   12090:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12091:                 ($path) =
                   12092:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12093:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12094:                 $fileloc =~ s{^/}{};
                   12095:             }
1.1071    raeburn  12096:         }
                   12097:     } elsif ($actionurl eq '/adm/dependencies') {
                   12098:         if ($env{'request.course.id'} ne '') {
                   12099:             if (ref($args) eq 'HASH') {
                   12100:                 $url = $args->{'docs_url'};
                   12101:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  12102:                 $toplevel = $url;
                   12103:                 unless ($toplevel =~ m{^/}) {
                   12104:                     $toplevel = "/$url";
                   12105:                 }
1.1075.2.11  raeburn  12106:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  12107:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12108:                     $path = $1;
                   12109:                 } else {
                   12110:                     ($path) =
                   12111:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12112:                 }
1.1075.2.79  raeburn  12113:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12114:                     $fileloc = $toplevel;
                   12115:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12116:                     my ($udom,$uname,$fname) =
                   12117:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12118:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12119:                 } else {
                   12120:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12121:                 }
1.1071    raeburn  12122:                 $fileloc =~ s{^/}{};
                   12123:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12124:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12125:             }
1.987     raeburn  12126:         }
1.1075.2.35  raeburn  12127:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12128:         $udom = $cdom;
                   12129:         $uname = $cnum;
                   12130:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12131:         $toplevel = $url;
                   12132:         $path = $url;
                   12133:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12134:         $fileloc =~ s{^/}{};
                   12135:     }
                   12136:     foreach my $file (keys(%{$allfiles})) {
                   12137:         my $embed_file;
                   12138:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12139:             $embed_file = $1;
                   12140:         } else {
                   12141:             $embed_file = $file;
                   12142:         }
1.1075.2.55  raeburn  12143:         my ($absolutepath,$cleaned_file);
                   12144:         if ($embed_file =~ m{^\w+://}) {
                   12145:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  12146:             $newfiles{$cleaned_file} = 1;
                   12147:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12148:         } else {
1.1075.2.55  raeburn  12149:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12150:             if ($embed_file =~ m{^/}) {
                   12151:                 $absolutepath = $embed_file;
                   12152:             }
1.1075.2.47  raeburn  12153:             if ($cleaned_file =~ m{/}) {
                   12154:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12155:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12156:                 my $item = $fname;
                   12157:                 if ($path ne '') {
                   12158:                     $item = $path.'/'.$fname;
                   12159:                     $subdependencies{$path}{$fname} = 1;
                   12160:                 } else {
                   12161:                     $dependencies{$item} = 1;
                   12162:                 }
                   12163:                 if ($absolutepath) {
                   12164:                     $mapping{$item} = $absolutepath;
                   12165:                 } else {
                   12166:                     $mapping{$item} = $embed_file;
                   12167:                 }
                   12168:             } else {
                   12169:                 $dependencies{$embed_file} = 1;
                   12170:                 if ($absolutepath) {
1.1075.2.47  raeburn  12171:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12172:                 } else {
1.1075.2.47  raeburn  12173:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12174:                 }
                   12175:             }
1.984     raeburn  12176:         }
                   12177:     }
1.1071    raeburn  12178:     my $dirptr = 16384;
1.984     raeburn  12179:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12180:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  12181:         if (($actionurl eq '/adm/portfolio') ||
                   12182:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  12183:             my ($sublistref,$listerror) =
                   12184:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12185:             if (ref($sublistref) eq 'ARRAY') {
                   12186:                 foreach my $line (@{$sublistref}) {
                   12187:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12188:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12189:                 }
1.984     raeburn  12190:             }
1.987     raeburn  12191:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12192:             if (opendir(my $dir,$url.'/'.$path)) {
                   12193:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12194:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12195:             }
1.1075.2.11  raeburn  12196:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12197:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12198:                   ($args->{'context'} eq 'paste')) ||
                   12199:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12200:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  12201:                 my $dir;
                   12202:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12203:                     $dir = $fileloc;
                   12204:                 } else {
                   12205:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12206:                 }
1.1071    raeburn  12207:                 if ($dir ne '') {
                   12208:                     my ($sublistref,$listerror) =
                   12209:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12210:                     if (ref($sublistref) eq 'ARRAY') {
                   12211:                         foreach my $line (@{$sublistref}) {
                   12212:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12213:                                 undef,$mtime)=split(/\&/,$line,12);
                   12214:                             unless (($testdir&$dirptr) ||
                   12215:                                     ($file_name =~ /^\.\.?$/)) {
                   12216:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12217:                             }
                   12218:                         }
                   12219:                     }
                   12220:                 }
1.984     raeburn  12221:             }
                   12222:         }
                   12223:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12224:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12225:                 my $item = $path.'/'.$file;
                   12226:                 unless ($mapping{$item} eq $item) {
                   12227:                     $pathchanges{$item} = 1;
                   12228:                 }
                   12229:                 $existing{$item} = 1;
                   12230:                 $numexisting ++;
                   12231:             } else {
                   12232:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12233:             }
                   12234:         }
1.1071    raeburn  12235:         if ($actionurl eq '/adm/dependencies') {
                   12236:             foreach my $path (keys(%currsubfile)) {
                   12237:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12238:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12239:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  12240:                              next if (($rem ne '') &&
                   12241:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12242:                                        (ref($navmap) &&
                   12243:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12244:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12245:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12246:                              $unused{$path.'/'.$file} = 1; 
                   12247:                          }
                   12248:                     }
                   12249:                 }
                   12250:             }
                   12251:         }
1.984     raeburn  12252:     }
1.987     raeburn  12253:     my %currfile;
1.1075.2.35  raeburn  12254:     if (($actionurl eq '/adm/portfolio') ||
                   12255:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12256:         my ($dirlistref,$listerror) =
                   12257:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12258:         if (ref($dirlistref) eq 'ARRAY') {
                   12259:             foreach my $line (@{$dirlistref}) {
                   12260:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12261:                 $currfile{$file_name} = 1;
                   12262:             }
1.984     raeburn  12263:         }
1.987     raeburn  12264:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12265:         if (opendir(my $dir,$url)) {
1.987     raeburn  12266:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12267:             map {$currfile{$_} = 1;} @dir_list;
                   12268:         }
1.1075.2.11  raeburn  12269:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12270:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  12271:               ($args->{'context'} eq 'paste')) ||
                   12272:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12273:         if ($env{'request.course.id'} ne '') {
                   12274:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12275:             if ($dir ne '') {
                   12276:                 my ($dirlistref,$listerror) =
                   12277:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12278:                 if (ref($dirlistref) eq 'ARRAY') {
                   12279:                     foreach my $line (@{$dirlistref}) {
                   12280:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12281:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12282:                         unless (($testdir&$dirptr) ||
                   12283:                                 ($file_name =~ /^\.\.?$/)) {
                   12284:                             $currfile{$file_name} = [$size,$mtime];
                   12285:                         }
                   12286:                     }
                   12287:                 }
                   12288:             }
                   12289:         }
1.984     raeburn  12290:     }
                   12291:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12292:         if (exists($currfile{$file})) {
1.987     raeburn  12293:             unless ($mapping{$file} eq $file) {
                   12294:                 $pathchanges{$file} = 1;
                   12295:             }
                   12296:             $existing{$file} = 1;
                   12297:             $numexisting ++;
                   12298:         } else {
1.984     raeburn  12299:             $newfiles{$file} = 1;
                   12300:         }
                   12301:     }
1.1071    raeburn  12302:     foreach my $file (keys(%currfile)) {
                   12303:         unless (($file eq $filename) ||
                   12304:                 ($file eq $filename.'.bak') ||
                   12305:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  12306:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  12307:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12308:                     next if (($rem ne '') &&
                   12309:                              (($env{"httpref.$rem".$file} ne '') ||
                   12310:                               (ref($navmap) &&
                   12311:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12312:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12313:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12314:                 }
1.1075.2.11  raeburn  12315:             }
1.1071    raeburn  12316:             $unused{$file} = 1;
                   12317:         }
                   12318:     }
1.1075.2.11  raeburn  12319:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12320:         ($args->{'context'} eq 'paste')) {
                   12321:         $counter = scalar(keys(%existing));
                   12322:         $numpathchg = scalar(keys(%pathchanges));
                   12323:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  12324:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   12325:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12326:         $counter = scalar(keys(%existing));
                   12327:         $numpathchg = scalar(keys(%pathchanges));
                   12328:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  12329:     }
1.984     raeburn  12330:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12331:         if ($actionurl eq '/adm/dependencies') {
                   12332:             next if ($embed_file =~ m{^\w+://});
                   12333:         }
1.660     raeburn  12334:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12335:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12336:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12337:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  12338:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12339:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12340:         }
1.1075.2.35  raeburn  12341:         $upload_output .= '</td>';
1.1071    raeburn  12342:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  12343:             $upload_output.='<td align="right">'.
                   12344:                             '<span class="LC_info LC_fontsize_medium">'.
                   12345:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12346:             $numremref++;
1.660     raeburn  12347:         } elsif ($args->{'error_on_invalid_names'}
                   12348:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  12349:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12350:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12351:             $numinvalid++;
1.660     raeburn  12352:         } else {
1.1075.2.35  raeburn  12353:             $upload_output .= '<td>'.
                   12354:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12355:                                                      $embed_file,\%mapping,
1.1071    raeburn  12356:                                                      $allfiles,$codebase,'upload');
                   12357:             $counter ++;
                   12358:             $numnew ++;
1.987     raeburn  12359:         }
                   12360:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12361:     }
                   12362:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12363:         if ($actionurl eq '/adm/dependencies') {
                   12364:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12365:             $modify_output .= &start_data_table_row().
                   12366:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12367:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12368:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12369:                               '<td>'.$size.'</td>'.
                   12370:                               '<td>'.$mtime.'</td>'.
                   12371:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12372:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12373:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12374:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12375:                               &embedded_file_element('upload_embedded',$counter,
                   12376:                                                      $embed_file,\%mapping,
                   12377:                                                      $allfiles,$codebase,'modify').
                   12378:                               '</div></td>'.
                   12379:                               &end_data_table_row()."\n";
                   12380:             $counter ++;
                   12381:         } else {
                   12382:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  12383:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12384:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12385:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12386:                               &Apache::loncommon::end_data_table_row()."\n";
                   12387:         }
                   12388:     }
                   12389:     my $delidx = $counter;
                   12390:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12391:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12392:         $delete_output .= &start_data_table_row().
                   12393:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12394:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12395:                           '<td>'.$size.'</td>'.
                   12396:                           '<td>'.$mtime.'</td>'.
                   12397:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12398:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12399:                           &embedded_file_element('upload_embedded',$delidx,
                   12400:                                                  $oldfile,\%mapping,$allfiles,
                   12401:                                                  $codebase,'delete').'</td>'.
                   12402:                           &end_data_table_row()."\n"; 
                   12403:         $numunused ++;
                   12404:         $delidx ++;
1.987     raeburn  12405:     }
                   12406:     if ($upload_output) {
                   12407:         $upload_output = &start_data_table().
                   12408:                          $upload_output.
                   12409:                          &end_data_table()."\n";
                   12410:     }
1.1071    raeburn  12411:     if ($modify_output) {
                   12412:         $modify_output = &start_data_table().
                   12413:                          &start_data_table_header_row().
                   12414:                          '<th>'.&mt('File').'</th>'.
                   12415:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12416:                          '<th>'.&mt('Modified').'</th>'.
                   12417:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12418:                          &end_data_table_header_row().
                   12419:                          $modify_output.
                   12420:                          &end_data_table()."\n";
                   12421:     }
                   12422:     if ($delete_output) {
                   12423:         $delete_output = &start_data_table().
                   12424:                          &start_data_table_header_row().
                   12425:                          '<th>'.&mt('File').'</th>'.
                   12426:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12427:                          '<th>'.&mt('Modified').'</th>'.
                   12428:                          '<th>'.&mt('Delete?').'</th>'.
                   12429:                          &end_data_table_header_row().
                   12430:                          $delete_output.
                   12431:                          &end_data_table()."\n";
                   12432:     }
1.987     raeburn  12433:     my $applies = 0;
                   12434:     if ($numremref) {
                   12435:         $applies ++;
                   12436:     }
                   12437:     if ($numinvalid) {
                   12438:         $applies ++;
                   12439:     }
                   12440:     if ($numexisting) {
                   12441:         $applies ++;
                   12442:     }
1.1071    raeburn  12443:     if ($counter || $numunused) {
1.987     raeburn  12444:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12445:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12446:                   $state.'<h3>'.$heading.'</h3>'; 
                   12447:         if ($actionurl eq '/adm/dependencies') {
                   12448:             if ($numnew) {
                   12449:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12450:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12451:                            $upload_output.'<br />'."\n";
                   12452:             }
                   12453:             if ($numexisting) {
                   12454:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12455:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12456:                            $modify_output.'<br />'."\n";
                   12457:                            $buttontext = &mt('Save changes');
                   12458:             }
                   12459:             if ($numunused) {
                   12460:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12461:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12462:                            $delete_output.'<br />'."\n";
                   12463:                            $buttontext = &mt('Save changes');
                   12464:             }
                   12465:         } else {
                   12466:             $output .= $upload_output.'<br />'."\n";
                   12467:         }
                   12468:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12469:                    $counter.'" />'."\n";
                   12470:         if ($actionurl eq '/adm/dependencies') { 
                   12471:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12472:                        $numnew.'" />'."\n";
                   12473:         } elsif ($actionurl eq '') {
1.987     raeburn  12474:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12475:         }
                   12476:     } elsif ($applies) {
                   12477:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12478:         if ($applies > 1) {
                   12479:             $output .=  
1.1075.2.35  raeburn  12480:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12481:             if ($numremref) {
                   12482:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12483:             }
                   12484:             if ($numinvalid) {
                   12485:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12486:             }
                   12487:             if ($numexisting) {
                   12488:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12489:             }
                   12490:             $output .= '</ul><br />';
                   12491:         } elsif ($numremref) {
                   12492:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12493:         } elsif ($numinvalid) {
                   12494:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12495:         } elsif ($numexisting) {
                   12496:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12497:         }
                   12498:         $output .= $upload_output.'<br />';
                   12499:     }
                   12500:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12501:     $chgcount = $counter;
1.987     raeburn  12502:     if (keys(%pathchanges) > 0) {
                   12503:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12504:             if ($counter) {
1.987     raeburn  12505:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12506:                                                   $embed_file,\%mapping,
1.1071    raeburn  12507:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12508:             } else {
                   12509:                 $pathchange_output .= 
                   12510:                     &start_data_table_row().
                   12511:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12512:                     $chgcount.'" checked="checked" /></td>'.
                   12513:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12514:                     '<td>'.$embed_file.
                   12515:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12516:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12517:                     '</td>'.&end_data_table_row();
1.660     raeburn  12518:             }
1.987     raeburn  12519:             $numpathchg ++;
                   12520:             $chgcount ++;
1.660     raeburn  12521:         }
                   12522:     }
1.1075.2.35  raeburn  12523:     if (($counter) || ($numunused)) {
1.987     raeburn  12524:         if ($numpathchg) {
                   12525:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12526:                        $numpathchg.'" />'."\n";
                   12527:         }
                   12528:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12529:             ($actionurl eq '/adm/imsimport')) {
                   12530:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12531:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12532:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12533:         } elsif ($actionurl eq '/adm/dependencies') {
                   12534:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12535:         }
1.1075.2.35  raeburn  12536:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12537:     } elsif ($numpathchg) {
                   12538:         my %pathchange = ();
                   12539:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12540:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12541:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12542:         }
1.987     raeburn  12543:     }
1.1071    raeburn  12544:     return ($output,$counter,$numpathchg);
1.987     raeburn  12545: }
                   12546: 
1.1075.2.47  raeburn  12547: =pod
                   12548: 
                   12549: =item * clean_path($name)
                   12550: 
                   12551: Performs clean-up of directories, subdirectories and filename in an
                   12552: embedded object, referenced in an HTML file which is being uploaded
                   12553: to a course or portfolio, where
                   12554: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12555: checked.
                   12556: 
                   12557: Clean-up is similar to replacements in lonnet::clean_filename()
                   12558: except each / between sub-directory and next level is preserved.
                   12559: 
                   12560: =cut
                   12561: 
                   12562: sub clean_path {
                   12563:     my ($embed_file) = @_;
                   12564:     $embed_file =~s{^/+}{};
                   12565:     my @contents;
                   12566:     if ($embed_file =~ m{/}) {
                   12567:         @contents = split(/\//,$embed_file);
                   12568:     } else {
                   12569:         @contents = ($embed_file);
                   12570:     }
                   12571:     my $lastidx = scalar(@contents)-1;
                   12572:     for (my $i=0; $i<=$lastidx; $i++) {
                   12573:         $contents[$i]=~s{\\}{/}g;
                   12574:         $contents[$i]=~s/\s+/\_/g;
                   12575:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12576:         if ($i == $lastidx) {
                   12577:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12578:         }
                   12579:     }
                   12580:     if ($lastidx > 0) {
                   12581:         return join('/',@contents);
                   12582:     } else {
                   12583:         return $contents[0];
                   12584:     }
                   12585: }
                   12586: 
1.987     raeburn  12587: sub embedded_file_element {
1.1071    raeburn  12588:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12589:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12590:                    (ref($codebase) eq 'HASH'));
                   12591:     my $output;
1.1071    raeburn  12592:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12593:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12594:     }
                   12595:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12596:                &escape($embed_file).'" />';
                   12597:     unless (($context eq 'upload_embedded') && 
                   12598:             ($mapping->{$embed_file} eq $embed_file)) {
                   12599:         $output .='
                   12600:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12601:     }
                   12602:     my $attrib;
                   12603:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12604:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12605:     }
                   12606:     $output .=
                   12607:         "\n\t\t".
                   12608:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12609:         $attrib.'" />';
                   12610:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12611:         $output .=
                   12612:             "\n\t\t".
                   12613:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12614:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12615:     }
1.987     raeburn  12616:     return $output;
1.660     raeburn  12617: }
                   12618: 
1.1071    raeburn  12619: sub get_dependency_details {
                   12620:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12621:     my ($size,$mtime,$showsize,$showmtime);
                   12622:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12623:         if ($embed_file =~ m{/}) {
                   12624:             my ($path,$fname) = split(/\//,$embed_file);
                   12625:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12626:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12627:             }
                   12628:         } else {
                   12629:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12630:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12631:             }
                   12632:         }
                   12633:         $showsize = $size/1024.0;
                   12634:         $showsize = sprintf("%.1f",$showsize);
                   12635:         if ($mtime > 0) {
                   12636:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12637:         }
                   12638:     }
                   12639:     return ($showsize,$showmtime);
                   12640: }
                   12641: 
                   12642: sub ask_embedded_js {
                   12643:     return <<"END";
                   12644: <script type="text/javascript"">
                   12645: // <![CDATA[
                   12646: function toggleBrowse(counter) {
                   12647:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12648:     var fileid = document.getElementById('embedded_item_'+counter);
                   12649:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12650:     if (chkboxid.checked == true) {
                   12651:         uploaddivid.style.display='block';
                   12652:     } else {
                   12653:         uploaddivid.style.display='none';
                   12654:         fileid.value = '';
                   12655:     }
                   12656: }
                   12657: // ]]>
                   12658: </script>
                   12659: 
                   12660: END
                   12661: }
                   12662: 
1.661     raeburn  12663: sub upload_embedded {
                   12664:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12665:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12666:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12667:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12668:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12669:         my $orig_uploaded_filename =
                   12670:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12671:         foreach my $type ('orig','ref','attrib','codebase') {
                   12672:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12673:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12674:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12675:             }
                   12676:         }
1.661     raeburn  12677:         my ($path,$fname) =
                   12678:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12679:         # no path, whole string is fname
                   12680:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12681:         $fname = &Apache::lonnet::clean_filename($fname);
                   12682:         # See if there is anything left
                   12683:         next if ($fname eq '');
                   12684: 
                   12685:         # Check if file already exists as a file or directory.
                   12686:         my ($state,$msg);
                   12687:         if ($context eq 'portfolio') {
                   12688:             my $port_path = $dirpath;
                   12689:             if ($group ne '') {
                   12690:                 $port_path = "groups/$group/$port_path";
                   12691:             }
1.987     raeburn  12692:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12693:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12694:                                               $dir_root,$port_path,$disk_quota,
                   12695:                                               $current_disk_usage,$uname,$udom);
                   12696:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12697:                 || $state eq 'file_locked') {
1.661     raeburn  12698:                 $output .= $msg;
                   12699:                 next;
                   12700:             }
                   12701:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12702:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12703:             if ($state eq 'exists') {
                   12704:                 $output .= $msg;
                   12705:                 next;
                   12706:             }
                   12707:         }
                   12708:         # Check if extension is valid
                   12709:         if (($fname =~ /\.(\w+)$/) &&
                   12710:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12711:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12712:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12713:             next;
                   12714:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12715:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12716:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12717:             next;
                   12718:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12719:             $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  12720:             next;
                   12721:         }
                   12722:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12723:         my $subdir = $path;
                   12724:         $subdir =~ s{/+$}{};
1.661     raeburn  12725:         if ($context eq 'portfolio') {
1.984     raeburn  12726:             my $result;
                   12727:             if ($state eq 'existingfile') {
                   12728:                 $result=
                   12729:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12730:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12731:             } else {
1.984     raeburn  12732:                 $result=
                   12733:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12734:                                                     $dirpath.
1.1075.2.35  raeburn  12735:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12736:                 if ($result !~ m|^/uploaded/|) {
                   12737:                     $output .= '<span class="LC_error">'
                   12738:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12739:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12740:                                .'</span><br />';
                   12741:                     next;
                   12742:                 } else {
1.987     raeburn  12743:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12744:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12745:                 }
1.661     raeburn  12746:             }
1.1075.2.35  raeburn  12747:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12748:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12749:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12750:             my $result =
1.1075.2.35  raeburn  12751:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12752:             if ($result !~ m|^/uploaded/|) {
                   12753:                 $output .= '<span class="LC_error">'
                   12754:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12755:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12756:                            .'</span><br />';
                   12757:                     next;
                   12758:             } else {
                   12759:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12760:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12761:                 if ($context eq 'syllabus') {
                   12762:                     &Apache::lonnet::make_public_indefinitely($result);
                   12763:                 }
1.987     raeburn  12764:             }
1.661     raeburn  12765:         } else {
                   12766: # Save the file
                   12767:             my $target = $env{'form.embedded_item_'.$i};
                   12768:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12769:             my $dest = $fullpath.$fname;
                   12770:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12771:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12772:             my $count;
                   12773:             my $filepath = $dir_root;
1.1027    raeburn  12774:             foreach my $subdir (@parts) {
                   12775:                 $filepath .= "/$subdir";
                   12776:                 if (!-e $filepath) {
1.661     raeburn  12777:                     mkdir($filepath,0770);
                   12778:                 }
                   12779:             }
                   12780:             my $fh;
                   12781:             if (!open($fh,'>'.$dest)) {
                   12782:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12783:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12784:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12785:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12786:                            '</span><br />';
                   12787:             } else {
                   12788:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12789:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12790:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12791:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12792:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12793:                               '</span><br />';
                   12794:                 } else {
1.987     raeburn  12795:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12796:                                $url.'</span>').'<br />';
                   12797:                     unless ($context eq 'testbank') {
                   12798:                         $footer .= &mt('View embedded file: [_1]',
                   12799:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12800:                     }
                   12801:                 }
                   12802:                 close($fh);
                   12803:             }
                   12804:         }
                   12805:         if ($env{'form.embedded_ref_'.$i}) {
                   12806:             $pathchange{$i} = 1;
                   12807:         }
                   12808:     }
                   12809:     if ($output) {
                   12810:         $output = '<p>'.$output.'</p>';
                   12811:     }
                   12812:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12813:     $returnflag = 'ok';
1.1071    raeburn  12814:     my $numpathchgs = scalar(keys(%pathchange));
                   12815:     if ($numpathchgs > 0) {
1.987     raeburn  12816:         if ($context eq 'portfolio') {
                   12817:             $output .= '<p>'.&mt('or').'</p>';
                   12818:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12819:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12820:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12821:             $returnflag = 'modify_orightml';
                   12822:         }
                   12823:     }
1.1071    raeburn  12824:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12825: }
                   12826: 
                   12827: sub modify_html_form {
                   12828:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12829:     my $end = 0;
                   12830:     my $modifyform;
                   12831:     if ($context eq 'upload_embedded') {
                   12832:         return unless (ref($pathchange) eq 'HASH');
                   12833:         if ($env{'form.number_embedded_items'}) {
                   12834:             $end += $env{'form.number_embedded_items'};
                   12835:         }
                   12836:         if ($env{'form.number_pathchange_items'}) {
                   12837:             $end += $env{'form.number_pathchange_items'};
                   12838:         }
                   12839:         if ($end) {
                   12840:             for (my $i=0; $i<$end; $i++) {
                   12841:                 if ($i < $env{'form.number_embedded_items'}) {
                   12842:                     next unless($pathchange->{$i});
                   12843:                 }
                   12844:                 $modifyform .=
                   12845:                     &start_data_table_row().
                   12846:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12847:                     'checked="checked" /></td>'.
                   12848:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12849:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12850:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12851:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12852:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12853:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12854:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12855:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12856:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12857:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12858:                     &end_data_table_row();
1.1071    raeburn  12859:             }
1.987     raeburn  12860:         }
                   12861:     } else {
                   12862:         $modifyform = $pathchgtable;
                   12863:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12864:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12865:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12866:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12867:         }
                   12868:     }
                   12869:     if ($modifyform) {
1.1071    raeburn  12870:         if ($actionurl eq '/adm/dependencies') {
                   12871:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12872:         }
1.987     raeburn  12873:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12874:                '<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".
                   12875:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12876:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12877:                '</ol></p>'."\n".'<p>'.
                   12878:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12879:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12880:                &start_data_table()."\n".
                   12881:                &start_data_table_header_row().
                   12882:                '<th>'.&mt('Change?').'</th>'.
                   12883:                '<th>'.&mt('Current reference').'</th>'.
                   12884:                '<th>'.&mt('Required reference').'</th>'.
                   12885:                &end_data_table_header_row()."\n".
                   12886:                $modifyform.
                   12887:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12888:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12889:                '</form>'."\n";
                   12890:     }
                   12891:     return;
                   12892: }
                   12893: 
                   12894: sub modify_html_refs {
1.1075.2.35  raeburn  12895:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12896:     my $container;
                   12897:     if ($context eq 'portfolio') {
                   12898:         $container = $env{'form.container'};
                   12899:     } elsif ($context eq 'coursedoc') {
                   12900:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12901:     } elsif ($context eq 'manage_dependencies') {
                   12902:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12903:         $container = "/$container";
1.1075.2.35  raeburn  12904:     } elsif ($context eq 'syllabus') {
                   12905:         $container = $url;
1.987     raeburn  12906:     } else {
1.1027    raeburn  12907:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12908:     }
                   12909:     my (%allfiles,%codebase,$output,$content);
                   12910:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12911:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12912:         if (wantarray) {
                   12913:             return ('',0,0); 
                   12914:         } else {
                   12915:             return;
                   12916:         }
                   12917:     }
                   12918:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12919:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12920:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12921:             if (wantarray) {
                   12922:                 return ('',0,0);
                   12923:             } else {
                   12924:                 return;
                   12925:             }
                   12926:         } 
1.987     raeburn  12927:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12928:         if ($content eq '-1') {
                   12929:             if (wantarray) {
                   12930:                 return ('',0,0);
                   12931:             } else {
                   12932:                 return;
                   12933:             }
                   12934:         }
1.987     raeburn  12935:     } else {
1.1071    raeburn  12936:         unless ($container =~ /^\Q$dir_root\E/) {
                   12937:             if (wantarray) {
                   12938:                 return ('',0,0);
                   12939:             } else {
                   12940:                 return;
                   12941:             }
                   12942:         } 
1.1075.2.128  raeburn  12943:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12944:             $content = join('', <$fh>);
                   12945:             close($fh);
                   12946:         } else {
1.1071    raeburn  12947:             if (wantarray) {
                   12948:                 return ('',0,0);
                   12949:             } else {
                   12950:                 return;
                   12951:             }
1.987     raeburn  12952:         }
                   12953:     }
                   12954:     my ($count,$codebasecount) = (0,0);
                   12955:     my $mm = new File::MMagic;
                   12956:     my $mime_type = $mm->checktype_contents($content);
                   12957:     if ($mime_type eq 'text/html') {
                   12958:         my $parse_result = 
                   12959:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12960:                                                     \%codebase,\$content);
                   12961:         if ($parse_result eq 'ok') {
                   12962:             foreach my $i (@changes) {
                   12963:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12964:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12965:                 if ($allfiles{$ref}) {
                   12966:                     my $newname =  $orig;
                   12967:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12968:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12969:                     if ($attrib_regexp =~ /:/) {
                   12970:                         $attrib_regexp =~ s/\:/|/g;
                   12971:                     }
                   12972:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12973:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12974:                         $count += $numchg;
1.1075.2.35  raeburn  12975:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12976:                         delete($allfiles{$ref});
1.987     raeburn  12977:                     }
                   12978:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12979:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12980:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12981:                         $codebasecount ++;
                   12982:                     }
                   12983:                 }
                   12984:             }
1.1075.2.35  raeburn  12985:             my $skiprewrites;
1.987     raeburn  12986:             if ($count || $codebasecount) {
                   12987:                 my $saveresult;
1.1071    raeburn  12988:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12989:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12990:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12991:                     if ($url eq $container) {
                   12992:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12993:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12994:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12995:                                             $fname.'</span>').'</p>';
1.987     raeburn  12996:                     } else {
                   12997:                          $output = '<p class="LC_error">'.
                   12998:                                    &mt('Error: update failed for: [_1].',
                   12999:                                    '<span class="LC_filename">'.
                   13000:                                    $container.'</span>').'</p>';
                   13001:                     }
1.1075.2.35  raeburn  13002:                     if ($context eq 'syllabus') {
                   13003:                         unless ($saveresult eq 'ok') {
                   13004:                             $skiprewrites = 1;
                   13005:                         }
                   13006:                     }
1.987     raeburn  13007:                 } else {
1.1075.2.128  raeburn  13008:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13009:                         print $fh $content;
                   13010:                         close($fh);
                   13011:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13012:                                   $count,'<span class="LC_filename">'.
                   13013:                                   $container.'</span>').'</p>';
1.661     raeburn  13014:                     } else {
1.987     raeburn  13015:                          $output = '<p class="LC_error">'.
                   13016:                                    &mt('Error: could not update [_1].',
                   13017:                                    '<span class="LC_filename">'.
                   13018:                                    $container.'</span>').'</p>';
1.661     raeburn  13019:                     }
                   13020:                 }
                   13021:             }
1.1075.2.35  raeburn  13022:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13023:                 my ($actionurl,$state);
                   13024:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13025:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13026:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13027:                                               \%codebase,
                   13028:                                               {'context' => 'rewrites',
                   13029:                                                'ignore_remote_references' => 1,});
                   13030:                 if (ref($mapping) eq 'HASH') {
                   13031:                     my $rewrites = 0;
                   13032:                     foreach my $key (keys(%{$mapping})) {
                   13033:                         next if ($key =~ m{^https?://});
                   13034:                         my $ref = $mapping->{$key};
                   13035:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13036:                         my $attrib;
                   13037:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13038:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13039:                         }
                   13040:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13041:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13042:                             $rewrites += $numchg;
                   13043:                         }
                   13044:                     }
                   13045:                     if ($rewrites) {
                   13046:                         my $saveresult;
                   13047:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13048:                         if ($url eq $container) {
                   13049:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13050:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13051:                                             $count,'<span class="LC_filename">'.
                   13052:                                             $fname.'</span>').'</p>';
                   13053:                         } else {
                   13054:                             $output .= '<p class="LC_error">'.
                   13055:                                        &mt('Error: could not update links in [_1].',
                   13056:                                        '<span class="LC_filename">'.
                   13057:                                        $container.'</span>').'</p>';
                   13058: 
                   13059:                         }
                   13060:                     }
                   13061:                 }
                   13062:             }
1.987     raeburn  13063:         } else {
                   13064:             &logthis('Failed to parse '.$container.
                   13065:                      ' to modify references: '.$parse_result);
1.661     raeburn  13066:         }
                   13067:     }
1.1071    raeburn  13068:     if (wantarray) {
                   13069:         return ($output,$count,$codebasecount);
                   13070:     } else {
                   13071:         return $output;
                   13072:     }
1.661     raeburn  13073: }
                   13074: 
                   13075: sub check_for_existing {
                   13076:     my ($path,$fname,$element) = @_;
                   13077:     my ($state,$msg);
                   13078:     if (-d $path.'/'.$fname) {
                   13079:         $state = 'exists';
                   13080:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13081:     } elsif (-e $path.'/'.$fname) {
                   13082:         $state = 'exists';
                   13083:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13084:     }
                   13085:     if ($state eq 'exists') {
                   13086:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13087:     }
                   13088:     return ($state,$msg);
                   13089: }
                   13090: 
                   13091: sub check_for_upload {
                   13092:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13093:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13094:     my $filesize = length($env{'form.'.$element});
                   13095:     if (!$filesize) {
                   13096:         my $msg = '<span class="LC_error">'.
                   13097:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13098:                       '<span class="LC_filename">'.$fname.'</span>',
                   13099:                       $filesize).'<br />'.
1.1007    raeburn  13100:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13101:                   '</span>';
                   13102:         return ('zero_bytes',$msg);
                   13103:     }
                   13104:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13105:     my $getpropath = 1;
1.1021    raeburn  13106:     my ($dirlistref,$listerror) =
                   13107:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13108:     my $found_file = 0;
                   13109:     my $locked_file = 0;
1.991     raeburn  13110:     my @lockers;
                   13111:     my $navmap;
                   13112:     if ($env{'request.course.id'}) {
                   13113:         $navmap = Apache::lonnavmaps::navmap->new();
                   13114:     }
1.1021    raeburn  13115:     if (ref($dirlistref) eq 'ARRAY') {
                   13116:         foreach my $line (@{$dirlistref}) {
                   13117:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13118:             if ($file_name eq $fname){
                   13119:                 $file_name = $path.$file_name;
                   13120:                 if ($group ne '') {
                   13121:                     $file_name = $group.$file_name;
                   13122:                 }
                   13123:                 $found_file = 1;
                   13124:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13125:                     foreach my $lock (@lockers) {
                   13126:                         if (ref($lock) eq 'ARRAY') {
                   13127:                             my ($symb,$crsid) = @{$lock};
                   13128:                             if ($crsid eq $env{'request.course.id'}) {
                   13129:                                 if (ref($navmap)) {
                   13130:                                     my $res = $navmap->getBySymb($symb);
                   13131:                                     foreach my $part (@{$res->parts()}) { 
                   13132:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13133:                                         unless (($slot_status == $res->RESERVED) ||
                   13134:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13135:                                             $locked_file = 1;
                   13136:                                         }
1.991     raeburn  13137:                                     }
1.1021    raeburn  13138:                                 } else {
                   13139:                                     $locked_file = 1;
1.991     raeburn  13140:                                 }
                   13141:                             } else {
                   13142:                                 $locked_file = 1;
                   13143:                             }
                   13144:                         }
1.1021    raeburn  13145:                    }
                   13146:                 } else {
                   13147:                     my @info = split(/\&/,$rest);
                   13148:                     my $currsize = $info[6]/1000;
                   13149:                     if ($currsize < $filesize) {
                   13150:                         my $extra = $filesize - $currsize;
                   13151:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  13152:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13153:                                       &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  13154:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13155:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13156:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13157:                             return ('will_exceed_quota',$msg);
                   13158:                         }
1.984     raeburn  13159:                     }
                   13160:                 }
1.661     raeburn  13161:             }
                   13162:         }
                   13163:     }
                   13164:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  13165:         my $msg = '<p class="LC_warning">'.
                   13166:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   13167:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13168:         return ('will_exceed_quota',$msg);
                   13169:     } elsif ($found_file) {
                   13170:         if ($locked_file) {
1.1075.2.69  raeburn  13171:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13172:             $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  13173:             $msg .= '</p>';
1.661     raeburn  13174:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13175:             return ('file_locked',$msg);
                   13176:         } else {
1.1075.2.69  raeburn  13177:             my $msg = '<p class="LC_error">';
1.984     raeburn  13178:             $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  13179:             $msg .= '</p>';
1.984     raeburn  13180:             return ('existingfile',$msg);
1.661     raeburn  13181:         }
                   13182:     }
                   13183: }
                   13184: 
1.987     raeburn  13185: sub check_for_traversal {
                   13186:     my ($path,$url,$toplevel) = @_;
                   13187:     my @parts=split(/\//,$path);
                   13188:     my $cleanpath;
                   13189:     my $fullpath = $url;
                   13190:     for (my $i=0;$i<@parts;$i++) {
                   13191:         next if ($parts[$i] eq '.');
                   13192:         if ($parts[$i] eq '..') {
                   13193:             $fullpath =~ s{([^/]+/)$}{};
                   13194:         } else {
                   13195:             $fullpath .= $parts[$i].'/';
                   13196:         }
                   13197:     }
                   13198:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13199:         $cleanpath = $1;
                   13200:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13201:         my $curr_toprel = $1;
                   13202:         my @parts = split(/\//,$curr_toprel);
                   13203:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13204:         my @urlparts = split(/\//,$url_toprel);
                   13205:         my $doubledots;
                   13206:         my $startdiff = -1;
                   13207:         for (my $i=0; $i<@urlparts; $i++) {
                   13208:             if ($startdiff == -1) {
                   13209:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13210:                     $startdiff = $i;
                   13211:                     $doubledots .= '../';
                   13212:                 }
                   13213:             } else {
                   13214:                 $doubledots .= '../';
                   13215:             }
                   13216:         }
                   13217:         if ($startdiff > -1) {
                   13218:             $cleanpath = $doubledots;
                   13219:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13220:                 $cleanpath .= $parts[$i].'/';
                   13221:             }
                   13222:         }
                   13223:     }
                   13224:     $cleanpath =~ s{(/)$}{};
                   13225:     return $cleanpath;
                   13226: }
1.31      albertel 13227: 
1.1053    raeburn  13228: sub is_archive_file {
                   13229:     my ($mimetype) = @_;
                   13230:     if (($mimetype eq 'application/octet-stream') ||
                   13231:         ($mimetype eq 'application/x-stuffit') ||
                   13232:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13233:         return 1;
                   13234:     }
                   13235:     return;
                   13236: }
                   13237: 
                   13238: sub decompress_form {
1.1065    raeburn  13239:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13240:     my %lt = &Apache::lonlocal::texthash (
                   13241:         this => 'This file is an archive file.',
1.1067    raeburn  13242:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13243:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13244:         youm => 'You may wish to extract its contents.',
                   13245:         extr => 'Extract contents',
1.1067    raeburn  13246:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13247:         proa => 'Process automatically?',
1.1053    raeburn  13248:         yes  => 'Yes',
                   13249:         no   => 'No',
1.1067    raeburn  13250:         fold => 'Title for folder containing movie',
                   13251:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13252:     );
1.1065    raeburn  13253:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13254:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13255:     my $info = &list_archive_contents($fileloc,\@paths);
                   13256:     if (@paths) {
                   13257:         foreach my $path (@paths) {
                   13258:             $path =~ s{^/}{};
1.1067    raeburn  13259:             if ($path =~ m{^([^/]+)/$}) {
                   13260:                 $topdir = $1;
                   13261:             }
1.1065    raeburn  13262:             if ($path =~ m{^([^/]+)/}) {
                   13263:                 $toplevel{$1} = $path;
                   13264:             } else {
                   13265:                 $toplevel{$path} = $path;
                   13266:             }
                   13267:         }
                   13268:     }
1.1067    raeburn  13269:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  13270:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13271:                         "$topdir/media/",
                   13272:                         "$topdir/media/$topdir.mp4",
                   13273:                         "$topdir/media/FirstFrame.png",
                   13274:                         "$topdir/media/player.swf",
                   13275:                         "$topdir/media/swfobject.js",
                   13276:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  13277:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  13278:                          "$topdir/$topdir.mp4",
                   13279:                          "$topdir/$topdir\_config.xml",
                   13280:                          "$topdir/$topdir\_controller.swf",
                   13281:                          "$topdir/$topdir\_embed.css",
                   13282:                          "$topdir/$topdir\_First_Frame.png",
                   13283:                          "$topdir/$topdir\_player.html",
                   13284:                          "$topdir/$topdir\_Thumbnails.png",
                   13285:                          "$topdir/playerProductInstall.swf",
                   13286:                          "$topdir/scripts/",
                   13287:                          "$topdir/scripts/config_xml.js",
                   13288:                          "$topdir/scripts/handlebars.js",
                   13289:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13290:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13291:                          "$topdir/scripts/modernizr.js",
                   13292:                          "$topdir/scripts/player-min.js",
                   13293:                          "$topdir/scripts/swfobject.js",
                   13294:                          "$topdir/skins/",
                   13295:                          "$topdir/skins/configuration_express.xml",
                   13296:                          "$topdir/skins/express_show/",
                   13297:                          "$topdir/skins/express_show/player-min.css",
                   13298:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  13299:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13300:                          "$topdir/$topdir.mp4",
                   13301:                          "$topdir/$topdir\_config.xml",
                   13302:                          "$topdir/$topdir\_controller.swf",
                   13303:                          "$topdir/$topdir\_embed.css",
                   13304:                          "$topdir/$topdir\_First_Frame.png",
                   13305:                          "$topdir/$topdir\_player.html",
                   13306:                          "$topdir/$topdir\_Thumbnails.png",
                   13307:                          "$topdir/playerProductInstall.swf",
                   13308:                          "$topdir/scripts/",
                   13309:                          "$topdir/scripts/config_xml.js",
                   13310:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13311:                          "$topdir/skins/",
                   13312:                          "$topdir/skins/configuration_express.xml",
                   13313:                          "$topdir/skins/express_show/",
                   13314:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13315:                          "$topdir/skins/express_show/spritesheet.png",
                   13316:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  13317:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13318:         if (@diffs == 0) {
1.1075.2.59  raeburn  13319:             $is_camtasia = 6;
                   13320:         } else {
1.1075.2.81  raeburn  13321:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  13322:             if (@diffs == 0) {
                   13323:                 $is_camtasia = 8;
1.1075.2.81  raeburn  13324:             } else {
                   13325:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13326:                 if (@diffs == 0) {
                   13327:                     $is_camtasia = 8;
                   13328:                 }
1.1075.2.59  raeburn  13329:             }
1.1067    raeburn  13330:         }
                   13331:     }
                   13332:     my $output;
                   13333:     if ($is_camtasia) {
                   13334:         $output = <<"ENDCAM";
                   13335: <script type="text/javascript" language="Javascript">
                   13336: // <![CDATA[
                   13337: 
                   13338: function camtasiaToggle() {
                   13339:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13340:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  13341:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13342:                 document.getElementById('camtasia_titles').style.display='block';
                   13343:             } else {
                   13344:                 document.getElementById('camtasia_titles').style.display='none';
                   13345:             }
                   13346:         }
                   13347:     }
                   13348:     return;
                   13349: }
                   13350: 
                   13351: // ]]>
                   13352: </script>
                   13353: <p>$lt{'camt'}</p>
                   13354: ENDCAM
1.1065    raeburn  13355:     } else {
1.1067    raeburn  13356:         $output = '<p>'.$lt{'this'};
                   13357:         if ($info eq '') {
                   13358:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13359:         } else {
                   13360:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13361:                        '<div><pre>'.$info.'</pre></div>';
                   13362:         }
1.1065    raeburn  13363:     }
1.1067    raeburn  13364:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13365:     my $duplicates;
                   13366:     my $num = 0;
                   13367:     if (ref($dirlist) eq 'ARRAY') {
                   13368:         foreach my $item (@{$dirlist}) {
                   13369:             if (ref($item) eq 'ARRAY') {
                   13370:                 if (exists($toplevel{$item->[0]})) {
                   13371:                     $duplicates .= 
                   13372:                         &start_data_table_row().
                   13373:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13374:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13375:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13376:                         'value="1" />'.&mt('Yes').'</label>'.
                   13377:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13378:                         '<td>'.$item->[0].'</td>';
                   13379:                     if ($item->[2]) {
                   13380:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13381:                     } else {
                   13382:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13383:                     }
                   13384:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13385:                                    '<td>'.
                   13386:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13387:                                    '</td>'.
                   13388:                                    &end_data_table_row();
                   13389:                     $num ++;
                   13390:                 }
                   13391:             }
                   13392:         }
                   13393:     }
                   13394:     my $itemcount;
                   13395:     if (@paths > 0) {
                   13396:         $itemcount = scalar(@paths);
                   13397:     } else {
                   13398:         $itemcount = 1;
                   13399:     }
1.1067    raeburn  13400:     if ($is_camtasia) {
                   13401:         $output .= $lt{'auto'}.'<br />'.
                   13402:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  13403:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13404:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13405:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13406:                    $lt{'no'}.'</label></span><br />'.
                   13407:                    '<div id="camtasia_titles" style="display:block">'.
                   13408:                    &Apache::lonhtmlcommon::start_pick_box().
                   13409:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13410:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13411:                    &Apache::lonhtmlcommon::row_closure().
                   13412:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13413:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13414:                    &Apache::lonhtmlcommon::row_closure(1).
                   13415:                    &Apache::lonhtmlcommon::end_pick_box().
                   13416:                    '</div>';
                   13417:     }
1.1065    raeburn  13418:     $output .= 
                   13419:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13420:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13421:         "\n";
1.1065    raeburn  13422:     if ($duplicates ne '') {
                   13423:         $output .= '<p><span class="LC_warning">'.
                   13424:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13425:                    &start_data_table().
                   13426:                    &start_data_table_header_row().
                   13427:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13428:                    '<th>'.&mt('Name').'</th>'.
                   13429:                    '<th>'.&mt('Type').'</th>'.
                   13430:                    '<th>'.&mt('Size').'</th>'.
                   13431:                    '<th>'.&mt('Last modified').'</th>'.
                   13432:                    &end_data_table_header_row().
                   13433:                    $duplicates.
                   13434:                    &end_data_table().
                   13435:                    '</p>';
                   13436:     }
1.1067    raeburn  13437:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13438:     if (ref($hiddenelements) eq 'HASH') {
                   13439:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13440:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13441:         }
                   13442:     }
                   13443:     $output .= <<"END";
1.1067    raeburn  13444: <br />
1.1053    raeburn  13445: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13446: </form>
                   13447: $noextract
                   13448: END
                   13449:     return $output;
                   13450: }
                   13451: 
1.1065    raeburn  13452: sub decompression_utility {
                   13453:     my ($program) = @_;
                   13454:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13455:     my $location;
                   13456:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13457:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13458:                          '/usr/sbin/') {
                   13459:             if (-x $dir.$program) {
                   13460:                 $location = $dir.$program;
                   13461:                 last;
                   13462:             }
                   13463:         }
                   13464:     }
                   13465:     return $location;
                   13466: }
                   13467: 
                   13468: sub list_archive_contents {
                   13469:     my ($file,$pathsref) = @_;
                   13470:     my (@cmd,$output);
                   13471:     my $needsregexp;
                   13472:     if ($file =~ /\.zip$/) {
                   13473:         @cmd = (&decompression_utility('unzip'),"-l");
                   13474:         $needsregexp = 1;
                   13475:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13476:              ($file =~ /\.tgz$/)) {
                   13477:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13478:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13479:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13480:     } elsif ($file =~ m|\.tar$|) {
                   13481:         @cmd = (&decompression_utility('tar'),"-tf");
                   13482:     }
                   13483:     if (@cmd) {
                   13484:         undef($!);
                   13485:         undef($@);
                   13486:         if (open(my $fh,"-|", @cmd, $file)) {
                   13487:             while (my $line = <$fh>) {
                   13488:                 $output .= $line;
                   13489:                 chomp($line);
                   13490:                 my $item;
                   13491:                 if ($needsregexp) {
                   13492:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13493:                 } else {
                   13494:                     $item = $line;
                   13495:                 }
                   13496:                 if ($item ne '') {
                   13497:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13498:                         push(@{$pathsref},$item);
                   13499:                     } 
                   13500:                 }
                   13501:             }
                   13502:             close($fh);
                   13503:         }
                   13504:     }
                   13505:     return $output;
                   13506: }
                   13507: 
1.1053    raeburn  13508: sub decompress_uploaded_file {
                   13509:     my ($file,$dir) = @_;
                   13510:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13511:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13512:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13513:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13514:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13515:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13516:     my $decompressed = $env{'cgi.decompressed'};
                   13517:     &Apache::lonnet::delenv('cgi.file');
                   13518:     &Apache::lonnet::delenv('cgi.dir');
                   13519:     &Apache::lonnet::delenv('cgi.decompressed');
                   13520:     return ($decompressed,$result);
                   13521: }
                   13522: 
1.1055    raeburn  13523: sub process_decompression {
                   13524:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13525:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13526:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13527:                &mt('Unexpected file path.').'</p>'."\n";
                   13528:     }
                   13529:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13530:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13531:                &mt('Unexpected course context.').'</p>'."\n";
                   13532:     }
                   13533:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13534:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13535:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13536:     }
1.1055    raeburn  13537:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13538:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13539:         $error = &mt('Filename not a supported archive file type.').
                   13540:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13541:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13542:     } else {
                   13543:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13544:         if ($docuhome eq 'no_host') {
                   13545:             $error = &mt('Could not determine home server for course.');
                   13546:         } else {
                   13547:             my @ids=&Apache::lonnet::current_machine_ids();
                   13548:             my $currdir = "$dir_root/$destination";
                   13549:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13550:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13551:                        "$dir_root/$destination";
                   13552:             } else {
                   13553:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13554:                        "$dir_root/$docudom/$docuname/$destination";
                   13555:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13556:                     $error = &mt('Archive file not found.');
                   13557:                 }
                   13558:             }
1.1065    raeburn  13559:             my (@to_overwrite,@to_skip);
                   13560:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13561:                 my $total = $env{'form.archive_overwrite_total'};
                   13562:                 for (my $i=0; $i<$total; $i++) {
                   13563:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13564:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13565:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13566:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13567:                     }
                   13568:                 }
                   13569:             }
                   13570:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13571:             my $numoverwrite = scalar(@to_overwrite);
                   13572:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13573:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13574:             } elsif ($dir eq '') {
1.1055    raeburn  13575:                 $error = &mt('Directory containing archive file unavailable.');
                   13576:             } elsif (!$error) {
1.1065    raeburn  13577:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13578:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13579:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13580:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13581:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13582:                         ($decompressed,$display) =
                   13583:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13584:                         foreach my $item (@to_skip) {
                   13585:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13586:                                 if (-f "$dir/$tempdir/$item") {
                   13587:                                     unlink("$dir/$tempdir/$item");
                   13588:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13589:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13590:                                 }
                   13591:                             }
                   13592:                         }
                   13593:                         foreach my $item (@to_overwrite) {
                   13594:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13595:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13596:                                     if (-f "$dir/$item") {
                   13597:                                         unlink("$dir/$item");
                   13598:                                     } elsif (-d "$dir/$item") {
                   13599:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13600:                                     }
                   13601:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13602:                                 }
1.1065    raeburn  13603:                             }
                   13604:                         }
1.1075.2.128  raeburn  13605:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13606:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13607:                         }
1.1065    raeburn  13608:                     }
                   13609:                 } else {
                   13610:                     ($decompressed,$display) = 
                   13611:                         &decompress_uploaded_file($file,$dir);
                   13612:                 }
1.1055    raeburn  13613:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13614:                     $output = '<p class="LC_info">'.
                   13615:                               &mt('Files extracted successfully from archive.').
                   13616:                               '</p>'."\n";
1.1055    raeburn  13617:                     my ($warning,$result,@contents);
                   13618:                     my ($newdirlistref,$newlisterror) =
                   13619:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13620:                                                  $docuname,1);
                   13621:                     my (%is_dir,%changes,@newitems);
                   13622:                     my $dirptr = 16384;
1.1065    raeburn  13623:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13624:                         foreach my $dir_line (@{$newdirlistref}) {
                   13625:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13626:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13627:                                 push(@newitems,$item);
                   13628:                                 if ($dirptr&$testdir) {
                   13629:                                     $is_dir{$item} = 1;
                   13630:                                 }
                   13631:                                 $changes{$item} = 1;
                   13632:                             }
                   13633:                         }
                   13634:                     }
                   13635:                     if (keys(%changes) > 0) {
                   13636:                         foreach my $item (sort(@newitems)) {
                   13637:                             if ($changes{$item}) {
                   13638:                                 push(@contents,$item);
                   13639:                             }
                   13640:                         }
                   13641:                     }
                   13642:                     if (@contents > 0) {
1.1067    raeburn  13643:                         my $wantform;
                   13644:                         unless ($env{'form.autoextract_camtasia'}) {
                   13645:                             $wantform = 1;
                   13646:                         }
1.1056    raeburn  13647:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13648:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13649:                                                                 $currdir,\%is_dir,
                   13650:                                                                 \%children,\%parent,
1.1056    raeburn  13651:                                                                 \@contents,\%dirorder,
                   13652:                                                                 \%titles,$wantform);
1.1055    raeburn  13653:                         if ($datatable ne '') {
                   13654:                             $output .= &archive_options_form('decompressed',$datatable,
                   13655:                                                              $count,$hiddenelem);
1.1065    raeburn  13656:                             my $startcount = 6;
1.1055    raeburn  13657:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13658:                                                            \%titles,\%children);
1.1055    raeburn  13659:                         }
1.1067    raeburn  13660:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13661:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13662:                             my %displayed;
                   13663:                             my $total = 1;
                   13664:                             $env{'form.archive_directory'} = [];
                   13665:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13666:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13667:                                 $path =~ s{/$}{};
                   13668:                                 my $item;
                   13669:                                 if ($path ne '') {
                   13670:                                     $item = "$path/$titles{$i}";
                   13671:                                 } else {
                   13672:                                     $item = $titles{$i};
                   13673:                                 }
                   13674:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13675:                                 if ($item eq $contents[0]) {
                   13676:                                     push(@{$env{'form.archive_directory'}},$i);
                   13677:                                     $env{'form.archive_'.$i} = 'display';
                   13678:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13679:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13680:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13681:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13682:                                     $env{'form.archive_'.$i} = 'display';
                   13683:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13684:                                     $displayed{'web'} = $i;
                   13685:                                 } else {
1.1075.2.59  raeburn  13686:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13687:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13688:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13689:                                         push(@{$env{'form.archive_directory'}},$i);
                   13690:                                     }
                   13691:                                     $env{'form.archive_'.$i} = 'dependency';
                   13692:                                 }
                   13693:                                 $total ++;
                   13694:                             }
                   13695:                             for (my $i=1; $i<$total; $i++) {
                   13696:                                 next if ($i == $displayed{'web'});
                   13697:                                 next if ($i == $displayed{'folder'});
                   13698:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13699:                             }
                   13700:                             $env{'form.phase'} = 'decompress_cleanup';
                   13701:                             $env{'form.archivedelete'} = 1;
                   13702:                             $env{'form.archive_count'} = $total-1;
                   13703:                             $output .=
                   13704:                                 &process_extracted_files('coursedocs',$docudom,
                   13705:                                                          $docuname,$destination,
                   13706:                                                          $dir_root,$hiddenelem);
                   13707:                         }
1.1055    raeburn  13708:                     } else {
                   13709:                         $warning = &mt('No new items extracted from archive file.');
                   13710:                     }
                   13711:                 } else {
                   13712:                     $output = $display;
                   13713:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13714:                 }
                   13715:             }
                   13716:         }
                   13717:     }
                   13718:     if ($error) {
                   13719:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13720:                    $error.'</p>'."\n";
                   13721:     }
                   13722:     if ($warning) {
                   13723:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13724:     }
                   13725:     return $output;
                   13726: }
                   13727: 
                   13728: sub get_extracted {
1.1056    raeburn  13729:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13730:         $titles,$wantform) = @_;
1.1055    raeburn  13731:     my $count = 0;
                   13732:     my $depth = 0;
                   13733:     my $datatable;
1.1056    raeburn  13734:     my @hierarchy;
1.1055    raeburn  13735:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13736:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13737:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13738:     foreach my $item (@{$contents}) {
                   13739:         $count ++;
1.1056    raeburn  13740:         @{$dirorder->{$count}} = @hierarchy;
                   13741:         $titles->{$count} = $item;
1.1055    raeburn  13742:         &archive_hierarchy($depth,$count,$parent,$children);
                   13743:         if ($wantform) {
                   13744:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13745:                                        $currdir,$depth,$count);
                   13746:         }
                   13747:         if ($is_dir->{$item}) {
                   13748:             $depth ++;
1.1056    raeburn  13749:             push(@hierarchy,$count);
                   13750:             $parent->{$depth} = $count;
1.1055    raeburn  13751:             $datatable .=
                   13752:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13753:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13754:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13755:             $depth --;
1.1056    raeburn  13756:             pop(@hierarchy);
1.1055    raeburn  13757:         }
                   13758:     }
                   13759:     return ($count,$datatable);
                   13760: }
                   13761: 
                   13762: sub recurse_extracted_archive {
1.1056    raeburn  13763:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13764:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13765:     my $result='';
1.1056    raeburn  13766:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13767:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13768:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13769:         return $result;
                   13770:     }
                   13771:     my $dirptr = 16384;
                   13772:     my ($newdirlistref,$newlisterror) =
                   13773:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13774:     if (ref($newdirlistref) eq 'ARRAY') {
                   13775:         foreach my $dir_line (@{$newdirlistref}) {
                   13776:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13777:             unless ($item =~ /^\.+$/) {
                   13778:                 $$count ++;
1.1056    raeburn  13779:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13780:                 $titles->{$$count} = $item;
1.1055    raeburn  13781:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13782: 
1.1055    raeburn  13783:                 my $is_dir;
                   13784:                 if ($dirptr&$testdir) {
                   13785:                     $is_dir = 1;
                   13786:                 }
                   13787:                 if ($wantform) {
                   13788:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13789:                 }
                   13790:                 if ($is_dir) {
                   13791:                     $$depth ++;
1.1056    raeburn  13792:                     push(@{$hierarchy},$$count);
                   13793:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13794:                     $result .=
                   13795:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13796:                                                    $docuname,$depth,$count,
1.1056    raeburn  13797:                                                    $hierarchy,$dirorder,$children,
                   13798:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13799:                     $$depth --;
1.1056    raeburn  13800:                     pop(@{$hierarchy});
1.1055    raeburn  13801:                 }
                   13802:             }
                   13803:         }
                   13804:     }
                   13805:     return $result;
                   13806: }
                   13807: 
                   13808: sub archive_hierarchy {
                   13809:     my ($depth,$count,$parent,$children) =@_;
                   13810:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13811:         if (exists($parent->{$depth})) {
                   13812:              $children->{$parent->{$depth}} .= $count.':';
                   13813:         }
                   13814:     }
                   13815:     return;
                   13816: }
                   13817: 
                   13818: sub archive_row {
                   13819:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13820:     my ($name) = ($item =~ m{([^/]+)$});
                   13821:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13822:                                        'display'    => 'Add as file',
1.1055    raeburn  13823:                                        'dependency' => 'Include as dependency',
                   13824:                                        'discard'    => 'Discard',
                   13825:                                       );
                   13826:     if ($is_dir) {
1.1059    raeburn  13827:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13828:     }
1.1056    raeburn  13829:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13830:     my $offset = 0;
1.1055    raeburn  13831:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13832:         $offset ++;
1.1065    raeburn  13833:         if ($action ne 'display') {
                   13834:             $offset ++;
                   13835:         }  
1.1055    raeburn  13836:         $output .= '<td><span class="LC_nobreak">'.
                   13837:                    '<label><input type="radio" name="archive_'.$count.
                   13838:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13839:         my $text = $choices{$action};
                   13840:         if ($is_dir) {
                   13841:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13842:             if ($action eq 'display') {
1.1059    raeburn  13843:                 $text = &mt('Add as folder');
1.1055    raeburn  13844:             }
1.1056    raeburn  13845:         } else {
                   13846:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13847: 
                   13848:         }
                   13849:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13850:         if ($action eq 'dependency') {
                   13851:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13852:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13853:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13854:                        '<option value=""></option>'."\n".
                   13855:                        '</select>'."\n".
                   13856:                        '</div>';
1.1059    raeburn  13857:         } elsif ($action eq 'display') {
                   13858:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13859:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13860:                        '</div>';
1.1055    raeburn  13861:         }
1.1056    raeburn  13862:         $output .= '</td>';
1.1055    raeburn  13863:     }
                   13864:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13865:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13866:     for (my $i=0; $i<$depth; $i++) {
                   13867:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13868:     }
                   13869:     if ($is_dir) {
                   13870:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13871:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13872:     } else {
                   13873:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13874:     }
                   13875:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13876:                &end_data_table_row();
                   13877:     return $output;
                   13878: }
                   13879: 
                   13880: sub archive_options_form {
1.1065    raeburn  13881:     my ($form,$display,$count,$hiddenelem) = @_;
                   13882:     my %lt = &Apache::lonlocal::texthash(
                   13883:                perm => 'Permanently remove archive file?',
                   13884:                hows => 'How should each extracted item be incorporated in the course?',
                   13885:                cont => 'Content actions for all',
                   13886:                addf => 'Add as folder/file',
                   13887:                incd => 'Include as dependency for a displayed file',
                   13888:                disc => 'Discard',
                   13889:                no   => 'No',
                   13890:                yes  => 'Yes',
                   13891:                save => 'Save',
                   13892:     );
                   13893:     my $output = <<"END";
                   13894: <form name="$form" method="post" action="">
                   13895: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13896: <label>
                   13897:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13898: </label>
                   13899: &nbsp;
                   13900: <label>
                   13901:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13902: </span>
                   13903: </p>
                   13904: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13905: <br />$lt{'hows'}
                   13906: <div class="LC_columnSection">
                   13907:   <fieldset>
                   13908:     <legend>$lt{'cont'}</legend>
                   13909:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13910:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13911:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13912:   </fieldset>
                   13913: </div>
                   13914: END
                   13915:     return $output.
1.1055    raeburn  13916:            &start_data_table()."\n".
1.1065    raeburn  13917:            $display."\n".
1.1055    raeburn  13918:            &end_data_table()."\n".
                   13919:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13920:            $hiddenelem.
1.1065    raeburn  13921:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13922:            '</form>';
                   13923: }
                   13924: 
                   13925: sub archive_javascript {
1.1056    raeburn  13926:     my ($startcount,$numitems,$titles,$children) = @_;
                   13927:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13928:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13929:     my $scripttag = <<START;
                   13930: <script type="text/javascript">
                   13931: // <![CDATA[
                   13932: 
                   13933: function checkAll(form,prefix) {
                   13934:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13935:     for (var i=0; i < form.elements.length; i++) {
                   13936:         var id = form.elements[i].id;
                   13937:         if ((id != '') && (id != undefined)) {
                   13938:             if (idstr.test(id)) {
                   13939:                 if (form.elements[i].type == 'radio') {
                   13940:                     form.elements[i].checked = true;
1.1056    raeburn  13941:                     var nostart = i-$startcount;
1.1059    raeburn  13942:                     var offset = nostart%7;
                   13943:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13944:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13945:                 }
                   13946:             }
                   13947:         }
                   13948:     }
                   13949: }
                   13950: 
                   13951: function propagateCheck(form,count) {
                   13952:     if (count > 0) {
1.1059    raeburn  13953:         var startelement = $startcount + ((count-1) * 7);
                   13954:         for (var j=1; j<6; j++) {
                   13955:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13956:                 var item = startelement + j; 
                   13957:                 if (form.elements[item].type == 'radio') {
                   13958:                     if (form.elements[item].checked) {
                   13959:                         containerCheck(form,count,j);
                   13960:                         break;
                   13961:                     }
1.1055    raeburn  13962:                 }
                   13963:             }
                   13964:         }
                   13965:     }
                   13966: }
                   13967: 
                   13968: numitems = $numitems
1.1056    raeburn  13969: var titles = new Array(numitems);
                   13970: var parents = new Array(numitems);
1.1055    raeburn  13971: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13972:     parents[i] = new Array;
1.1055    raeburn  13973: }
1.1059    raeburn  13974: var maintitle = '$maintitle';
1.1055    raeburn  13975: 
                   13976: START
                   13977: 
1.1056    raeburn  13978:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13979:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13980:         for (my $i=0; $i<@contents; $i ++) {
                   13981:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13982:         }
                   13983:     }
                   13984: 
1.1056    raeburn  13985:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13986:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13987:     }
                   13988: 
1.1055    raeburn  13989:     $scripttag .= <<END;
                   13990: 
                   13991: function containerCheck(form,count,offset) {
                   13992:     if (count > 0) {
1.1056    raeburn  13993:         dependencyCheck(form,count,offset);
1.1059    raeburn  13994:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13995:         form.elements[item].checked = true;
                   13996:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13997:             if (parents[count].length > 0) {
                   13998:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13999:                     containerCheck(form,parents[count][j],offset);
                   14000:                 }
                   14001:             }
                   14002:         }
                   14003:     }
                   14004: }
                   14005: 
                   14006: function dependencyCheck(form,count,offset) {
                   14007:     if (count > 0) {
1.1059    raeburn  14008:         var chosen = (offset+$startcount)+7*(count-1);
                   14009:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14010:         var currtype = form.elements[depitem].type;
                   14011:         if (form.elements[chosen].value == 'dependency') {
                   14012:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14013:             form.elements[depitem].options.length = 0;
                   14014:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  14015:             for (var i=1; i<=numitems; i++) {
                   14016:                 if (i == count) {
                   14017:                     continue;
                   14018:                 }
1.1059    raeburn  14019:                 var startelement = $startcount + (i-1) * 7;
                   14020:                 for (var j=1; j<6; j++) {
                   14021:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14022:                         var item = startelement + j;
                   14023:                         if (form.elements[item].type == 'radio') {
                   14024:                             if (form.elements[item].checked) {
                   14025:                                 if (form.elements[item].value == 'display') {
                   14026:                                     var n = form.elements[depitem].options.length;
                   14027:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14028:                                 }
                   14029:                             }
                   14030:                         }
                   14031:                     }
                   14032:                 }
                   14033:             }
                   14034:         } else {
                   14035:             document.getElementById('arc_depon_'+count).style.display='none';
                   14036:             form.elements[depitem].options.length = 0;
                   14037:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14038:         }
1.1059    raeburn  14039:         titleCheck(form,count,offset);
1.1056    raeburn  14040:     }
                   14041: }
                   14042: 
                   14043: function propagateSelect(form,count,offset) {
                   14044:     if (count > 0) {
1.1065    raeburn  14045:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14046:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14047:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14048:             if (parents[count].length > 0) {
                   14049:                 for (var j=0; j<parents[count].length; j++) {
                   14050:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14051:                 }
                   14052:             }
                   14053:         }
                   14054:     }
                   14055: }
1.1056    raeburn  14056: 
                   14057: function containerSelect(form,count,offset,picked) {
                   14058:     if (count > 0) {
1.1065    raeburn  14059:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14060:         if (form.elements[item].type == 'radio') {
                   14061:             if (form.elements[item].value == 'dependency') {
                   14062:                 if (form.elements[item+1].type == 'select-one') {
                   14063:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14064:                         if (form.elements[item+1].options[i].value == picked) {
                   14065:                             form.elements[item+1].selectedIndex = i;
                   14066:                             break;
                   14067:                         }
                   14068:                     }
                   14069:                 }
                   14070:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14071:                     if (parents[count].length > 0) {
                   14072:                         for (var j=0; j<parents[count].length; j++) {
                   14073:                             containerSelect(form,parents[count][j],offset,picked);
                   14074:                         }
                   14075:                     }
                   14076:                 }
                   14077:             }
                   14078:         }
                   14079:     }
                   14080: }
                   14081: 
1.1059    raeburn  14082: function titleCheck(form,count,offset) {
                   14083:     if (count > 0) {
                   14084:         var chosen = (offset+$startcount)+7*(count-1);
                   14085:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14086:         var currtype = form.elements[depitem].type;
                   14087:         if (form.elements[chosen].value == 'display') {
                   14088:             document.getElementById('arc_title_'+count).style.display='block';
                   14089:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14090:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14091:             }
                   14092:         } else {
                   14093:             document.getElementById('arc_title_'+count).style.display='none';
                   14094:             if (currtype == 'text') { 
                   14095:                 document.getElementById('archive_title_'+count).value='';
                   14096:             }
                   14097:         }
                   14098:     }
                   14099:     return;
                   14100: }
                   14101: 
1.1055    raeburn  14102: // ]]>
                   14103: </script>
                   14104: END
                   14105:     return $scripttag;
                   14106: }
                   14107: 
                   14108: sub process_extracted_files {
1.1067    raeburn  14109:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14110:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  14111:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14112:     my @ids=&Apache::lonnet::current_machine_ids();
                   14113:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14114:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14115:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14116:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14117:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14118:         $pathtocheck = "$dir_root/$destination";
                   14119:         $dir = $dir_root;
                   14120:         $ishome = 1;
                   14121:     } else {
                   14122:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14123:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  14124:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14125:     }
                   14126:     my $currdir = "$dir_root/$destination";
                   14127:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14128:     if ($env{'form.folderpath'}) {
                   14129:         my @items = split('&',$env{'form.folderpath'});
                   14130:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  14131:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14132:             $containers{'0'}='page';
                   14133:         } else {
                   14134:             $containers{'0'}='sequence';
                   14135:         }
1.1055    raeburn  14136:     }
                   14137:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14138:     if ($numitems) {
                   14139:         for (my $i=1; $i<=$numitems; $i++) {
                   14140:             my $path = $env{'form.archive_content_'.$i};
                   14141:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14142:                 my $item = $1;
                   14143:                 $toplevelitems{$item} = $i;
                   14144:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14145:                     $is_dir{$item} = 1;
                   14146:                 }
                   14147:             }
                   14148:         }
                   14149:     }
1.1067    raeburn  14150:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14151:     if (keys(%toplevelitems) > 0) {
                   14152:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14153:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14154:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14155:     }
1.1066    raeburn  14156:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14157:     if ($numitems) {
                   14158:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  14159:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14160:             my $path = $env{'form.archive_content_'.$i};
                   14161:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14162:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14163:                     if ($prefix ne '' && $path ne '') {
                   14164:                         if (-e $prefix.$path) {
1.1066    raeburn  14165:                             if ((@archdirs > 0) && 
                   14166:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14167:                                 $todeletedir{$prefix.$path} = 1;
                   14168:                             } else {
                   14169:                                 $todelete{$prefix.$path} = 1;
                   14170:                             }
1.1055    raeburn  14171:                         }
                   14172:                     }
                   14173:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14174:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14175:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14176:                     $docstitle = $env{'form.archive_title_'.$i};
                   14177:                     if ($docstitle eq '') {
                   14178:                         $docstitle = $title;
                   14179:                     }
1.1055    raeburn  14180:                     $outer = 0;
1.1056    raeburn  14181:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14182:                         if (@{$dirorder{$i}} > 0) {
                   14183:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14184:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14185:                                     $outer = $item;
                   14186:                                     last;
                   14187:                                 }
                   14188:                             }
                   14189:                         }
                   14190:                     }
                   14191:                     my ($errtext,$fatal) = 
                   14192:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14193:                                                '/'.$folders{$outer}.'.'.
                   14194:                                                $containers{$outer});
                   14195:                     next if ($fatal);
                   14196:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14197:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14198:                             $mapinner{$i} = time;
1.1055    raeburn  14199:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14200:                             $containers{$i} = 'sequence';
                   14201:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14202:                                       $folders{$i}.'.'.$containers{$i};
                   14203:                             my $newidx = &LONCAPA::map::getresidx();
                   14204:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14205:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14206:                             push(@LONCAPA::map::order,$newidx);
                   14207:                             my ($outtext,$errtext) =
                   14208:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14209:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  14210:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14211:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14212:                             unless ($errtext) {
1.1075.2.128  raeburn  14213:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14214:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   14215:                                             '</li>'."\n";
1.1067    raeburn  14216:                             }
1.1055    raeburn  14217:                         }
                   14218:                     } else {
                   14219:                         if ($context eq 'coursedocs') {
                   14220:                             my $newidx=&LONCAPA::map::getresidx();
                   14221:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14222:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14223:                                       $title;
1.1075.2.161.  .13(raeb 14224:-23):                             if (($outer !~ /\D/) &&
                   14225:-23):                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14226:-23):                                 ($newidx !~ /\D/)) {
1.1075.2.128  raeburn  14227:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14228:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  14229:                                 }
1.1075.2.128  raeburn  14230:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14231:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14232:                                 }
                   14233:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14234:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14235:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14236:                                         unless ($ishome) {
                   14237:                                             my $fetch = "$newdest{$i}/$title";
                   14238:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14239:                                             $prompttofetch{$fetch} = 1;
                   14240:                                         }
                   14241:                                    }
                   14242:                                 }
                   14243:                                 $LONCAPA::map::resources[$newidx]=
                   14244:                                     $docstitle.':'.$url.':false:normal:res';
                   14245:                                 push(@LONCAPA::map::order, $newidx);
                   14246:                                 my ($outtext,$errtext)=
                   14247:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14248:                                                             $docuname.'/'.$folders{$outer}.
                   14249:                                                             '.'.$containers{$outer},1,1);
                   14250:                                 unless ($errtext) {
                   14251:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14252:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14253:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14254:                                                    '</li>'."\n";
                   14255:                                     }
1.1067    raeburn  14256:                                 }
1.1075.2.128  raeburn  14257:                             } else {
                   14258:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14259:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  14260:                             }
1.1055    raeburn  14261:                         }
                   14262:                     }
1.1075.2.11  raeburn  14263:                 }
                   14264:             } else {
1.1075.2.128  raeburn  14265:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14266:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  14267:             }
                   14268:         }
                   14269:         for (my $i=1; $i<=$numitems; $i++) {
                   14270:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14271:             my $path = $env{'form.archive_content_'.$i};
                   14272:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14273:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14274:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14275:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14276:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14277:                         my ($itemidx,$fullpath,$relpath);
                   14278:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14279:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14280:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  14281:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14282:                                     $itemidx = $j;
1.1056    raeburn  14283:                                 }
                   14284:                             }
1.1075.2.11  raeburn  14285:                         }
                   14286:                         if ($itemidx eq '') {
                   14287:                             $itemidx =  0;
                   14288:                         }
                   14289:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14290:                             if ($mapinner{$referrer{$i}}) {
                   14291:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14292:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14293:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14294:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14295:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14296:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14297:                                             if (!-e $fullpath) {
                   14298:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14299:                                             }
                   14300:                                         }
1.1075.2.11  raeburn  14301:                                     } else {
                   14302:                                         last;
1.1056    raeburn  14303:                                     }
1.1075.2.11  raeburn  14304:                                 }
                   14305:                             }
                   14306:                         } elsif ($newdest{$referrer{$i}}) {
                   14307:                             $fullpath = $newdest{$referrer{$i}};
                   14308:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14309:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14310:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14311:                                     last;
                   14312:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14313:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14314:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14315:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14316:                                         if (!-e $fullpath) {
                   14317:                                             mkdir($fullpath,0755);
1.1056    raeburn  14318:                                         }
                   14319:                                     }
1.1075.2.11  raeburn  14320:                                 } else {
                   14321:                                     last;
1.1056    raeburn  14322:                                 }
1.1075.2.11  raeburn  14323:                             }
                   14324:                         }
                   14325:                         if ($fullpath ne '') {
                   14326:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  14327:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14328:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14329:                                 }
1.1075.2.11  raeburn  14330:                             }
                   14331:                             if (-e "$fullpath/$title") {
                   14332:                                 my $showpath;
                   14333:                                 if ($relpath ne '') {
                   14334:                                     $showpath = "$relpath/$title";
                   14335:                                 } else {
                   14336:                                     $showpath = "/$title";
1.1056    raeburn  14337:                                 }
1.1075.2.128  raeburn  14338:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14339:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14340:                                            '</li>'."\n";
                   14341:                                 unless ($ishome) {
                   14342:                                     my $fetch = "$fullpath/$title";
                   14343:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   14344:                                     $prompttofetch{$fetch} = 1;
                   14345:                                 }
1.1055    raeburn  14346:                             }
                   14347:                         }
                   14348:                     }
1.1075.2.11  raeburn  14349:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14350:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  14351:                                     &HTML::Entities::encode($path,'<>&"'),
                   14352:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14353:                                 '<br />';
1.1055    raeburn  14354:                 }
                   14355:             } else {
1.1075.2.128  raeburn  14356:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14357:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14358:             }
                   14359:         }
                   14360:         if (keys(%todelete)) {
                   14361:             foreach my $key (keys(%todelete)) {
                   14362:                 unlink($key);
1.1066    raeburn  14363:             }
                   14364:         }
                   14365:         if (keys(%todeletedir)) {
                   14366:             foreach my $key (keys(%todeletedir)) {
                   14367:                 rmdir($key);
                   14368:             }
                   14369:         }
                   14370:         foreach my $dir (sort(keys(%is_dir))) {
                   14371:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14372:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14373:             }
                   14374:         }
1.1067    raeburn  14375:         if ($result ne '') {
                   14376:             $output .= '<ul>'."\n".
                   14377:                        $result."\n".
                   14378:                        '</ul>';
                   14379:         }
                   14380:         unless ($ishome) {
                   14381:             my $replicationfail;
                   14382:             foreach my $item (keys(%prompttofetch)) {
                   14383:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14384:                 unless ($fetchresult eq 'ok') {
                   14385:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14386:                 }
                   14387:             }
                   14388:             if ($replicationfail) {
                   14389:                 $output .= '<p class="LC_error">'.
                   14390:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14391:                            $replicationfail.
                   14392:                            '</ul></p>';
                   14393:             }
                   14394:         }
1.1055    raeburn  14395:     } else {
                   14396:         $warning = &mt('No items found in archive.');
                   14397:     }
                   14398:     if ($error) {
                   14399:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14400:                    $error.'</p>'."\n";
                   14401:     }
                   14402:     if ($warning) {
                   14403:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14404:     }
                   14405:     return $output;
                   14406: }
                   14407: 
1.1066    raeburn  14408: sub cleanup_empty_dirs {
                   14409:     my ($path) = @_;
                   14410:     if (($path ne '') && (-d $path)) {
                   14411:         if (opendir(my $dirh,$path)) {
                   14412:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14413:             my $numitems = 0;
                   14414:             foreach my $item (@dircontents) {
                   14415:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  14416:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14417:                     if (-e "$path/$item") {
                   14418:                         $numitems ++;
                   14419:                     }
                   14420:                 } else {
                   14421:                     $numitems ++;
                   14422:                 }
                   14423:             }
                   14424:             if ($numitems == 0) {
                   14425:                 rmdir($path);
                   14426:             }
                   14427:             closedir($dirh);
                   14428:         }
                   14429:     }
                   14430:     return;
                   14431: }
                   14432: 
1.41      ng       14433: =pod
1.45      matthew  14434: 
1.1075.2.56  raeburn  14435: =item * &get_folder_hierarchy()
1.1068    raeburn  14436: 
                   14437: Provides hierarchy of names of folders/sub-folders containing the current
                   14438: item,
                   14439: 
                   14440: Inputs: 3
                   14441:      - $navmap - navmaps object
                   14442: 
                   14443:      - $map - url for map (either the trigger itself, or map containing
                   14444:                            the resource, which is the trigger).
                   14445: 
                   14446:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14447: 
                   14448: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14449: 
                   14450: =cut
                   14451: 
                   14452: sub get_folder_hierarchy {
                   14453:     my ($navmap,$map,$showitem) = @_;
                   14454:     my @pathitems;
                   14455:     if (ref($navmap)) {
                   14456:         my $mapres = $navmap->getResourceByUrl($map);
                   14457:         if (ref($mapres)) {
                   14458:             my $pcslist = $mapres->map_hierarchy();
                   14459:             if ($pcslist ne '') {
                   14460:                 my @pcs = split(/,/,$pcslist);
                   14461:                 foreach my $pc (@pcs) {
                   14462:                     if ($pc == 1) {
1.1075.2.38  raeburn  14463:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14464:                     } else {
                   14465:                         my $res = $navmap->getByMapPc($pc);
                   14466:                         if (ref($res)) {
                   14467:                             my $title = $res->compTitle();
                   14468:                             $title =~ s/\W+/_/g;
                   14469:                             if ($title ne '') {
                   14470:                                 push(@pathitems,$title);
                   14471:                             }
                   14472:                         }
                   14473:                     }
                   14474:                 }
                   14475:             }
1.1071    raeburn  14476:             if ($showitem) {
                   14477:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  14478:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14479:                 } else {
                   14480:                     my $maptitle = $mapres->compTitle();
                   14481:                     $maptitle =~ s/\W+/_/g;
                   14482:                     if ($maptitle ne '') {
                   14483:                         push(@pathitems,$maptitle);
                   14484:                     }
1.1068    raeburn  14485:                 }
                   14486:             }
                   14487:         }
                   14488:     }
                   14489:     return @pathitems;
                   14490: }
                   14491: 
                   14492: =pod
                   14493: 
1.1015    raeburn  14494: =item * &get_turnedin_filepath()
                   14495: 
                   14496: Determines path in a user's portfolio file for storage of files uploaded
                   14497: to a specific essayresponse or dropbox item.
                   14498: 
                   14499: Inputs: 3 required + 1 optional.
                   14500: $symb is symb for resource, $uname and $udom are for current user (required).
                   14501: $caller is optional (can be "submission", if routine is called when storing
                   14502: an upoaded file when "Submit Answer" button was pressed).
                   14503: 
                   14504: Returns array containing $path and $multiresp. 
                   14505: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14506: than one file upload item.  Callers of routine should append partid as a 
                   14507: subdirectory to $path in cases where $multiresp is 1.
                   14508: 
                   14509: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14510: 
                   14511: =cut
                   14512: 
                   14513: sub get_turnedin_filepath {
                   14514:     my ($symb,$uname,$udom,$caller) = @_;
                   14515:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14516:     my $turnindir;
                   14517:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14518:     $turnindir = $userhash{'turnindir'};
                   14519:     my ($path,$multiresp);
                   14520:     if ($turnindir eq '') {
                   14521:         if ($caller eq 'submission') {
                   14522:             $turnindir = &mt('turned in');
                   14523:             $turnindir =~ s/\W+/_/g;
                   14524:             my %newhash = (
                   14525:                             'turnindir' => $turnindir,
                   14526:                           );
                   14527:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14528:         }
                   14529:     }
                   14530:     if ($turnindir ne '') {
                   14531:         $path = '/'.$turnindir.'/';
                   14532:         my ($multipart,$turnin,@pathitems);
                   14533:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14534:         if (defined($navmap)) {
                   14535:             my $mapres = $navmap->getResourceByUrl($map);
                   14536:             if (ref($mapres)) {
                   14537:                 my $pcslist = $mapres->map_hierarchy();
                   14538:                 if ($pcslist ne '') {
                   14539:                     foreach my $pc (split(/,/,$pcslist)) {
                   14540:                         my $res = $navmap->getByMapPc($pc);
                   14541:                         if (ref($res)) {
                   14542:                             my $title = $res->compTitle();
                   14543:                             $title =~ s/\W+/_/g;
                   14544:                             if ($title ne '') {
1.1075.2.48  raeburn  14545:                                 if (($pc > 1) && (length($title) > 12)) {
                   14546:                                     $title = substr($title,0,12);
                   14547:                                 }
1.1015    raeburn  14548:                                 push(@pathitems,$title);
                   14549:                             }
                   14550:                         }
                   14551:                     }
                   14552:                 }
                   14553:                 my $maptitle = $mapres->compTitle();
                   14554:                 $maptitle =~ s/\W+/_/g;
                   14555:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14556:                     if (length($maptitle) > 12) {
                   14557:                         $maptitle = substr($maptitle,0,12);
                   14558:                     }
1.1015    raeburn  14559:                     push(@pathitems,$maptitle);
                   14560:                 }
                   14561:                 unless ($env{'request.state'} eq 'construct') {
                   14562:                     my $res = $navmap->getBySymb($symb);
                   14563:                     if (ref($res)) {
                   14564:                         my $partlist = $res->parts();
                   14565:                         my $totaluploads = 0;
                   14566:                         if (ref($partlist) eq 'ARRAY') {
                   14567:                             foreach my $part (@{$partlist}) {
                   14568:                                 my @types = $res->responseType($part);
                   14569:                                 my @ids = $res->responseIds($part);
                   14570:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14571:                                     if ($types[$i] eq 'essay') {
                   14572:                                         my $partid = $part.'_'.$ids[$i];
                   14573:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14574:                                             $totaluploads ++;
                   14575:                                         }
                   14576:                                     }
                   14577:                                 }
                   14578:                             }
                   14579:                             if ($totaluploads > 1) {
                   14580:                                 $multiresp = 1;
                   14581:                             }
                   14582:                         }
                   14583:                     }
                   14584:                 }
                   14585:             } else {
                   14586:                 return;
                   14587:             }
                   14588:         } else {
                   14589:             return;
                   14590:         }
                   14591:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14592:         $restitle =~ s/\W+/_/g;
                   14593:         if ($restitle eq '') {
                   14594:             $restitle = ($resurl =~ m{/[^/]+$});
                   14595:             if ($restitle eq '') {
                   14596:                 $restitle = time;
                   14597:             }
                   14598:         }
1.1075.2.48  raeburn  14599:         if (length($restitle) > 12) {
                   14600:             $restitle = substr($restitle,0,12);
                   14601:         }
1.1015    raeburn  14602:         push(@pathitems,$restitle);
                   14603:         $path .= join('/',@pathitems);
                   14604:     }
                   14605:     return ($path,$multiresp);
                   14606: }
                   14607: 
                   14608: =pod
                   14609: 
1.464     albertel 14610: =back
1.41      ng       14611: 
1.112     bowersj2 14612: =head1 CSV Upload/Handling functions
1.38      albertel 14613: 
1.41      ng       14614: =over 4
                   14615: 
1.648     raeburn  14616: =item * &upfile_store($r)
1.41      ng       14617: 
                   14618: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14619: needs $env{'form.upfile'}
1.41      ng       14620: returns $datatoken to be put into hidden field
                   14621: 
                   14622: =cut
1.31      albertel 14623: 
                   14624: sub upfile_store {
                   14625:     my $r=shift;
1.258     albertel 14626:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14627:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14628:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14629:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14630: 
1.1075.2.128  raeburn  14631:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14632:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14633:                                      time.'_'.$$);
                   14634:     return if ($datatoken eq '');
                   14635: 
1.31      albertel 14636:     {
1.158     raeburn  14637:         my $datafile = $r->dir_config('lonDaemons').
                   14638:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14639:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14640:             print $fh $env{'form.upfile'};
1.158     raeburn  14641:             close($fh);
                   14642:         }
1.31      albertel 14643:     }
                   14644:     return $datatoken;
                   14645: }
                   14646: 
1.56      matthew  14647: =pod
                   14648: 
1.1075.2.128  raeburn  14649: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14650: 
                   14651: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14652: $datatoken is the name to assign to the temporary file.
1.258     albertel 14653: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14654: 
                   14655: =cut
1.31      albertel 14656: 
                   14657: sub load_tmp_file {
1.1075.2.128  raeburn  14658:     my ($r,$datatoken) = @_;
                   14659:     return if ($datatoken eq '');
1.31      albertel 14660:     my @studentdata=();
                   14661:     {
1.158     raeburn  14662:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14663:                               '/tmp/'.$datatoken.'.tmp';
                   14664:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14665:             @studentdata=<$fh>;
                   14666:             close($fh);
                   14667:         }
1.31      albertel 14668:     }
1.258     albertel 14669:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14670: }
                   14671: 
1.1075.2.128  raeburn  14672: sub valid_datatoken {
                   14673:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14674:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14675:         return $datatoken;
                   14676:     }
                   14677:     return;
                   14678: }
                   14679: 
1.56      matthew  14680: =pod
                   14681: 
1.648     raeburn  14682: =item * &upfile_record_sep()
1.41      ng       14683: 
                   14684: Separate uploaded file into records
                   14685: returns array of records,
1.258     albertel 14686: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14687: 
                   14688: =cut
1.31      albertel 14689: 
                   14690: sub upfile_record_sep {
1.258     albertel 14691:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14692:     } else {
1.248     albertel 14693: 	my @records;
1.258     albertel 14694: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14695: 	    if ($line=~/^\s*$/) { next; }
                   14696: 	    push(@records,$line);
                   14697: 	}
                   14698: 	return @records;
1.31      albertel 14699:     }
                   14700: }
                   14701: 
1.56      matthew  14702: =pod
                   14703: 
1.648     raeburn  14704: =item * &record_sep($record)
1.41      ng       14705: 
1.258     albertel 14706: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14707: 
                   14708: =cut
                   14709: 
1.263     www      14710: sub takeleft {
                   14711:     my $index=shift;
                   14712:     return substr('0000'.$index,-4,4);
                   14713: }
                   14714: 
1.31      albertel 14715: sub record_sep {
                   14716:     my $record=shift;
                   14717:     my %components=();
1.258     albertel 14718:     if ($env{'form.upfiletype'} eq 'xml') {
                   14719:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14720:         my $i=0;
1.356     albertel 14721:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14722:             $field=~s/^(\"|\')//;
                   14723:             $field=~s/(\"|\')$//;
1.263     www      14724:             $components{&takeleft($i)}=$field;
1.31      albertel 14725:             $i++;
                   14726:         }
1.258     albertel 14727:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14728:         my $i=0;
1.356     albertel 14729:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14730:             $field=~s/^(\"|\')//;
                   14731:             $field=~s/(\"|\')$//;
1.263     www      14732:             $components{&takeleft($i)}=$field;
1.31      albertel 14733:             $i++;
                   14734:         }
                   14735:     } else {
1.561     www      14736:         my $separator=',';
1.480     banghart 14737:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14738:             $separator=';';
1.480     banghart 14739:         }
1.31      albertel 14740:         my $i=0;
1.561     www      14741: # the character we are looking for to indicate the end of a quote or a record 
                   14742:         my $looking_for=$separator;
                   14743: # do not add the characters to the fields
                   14744:         my $ignore=0;
                   14745: # we just encountered a separator (or the beginning of the record)
                   14746:         my $just_found_separator=1;
                   14747: # store the field we are working on here
                   14748:         my $field='';
                   14749: # work our way through all characters in record
                   14750:         foreach my $character ($record=~/(.)/g) {
                   14751:             if ($character eq $looking_for) {
                   14752:                if ($character ne $separator) {
                   14753: # Found the end of a quote, again looking for separator
                   14754:                   $looking_for=$separator;
                   14755:                   $ignore=1;
                   14756:                } else {
                   14757: # Found a separator, store away what we got
                   14758:                   $components{&takeleft($i)}=$field;
                   14759: 	          $i++;
                   14760:                   $just_found_separator=1;
                   14761:                   $ignore=0;
                   14762:                   $field='';
                   14763:                }
                   14764:                next;
                   14765:             }
                   14766: # single or double quotation marks after a separator indicate beginning of a quote
                   14767: # we are now looking for the end of the quote and need to ignore separators
                   14768:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14769:                $looking_for=$character;
                   14770:                next;
                   14771:             }
                   14772: # ignore would be true after we reached the end of a quote
                   14773:             if ($ignore) { next; }
                   14774:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14775:             $field.=$character;
                   14776:             $just_found_separator=0; 
1.31      albertel 14777:         }
1.561     www      14778: # catch the very last entry, since we never encountered the separator
                   14779:         $components{&takeleft($i)}=$field;
1.31      albertel 14780:     }
                   14781:     return %components;
                   14782: }
                   14783: 
1.144     matthew  14784: ######################################################
                   14785: ######################################################
                   14786: 
1.56      matthew  14787: =pod
                   14788: 
1.648     raeburn  14789: =item * &upfile_select_html()
1.41      ng       14790: 
1.144     matthew  14791: Return HTML code to select a file from the users machine and specify 
                   14792: the file type.
1.41      ng       14793: 
                   14794: =cut
                   14795: 
1.144     matthew  14796: ######################################################
                   14797: ######################################################
1.31      albertel 14798: sub upfile_select_html {
1.144     matthew  14799:     my %Types = (
                   14800:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14801:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14802:                  space => &mt('Space separated'),
                   14803:                  tab   => &mt('Tabulator separated'),
                   14804: #                 xml   => &mt('HTML/XML'),
                   14805:                  );
                   14806:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14807:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14808:     foreach my $type (sort(keys(%Types))) {
                   14809:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14810:     }
                   14811:     $Str .= "</select>\n";
                   14812:     return $Str;
1.31      albertel 14813: }
                   14814: 
1.301     albertel 14815: sub get_samples {
                   14816:     my ($records,$toget) = @_;
                   14817:     my @samples=({});
                   14818:     my $got=0;
                   14819:     foreach my $rec (@$records) {
                   14820: 	my %temp = &record_sep($rec);
                   14821: 	if (! grep(/\S/, values(%temp))) { next; }
                   14822: 	if (%temp) {
                   14823: 	    $samples[$got]=\%temp;
                   14824: 	    $got++;
                   14825: 	    if ($got == $toget) { last; }
                   14826: 	}
                   14827:     }
                   14828:     return \@samples;
                   14829: }
                   14830: 
1.144     matthew  14831: ######################################################
                   14832: ######################################################
                   14833: 
1.56      matthew  14834: =pod
                   14835: 
1.648     raeburn  14836: =item * &csv_print_samples($r,$records)
1.41      ng       14837: 
                   14838: Prints a table of sample values from each column uploaded $r is an
                   14839: Apache Request ref, $records is an arrayref from
                   14840: &Apache::loncommon::upfile_record_sep
                   14841: 
                   14842: =cut
                   14843: 
1.144     matthew  14844: ######################################################
                   14845: ######################################################
1.31      albertel 14846: sub csv_print_samples {
                   14847:     my ($r,$records) = @_;
1.662     bisitz   14848:     my $samples = &get_samples($records,5);
1.301     albertel 14849: 
1.594     raeburn  14850:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14851:               &start_data_table_header_row());
1.356     albertel 14852:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14853:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14854:     $r->print(&end_data_table_header_row());
1.301     albertel 14855:     foreach my $hash (@$samples) {
1.594     raeburn  14856: 	$r->print(&start_data_table_row());
1.356     albertel 14857: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14858: 	    $r->print('<td>');
1.356     albertel 14859: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14860: 	    $r->print('</td>');
                   14861: 	}
1.594     raeburn  14862: 	$r->print(&end_data_table_row());
1.31      albertel 14863:     }
1.594     raeburn  14864:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14865: }
                   14866: 
1.144     matthew  14867: ######################################################
                   14868: ######################################################
                   14869: 
1.56      matthew  14870: =pod
                   14871: 
1.648     raeburn  14872: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14873: 
                   14874: Prints a table to create associations between values and table columns.
1.144     matthew  14875: 
1.41      ng       14876: $r is an Apache Request ref,
                   14877: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14878: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14879: 
                   14880: =cut
                   14881: 
1.144     matthew  14882: ######################################################
                   14883: ######################################################
1.31      albertel 14884: sub csv_print_select_table {
                   14885:     my ($r,$records,$d) = @_;
1.301     albertel 14886:     my $i=0;
                   14887:     my $samples = &get_samples($records,1);
1.144     matthew  14888:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14889: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14890:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14891:               '<th>'.&mt('Column').'</th>'.
                   14892:               &end_data_table_header_row()."\n");
1.356     albertel 14893:     foreach my $array_ref (@$d) {
                   14894: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14895: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14896: 
1.875     bisitz   14897: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14898: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14899: 	$r->print('<option value="none"></option>');
1.356     albertel 14900: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14901: 	    $r->print('<option value="'.$sample.'"'.
                   14902:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14903:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14904: 	}
1.594     raeburn  14905: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14906: 	$i++;
                   14907:     }
1.594     raeburn  14908:     $r->print(&end_data_table());
1.31      albertel 14909:     $i--;
                   14910:     return $i;
                   14911: }
1.56      matthew  14912: 
1.144     matthew  14913: ######################################################
                   14914: ######################################################
                   14915: 
1.56      matthew  14916: =pod
1.31      albertel 14917: 
1.648     raeburn  14918: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14919: 
                   14920: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14921: 
                   14922: $r is an Apache Request ref,
                   14923: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14924: $d is an array of 2 element arrays (internal name, displayed name)
                   14925: 
                   14926: =cut
                   14927: 
1.144     matthew  14928: ######################################################
                   14929: ######################################################
1.31      albertel 14930: sub csv_samples_select_table {
                   14931:     my ($r,$records,$d) = @_;
                   14932:     my $i=0;
1.144     matthew  14933:     #
1.662     bisitz   14934:     my $max_samples = 5;
                   14935:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14936:     $r->print(&start_data_table().
                   14937:               &start_data_table_header_row().'<th>'.
                   14938:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14939:               &end_data_table_header_row());
1.301     albertel 14940: 
                   14941:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14942: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14943: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14944: 	foreach my $option (@$d) {
                   14945: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14946: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14947:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14948:                       $display.'</option>');
1.31      albertel 14949: 	}
                   14950: 	$r->print('</select></td><td>');
1.662     bisitz   14951: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14952: 	    if (defined($samples->[$line]{$key})) { 
                   14953: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14954: 	    }
                   14955: 	}
1.594     raeburn  14956: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14957: 	$i++;
                   14958:     }
1.594     raeburn  14959:     $r->print(&end_data_table());
1.31      albertel 14960:     $i--;
                   14961:     return($i);
1.115     matthew  14962: }
                   14963: 
1.144     matthew  14964: ######################################################
                   14965: ######################################################
                   14966: 
1.115     matthew  14967: =pod
                   14968: 
1.648     raeburn  14969: =item * &clean_excel_name($name)
1.115     matthew  14970: 
                   14971: Returns a replacement for $name which does not contain any illegal characters.
                   14972: 
                   14973: =cut
                   14974: 
1.144     matthew  14975: ######################################################
                   14976: ######################################################
1.115     matthew  14977: sub clean_excel_name {
                   14978:     my ($name) = @_;
                   14979:     $name =~ s/[:\*\?\/\\]//g;
                   14980:     if (length($name) > 31) {
                   14981:         $name = substr($name,0,31);
                   14982:     }
                   14983:     return $name;
1.25      albertel 14984: }
1.84      albertel 14985: 
1.85      albertel 14986: =pod
                   14987: 
1.648     raeburn  14988: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14989: 
                   14990: Returns either 1 or undef
                   14991: 
                   14992: 1 if the part is to be hidden, undef if it is to be shown
                   14993: 
                   14994: Arguments are:
                   14995: 
                   14996: $id the id of the part to be checked
                   14997: $symb, optional the symb of the resource to check
                   14998: $udom, optional the domain of the user to check for
                   14999: $uname, optional the username of the user to check for
                   15000: 
                   15001: =cut
1.84      albertel 15002: 
                   15003: sub check_if_partid_hidden {
                   15004:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15005:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15006: 					 $symb,$udom,$uname);
1.141     albertel 15007:     my $truth=1;
                   15008:     #if the string starts with !, then the list is the list to show not hide
                   15009:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15010:     my @hiddenlist=split(/,/,$hiddenparts);
                   15011:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15012: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15013:     }
1.141     albertel 15014:     return !$truth;
1.84      albertel 15015: }
1.127     matthew  15016: 
1.138     matthew  15017: 
                   15018: ############################################################
                   15019: ############################################################
                   15020: 
                   15021: =pod
                   15022: 
1.157     matthew  15023: =back 
                   15024: 
1.138     matthew  15025: =head1 cgi-bin script and graphing routines
                   15026: 
1.157     matthew  15027: =over 4
                   15028: 
1.648     raeburn  15029: =item * &get_cgi_id()
1.138     matthew  15030: 
                   15031: Inputs: none
                   15032: 
                   15033: Returns an id which can be used to pass environment variables
                   15034: to various cgi-bin scripts.  These environment variables will
                   15035: be removed from the users environment after a given time by
                   15036: the routine &Apache::lonnet::transfer_profile_to_env.
                   15037: 
                   15038: =cut
                   15039: 
                   15040: ############################################################
                   15041: ############################################################
1.152     albertel 15042: my $uniq=0;
1.136     matthew  15043: sub get_cgi_id {
1.154     albertel 15044:     $uniq=($uniq+1)%100000;
1.280     albertel 15045:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15046: }
                   15047: 
1.127     matthew  15048: ############################################################
                   15049: ############################################################
                   15050: 
                   15051: =pod
                   15052: 
1.648     raeburn  15053: =item * &DrawBarGraph()
1.127     matthew  15054: 
1.138     matthew  15055: Facilitates the plotting of data in a (stacked) bar graph.
                   15056: Puts plot definition data into the users environment in order for 
                   15057: graph.png to plot it.  Returns an <img> tag for the plot.
                   15058: The bars on the plot are labeled '1','2',...,'n'.
                   15059: 
                   15060: Inputs:
                   15061: 
                   15062: =over 4
                   15063: 
                   15064: =item $Title: string, the title of the plot
                   15065: 
                   15066: =item $xlabel: string, text describing the X-axis of the plot
                   15067: 
                   15068: =item $ylabel: string, text describing the Y-axis of the plot
                   15069: 
                   15070: =item $Max: scalar, the maximum Y value to use in the plot
                   15071: If $Max is < any data point, the graph will not be rendered.
                   15072: 
1.140     matthew  15073: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15074: they are plotted.  If undefined, default values will be used.
                   15075: 
1.178     matthew  15076: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15077: 
1.138     matthew  15078: =item @Values: An array of array references.  Each array reference holds data
                   15079: to be plotted in a stacked bar chart.
                   15080: 
1.239     matthew  15081: =item If the final element of @Values is a hash reference the key/value
                   15082: pairs will be added to the graph definition.
                   15083: 
1.138     matthew  15084: =back
                   15085: 
                   15086: Returns:
                   15087: 
                   15088: An <img> tag which references graph.png and the appropriate identifying
                   15089: information for the plot.
                   15090: 
1.127     matthew  15091: =cut
                   15092: 
                   15093: ############################################################
                   15094: ############################################################
1.134     matthew  15095: sub DrawBarGraph {
1.178     matthew  15096:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15097:     #
                   15098:     if (! defined($colors)) {
                   15099:         $colors = ['#33ff00', 
                   15100:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15101:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15102:                   ]; 
                   15103:     }
1.228     matthew  15104:     my $extra_settings = {};
                   15105:     if (ref($Values[-1]) eq 'HASH') {
                   15106:         $extra_settings = pop(@Values);
                   15107:     }
1.127     matthew  15108:     #
1.136     matthew  15109:     my $identifier = &get_cgi_id();
                   15110:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15111:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15112:         return '';
                   15113:     }
1.225     matthew  15114:     #
                   15115:     my @Labels;
                   15116:     if (defined($labels)) {
                   15117:         @Labels = @$labels;
                   15118:     } else {
                   15119:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  15120:             push(@Labels,$i+1);
1.225     matthew  15121:         }
                   15122:     }
                   15123:     #
1.129     matthew  15124:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15125:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15126:     my %ValuesHash;
                   15127:     my $NumSets=1;
                   15128:     foreach my $array (@Values) {
                   15129:         next if (! ref($array));
1.136     matthew  15130:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15131:             join(',',@$array);
1.129     matthew  15132:     }
1.127     matthew  15133:     #
1.136     matthew  15134:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15135:     if ($NumBars < 3) {
                   15136:         $width = 120+$NumBars*32;
1.220     matthew  15137:         $xskip = 1;
1.225     matthew  15138:         $bar_width = 30;
                   15139:     } elsif ($NumBars < 5) {
                   15140:         $width = 120+$NumBars*20;
                   15141:         $xskip = 1;
                   15142:         $bar_width = 20;
1.220     matthew  15143:     } elsif ($NumBars < 10) {
1.136     matthew  15144:         $width = 120+$NumBars*15;
                   15145:         $xskip = 1;
                   15146:         $bar_width = 15;
                   15147:     } elsif ($NumBars <= 25) {
                   15148:         $width = 120+$NumBars*11;
                   15149:         $xskip = 5;
                   15150:         $bar_width = 8;
                   15151:     } elsif ($NumBars <= 50) {
                   15152:         $width = 120+$NumBars*8;
                   15153:         $xskip = 5;
                   15154:         $bar_width = 4;
                   15155:     } else {
                   15156:         $width = 120+$NumBars*8;
                   15157:         $xskip = 5;
                   15158:         $bar_width = 4;
                   15159:     }
                   15160:     #
1.137     matthew  15161:     $Max = 1 if ($Max < 1);
                   15162:     if ( int($Max) < $Max ) {
                   15163:         $Max++;
                   15164:         $Max = int($Max);
                   15165:     }
1.127     matthew  15166:     $Title  = '' if (! defined($Title));
                   15167:     $xlabel = '' if (! defined($xlabel));
                   15168:     $ylabel = '' if (! defined($ylabel));
1.369     www      15169:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15170:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15171:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15172:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15173:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15174:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15175:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15176:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15177:     $ValuesHash{$id.'.height'}   = $height;
                   15178:     $ValuesHash{$id.'.width'}    = $width;
                   15179:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15180:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15181:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15182:     #
1.228     matthew  15183:     # Deal with other parameters
                   15184:     while (my ($key,$value) = each(%$extra_settings)) {
                   15185:         $ValuesHash{$id.'.'.$key} = $value;
                   15186:     }
                   15187:     #
1.646     raeburn  15188:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15189:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15190: }
                   15191: 
                   15192: ############################################################
                   15193: ############################################################
                   15194: 
                   15195: =pod
                   15196: 
1.648     raeburn  15197: =item * &DrawXYGraph()
1.137     matthew  15198: 
1.138     matthew  15199: Facilitates the plotting of data in an XY graph.
                   15200: Puts plot definition data into the users environment in order for 
                   15201: graph.png to plot it.  Returns an <img> tag for the plot.
                   15202: 
                   15203: Inputs:
                   15204: 
                   15205: =over 4
                   15206: 
                   15207: =item $Title: string, the title of the plot
                   15208: 
                   15209: =item $xlabel: string, text describing the X-axis of the plot
                   15210: 
                   15211: =item $ylabel: string, text describing the Y-axis of the plot
                   15212: 
                   15213: =item $Max: scalar, the maximum Y value to use in the plot
                   15214: If $Max is < any data point, the graph will not be rendered.
                   15215: 
                   15216: =item $colors: Array ref containing the hex color codes for the data to be 
                   15217: plotted in.  If undefined, default values will be used.
                   15218: 
                   15219: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15220: 
                   15221: =item $Ydata: Array ref containing Array refs.  
1.185     www      15222: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15223: 
                   15224: =item %Values: hash indicating or overriding any default values which are 
                   15225: passed to graph.png.  
                   15226: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15227: 
                   15228: =back
                   15229: 
                   15230: Returns:
                   15231: 
                   15232: An <img> tag which references graph.png and the appropriate identifying
                   15233: information for the plot.
                   15234: 
1.137     matthew  15235: =cut
                   15236: 
                   15237: ############################################################
                   15238: ############################################################
                   15239: sub DrawXYGraph {
                   15240:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15241:     #
                   15242:     # Create the identifier for the graph
                   15243:     my $identifier = &get_cgi_id();
                   15244:     my $id = 'cgi.'.$identifier;
                   15245:     #
                   15246:     $Title  = '' if (! defined($Title));
                   15247:     $xlabel = '' if (! defined($xlabel));
                   15248:     $ylabel = '' if (! defined($ylabel));
                   15249:     my %ValuesHash = 
                   15250:         (
1.369     www      15251:          $id.'.title'  => &escape($Title),
                   15252:          $id.'.xlabel' => &escape($xlabel),
                   15253:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15254:          $id.'.y_max_value'=> $Max,
                   15255:          $id.'.labels'     => join(',',@$Xlabels),
                   15256:          $id.'.PlotType'   => 'XY',
                   15257:          );
                   15258:     #
                   15259:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15260:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15261:     }
                   15262:     #
                   15263:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15264:         return '';
                   15265:     }
                   15266:     my $NumSets=1;
1.138     matthew  15267:     foreach my $array (@{$Ydata}){
1.137     matthew  15268:         next if (! ref($array));
                   15269:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15270:     }
1.138     matthew  15271:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15272:     #
                   15273:     # Deal with other parameters
                   15274:     while (my ($key,$value) = each(%Values)) {
                   15275:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15276:     }
                   15277:     #
1.646     raeburn  15278:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15279:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15280: }
                   15281: 
                   15282: ############################################################
                   15283: ############################################################
                   15284: 
                   15285: =pod
                   15286: 
1.648     raeburn  15287: =item * &DrawXYYGraph()
1.138     matthew  15288: 
                   15289: Facilitates the plotting of data in an XY graph with two Y axes.
                   15290: Puts plot definition data into the users environment in order for 
                   15291: graph.png to plot it.  Returns an <img> tag for the plot.
                   15292: 
                   15293: Inputs:
                   15294: 
                   15295: =over 4
                   15296: 
                   15297: =item $Title: string, the title of the plot
                   15298: 
                   15299: =item $xlabel: string, text describing the X-axis of the plot
                   15300: 
                   15301: =item $ylabel: string, text describing the Y-axis of the plot
                   15302: 
                   15303: =item $colors: Array ref containing the hex color codes for the data to be 
                   15304: plotted in.  If undefined, default values will be used.
                   15305: 
                   15306: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15307: 
                   15308: =item $Ydata1: The first data set
                   15309: 
                   15310: =item $Min1: The minimum value of the left Y-axis
                   15311: 
                   15312: =item $Max1: The maximum value of the left Y-axis
                   15313: 
                   15314: =item $Ydata2: The second data set
                   15315: 
                   15316: =item $Min2: The minimum value of the right Y-axis
                   15317: 
                   15318: =item $Max2: The maximum value of the left Y-axis
                   15319: 
                   15320: =item %Values: hash indicating or overriding any default values which are 
                   15321: passed to graph.png.  
                   15322: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15323: 
                   15324: =back
                   15325: 
                   15326: Returns:
                   15327: 
                   15328: An <img> tag which references graph.png and the appropriate identifying
                   15329: information for the plot.
1.136     matthew  15330: 
                   15331: =cut
                   15332: 
                   15333: ############################################################
                   15334: ############################################################
1.137     matthew  15335: sub DrawXYYGraph {
                   15336:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15337:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15338:     #
                   15339:     # Create the identifier for the graph
                   15340:     my $identifier = &get_cgi_id();
                   15341:     my $id = 'cgi.'.$identifier;
                   15342:     #
                   15343:     $Title  = '' if (! defined($Title));
                   15344:     $xlabel = '' if (! defined($xlabel));
                   15345:     $ylabel = '' if (! defined($ylabel));
                   15346:     my %ValuesHash = 
                   15347:         (
1.369     www      15348:          $id.'.title'  => &escape($Title),
                   15349:          $id.'.xlabel' => &escape($xlabel),
                   15350:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15351:          $id.'.labels' => join(',',@$Xlabels),
                   15352:          $id.'.PlotType' => 'XY',
                   15353:          $id.'.NumSets' => 2,
1.137     matthew  15354:          $id.'.two_axes' => 1,
                   15355:          $id.'.y1_max_value' => $Max1,
                   15356:          $id.'.y1_min_value' => $Min1,
                   15357:          $id.'.y2_max_value' => $Max2,
                   15358:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15359:          );
                   15360:     #
1.137     matthew  15361:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15362:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15363:     }
                   15364:     #
                   15365:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15366:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15367:         return '';
                   15368:     }
                   15369:     my $NumSets=1;
1.137     matthew  15370:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15371:         next if (! ref($array));
                   15372:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15373:     }
                   15374:     #
                   15375:     # Deal with other parameters
                   15376:     while (my ($key,$value) = each(%Values)) {
                   15377:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15378:     }
                   15379:     #
1.646     raeburn  15380:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15381:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15382: }
                   15383: 
                   15384: ############################################################
                   15385: ############################################################
                   15386: 
                   15387: =pod
                   15388: 
1.157     matthew  15389: =back 
                   15390: 
1.139     matthew  15391: =head1 Statistics helper routines?  
                   15392: 
                   15393: Bad place for them but what the hell.
                   15394: 
1.157     matthew  15395: =over 4
                   15396: 
1.648     raeburn  15397: =item * &chartlink()
1.139     matthew  15398: 
                   15399: Returns a link to the chart for a specific student.  
                   15400: 
                   15401: Inputs:
                   15402: 
                   15403: =over 4
                   15404: 
                   15405: =item $linktext: The text of the link
                   15406: 
                   15407: =item $sname: The students username
                   15408: 
                   15409: =item $sdomain: The students domain
                   15410: 
                   15411: =back
                   15412: 
1.157     matthew  15413: =back
                   15414: 
1.139     matthew  15415: =cut
                   15416: 
                   15417: ############################################################
                   15418: ############################################################
                   15419: sub chartlink {
                   15420:     my ($linktext, $sname, $sdomain) = @_;
                   15421:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15422:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15423:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15424:        '">'.$linktext.'</a>';
1.153     matthew  15425: }
                   15426: 
                   15427: #######################################################
                   15428: #######################################################
                   15429: 
                   15430: =pod
                   15431: 
                   15432: =head1 Course Environment Routines
1.157     matthew  15433: 
                   15434: =over 4
1.153     matthew  15435: 
1.648     raeburn  15436: =item * &restore_course_settings()
1.153     matthew  15437: 
1.648     raeburn  15438: =item * &store_course_settings()
1.153     matthew  15439: 
                   15440: Restores/Store indicated form parameters from the course environment.
                   15441: Will not overwrite existing values of the form parameters.
                   15442: 
                   15443: Inputs: 
                   15444: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15445: 
                   15446: a hash ref describing the data to be stored.  For example:
                   15447:    
                   15448: %Save_Parameters = ('Status' => 'scalar',
                   15449:     'chartoutputmode' => 'scalar',
                   15450:     'chartoutputdata' => 'scalar',
                   15451:     'Section' => 'array',
1.373     raeburn  15452:     'Group' => 'array',
1.153     matthew  15453:     'StudentData' => 'array',
                   15454:     'Maps' => 'array');
                   15455: 
                   15456: Returns: both routines return nothing
                   15457: 
1.631     raeburn  15458: =back
                   15459: 
1.153     matthew  15460: =cut
                   15461: 
                   15462: #######################################################
                   15463: #######################################################
                   15464: sub store_course_settings {
1.496     albertel 15465:     return &store_settings($env{'request.course.id'},@_);
                   15466: }
                   15467: 
                   15468: sub store_settings {
1.153     matthew  15469:     # save to the environment
                   15470:     # appenv the same items, just to be safe
1.300     albertel 15471:     my $udom  = $env{'user.domain'};
                   15472:     my $uname = $env{'user.name'};
1.496     albertel 15473:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15474:     my %SaveHash;
                   15475:     my %AppHash;
                   15476:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15477:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15478:         my $envname = 'environment.'.$basename;
1.258     albertel 15479:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15480:             # Save this value away
                   15481:             if ($type eq 'scalar' &&
1.258     albertel 15482:                 (! exists($env{$envname}) || 
                   15483:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15484:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15485:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15486:             } elsif ($type eq 'array') {
                   15487:                 my $stored_form;
1.258     albertel 15488:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15489:                     $stored_form = join(',',
                   15490:                                         map {
1.369     www      15491:                                             &escape($_);
1.258     albertel 15492:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15493:                 } else {
                   15494:                     $stored_form = 
1.369     www      15495:                         &escape($env{'form.'.$setting});
1.153     matthew  15496:                 }
                   15497:                 # Determine if the array contents are the same.
1.258     albertel 15498:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15499:                     $SaveHash{$basename} = $stored_form;
                   15500:                     $AppHash{$envname}   = $stored_form;
                   15501:                 }
                   15502:             }
                   15503:         }
                   15504:     }
                   15505:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15506:                                           $udom,$uname);
1.153     matthew  15507:     if ($put_result !~ /^(ok|delayed)/) {
                   15508:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15509:                                  'got error:'.$put_result);
                   15510:     }
                   15511:     # Make sure these settings stick around in this session, too
1.646     raeburn  15512:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15513:     return;
                   15514: }
                   15515: 
                   15516: sub restore_course_settings {
1.499     albertel 15517:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15518: }
                   15519: 
                   15520: sub restore_settings {
                   15521:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15522:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15523:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15524:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15525:             '.'.$setting;
1.258     albertel 15526:         if (exists($env{$envname})) {
1.153     matthew  15527:             if ($type eq 'scalar') {
1.258     albertel 15528:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15529:             } elsif ($type eq 'array') {
1.258     albertel 15530:                 $env{'form.'.$setting} = [ 
1.153     matthew  15531:                                            map { 
1.369     www      15532:                                                &unescape($_); 
1.258     albertel 15533:                                            } split(',',$env{$envname})
1.153     matthew  15534:                                            ];
                   15535:             }
                   15536:         }
                   15537:     }
1.127     matthew  15538: }
                   15539: 
1.618     raeburn  15540: #######################################################
                   15541: #######################################################
                   15542: 
                   15543: =pod
                   15544: 
                   15545: =head1 Domain E-mail Routines  
                   15546: 
                   15547: =over 4
                   15548: 
1.648     raeburn  15549: =item * &build_recipient_list()
1.618     raeburn  15550: 
1.1075.2.44  raeburn  15551: Build recipient lists for following types of e-mail:
1.766     raeburn  15552: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15553: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15554: module change checking, student/employee ID conflict checks, as
                   15555: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15556: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15557: 
                   15558: Inputs:
1.1075.2.44  raeburn  15559: defmail (scalar - email address of default recipient),
                   15560: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15561: requestsmail, updatesmail, or idconflictsmail).
                   15562: 
1.619     raeburn  15563: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15564: 
                   15565: origmail (scalar - email address of recipient from loncapa.conf,
                   15566: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15567: 
1.1075.2.139  raeburn  15568: $requname username of requester (if mailing type is helpdeskmail)
                   15569: 
                   15570: $requdom domain of requester (if mailing type is helpdeskmail)
                   15571: 
                   15572: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15573: 
1.655     raeburn  15574: Returns: comma separated list of addresses to which to send e-mail.
                   15575: 
                   15576: =back
1.618     raeburn  15577: 
                   15578: =cut
                   15579: 
                   15580: ############################################################
                   15581: ############################################################
                   15582: sub build_recipient_list {
1.1075.2.139  raeburn  15583:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15584:     my @recipients;
1.1075.2.122  raeburn  15585:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15586:     my %domconfig =
1.1075.2.122  raeburn  15587:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15588:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15589:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15590:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15591:                 my @contacts = ('adminemail','supportemail');
                   15592:                 foreach my $item (@contacts) {
                   15593:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15594:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15595:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15596:                             push(@recipients,$addr);
                   15597:                         }
1.619     raeburn  15598:                     }
1.1075.2.122  raeburn  15599:                 }
                   15600:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15601:                 if ($mailing eq 'helpdeskmail') {
                   15602:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15603:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15604:                         my @ok_bccs;
                   15605:                         foreach my $bcc (@bccs) {
                   15606:                             $bcc =~ s/^\s+//g;
                   15607:                             $bcc =~ s/\s+$//g;
                   15608:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15609:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15610:                                     push(@ok_bccs,$bcc);
                   15611:                                 }
                   15612:                             }
                   15613:                         }
                   15614:                         if (@ok_bccs > 0) {
                   15615:                             $allbcc = join(', ',@ok_bccs);
                   15616:                         }
                   15617:                     }
                   15618:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15619:                 }
                   15620:             }
1.766     raeburn  15621:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15622:             $lastresort = $origmail;
1.618     raeburn  15623:         }
1.1075.2.139  raeburn  15624:         if ($mailing eq 'helpdeskmail') {
                   15625:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15626:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15627:                 my ($inststatus,$inststatus_checked);
                   15628:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15629:                     ($env{'user.domain'} ne 'public')) {
                   15630:                     $inststatus_checked = 1;
                   15631:                     $inststatus = $env{'environment.inststatus'};
                   15632:                 }
                   15633:                 unless ($inststatus_checked) {
                   15634:                     if (($requname ne '') && ($requdom ne '')) {
                   15635:                         if (($requname =~ /^$match_username$/) &&
                   15636:                             ($requdom =~ /^$match_domain$/) &&
                   15637:                             (&Apache::lonnet::domain($requdom))) {
                   15638:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15639:                                                                       $requdom);
                   15640:                             unless ($requhome eq 'no_host') {
                   15641:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15642:                                 $inststatus = $userenv{'inststatus'};
                   15643:                                 $inststatus_checked = 1;
                   15644:                             }
                   15645:                         }
                   15646:                     }
                   15647:                 }
                   15648:                 unless ($inststatus_checked) {
                   15649:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15650:                         my %srch = (srchby     => 'email',
                   15651:                                     srchdomain => $defdom,
                   15652:                                     srchterm   => $reqemail,
                   15653:                                     srchtype   => 'exact');
                   15654:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15655:                         foreach my $uname (keys(%srch_results)) {
                   15656:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15657:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15658:                                 $inststatus_checked = 1;
                   15659:                                 last;
                   15660:                             }
                   15661:                         }
                   15662:                         unless ($inststatus_checked) {
                   15663:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15664:                             if ($dirsrchres eq 'ok') {
                   15665:                                 foreach my $uname (keys(%srch_results)) {
                   15666:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15667:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15668:                                         $inststatus_checked = 1;
                   15669:                                         last;
                   15670:                                     }
                   15671:                                 }
                   15672:                             }
                   15673:                         }
                   15674:                     }
                   15675:                 }
                   15676:                 if ($inststatus ne '') {
                   15677:                     foreach my $status (split(/\:/,$inststatus)) {
                   15678:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15679:                             my @contacts = ('adminemail','supportemail');
                   15680:                             foreach my $item (@contacts) {
                   15681:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15682:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15683:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15684:                                         push(@recipients,$addr);
                   15685:                                     }
                   15686:                                 }
                   15687:                             }
                   15688:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15689:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15690:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15691:                                 my @ok_bccs;
                   15692:                                 foreach my $bcc (@bccs) {
                   15693:                                     $bcc =~ s/^\s+//g;
                   15694:                                     $bcc =~ s/\s+$//g;
                   15695:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15696:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15697:                                             push(@ok_bccs,$bcc);
                   15698:                                         }
                   15699:                                     }
                   15700:                                 }
                   15701:                                 if (@ok_bccs > 0) {
                   15702:                                     $allbcc = join(', ',@ok_bccs);
                   15703:                                 }
                   15704:                             }
                   15705:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15706:                             last;
                   15707:                         }
                   15708:                     }
                   15709:                 }
                   15710:             }
                   15711:         }
1.619     raeburn  15712:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15713:         $lastresort = $origmail;
                   15714:     }
1.1075.2.128  raeburn  15715:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15716:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15717:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15718:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15719:             my %what = (
                   15720:                           perlvar => 1,
                   15721:                        );
                   15722:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15723:             if ($primary) {
                   15724:                 my $gotaddr;
                   15725:                 my ($result,$returnhash) =
                   15726:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15727:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15728:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15729:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15730:                         $gotaddr = 1;
                   15731:                     }
                   15732:                 }
                   15733:                 unless ($gotaddr) {
                   15734:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15735:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15736:                     unless ($uintdom eq $intdom) {
                   15737:                         my %domconfig =
                   15738:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15739:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15740:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15741:                                 my @contacts = ('adminemail','supportemail');
                   15742:                                 foreach my $item (@contacts) {
                   15743:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15744:                                         my $addr = $domconfig{'contacts'}{$item};
                   15745:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15746:                                             push(@recipients,$addr);
                   15747:                                         }
                   15748:                                     }
                   15749:                                 }
                   15750:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15751:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15752:                                 }
                   15753:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15754:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15755:                                     my @ok_bccs;
                   15756:                                     foreach my $bcc (@bccs) {
                   15757:                                         $bcc =~ s/^\s+//g;
                   15758:                                         $bcc =~ s/\s+$//g;
                   15759:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15760:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15761:                                                 push(@ok_bccs,$bcc);
                   15762:                                             }
                   15763:                                         }
                   15764:                                     }
                   15765:                                     if (@ok_bccs > 0) {
                   15766:                                         $allbcc = join(', ',@ok_bccs);
                   15767:                                     }
                   15768:                                 }
                   15769:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15770:                             }
                   15771:                         }
                   15772:                     }
                   15773:                 }
                   15774:             }
                   15775:         }
1.618     raeburn  15776:     }
1.688     raeburn  15777:     if (defined($defmail)) {
                   15778:         if ($defmail ne '') {
                   15779:             push(@recipients,$defmail);
                   15780:         }
1.618     raeburn  15781:     }
                   15782:     if ($otheremails) {
1.619     raeburn  15783:         my @others;
                   15784:         if ($otheremails =~ /,/) {
                   15785:             @others = split(/,/,$otheremails);
1.618     raeburn  15786:         } else {
1.619     raeburn  15787:             push(@others,$otheremails);
                   15788:         }
                   15789:         foreach my $addr (@others) {
                   15790:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15791:                 push(@recipients,$addr);
                   15792:             }
1.618     raeburn  15793:         }
                   15794:     }
1.1075.2.128  raeburn  15795:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15796:         if ((!@recipients) && ($lastresort ne '')) {
                   15797:             push(@recipients,$lastresort);
                   15798:         }
                   15799:     } elsif ($lastresort ne '') {
                   15800:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15801:             push(@recipients,$lastresort);
                   15802:         }
                   15803:     }
                   15804:     my $recipientlist = join(',',@recipients);
                   15805:     if (wantarray) {
                   15806:         return ($recipientlist,$allbcc,$addtext);
                   15807:     } else {
                   15808:         return $recipientlist;
                   15809:     }
1.618     raeburn  15810: }
                   15811: 
1.127     matthew  15812: ############################################################
                   15813: ############################################################
1.154     albertel 15814: 
1.655     raeburn  15815: =pod
                   15816: 
                   15817: =head1 Course Catalog Routines
                   15818: 
                   15819: =over 4
                   15820: 
                   15821: =item * &gather_categories()
                   15822: 
                   15823: Converts category definitions - keys of categories hash stored in  
                   15824: coursecategories in configuration.db on the primary library server in a 
                   15825: domain - to an array.  Also generates javascript and idx hash used to 
                   15826: generate Domain Coordinator interface for editing Course Categories.
                   15827: 
                   15828: Inputs:
1.663     raeburn  15829: 
1.655     raeburn  15830: categories (reference to hash of category definitions).
1.663     raeburn  15831: 
1.655     raeburn  15832: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15833:       categories and subcategories).
1.663     raeburn  15834: 
1.655     raeburn  15835: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15836:       editing Course Categories).
1.663     raeburn  15837: 
1.655     raeburn  15838: jsarray (reference to array of categories used to create Javascript arrays for
                   15839:          Domain Coordinator interface for editing Course Categories).
                   15840: 
                   15841: Returns: nothing
                   15842: 
                   15843: Side effects: populates cats, idx and jsarray. 
                   15844: 
                   15845: =cut
                   15846: 
                   15847: sub gather_categories {
                   15848:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15849:     my %counters;
                   15850:     my $num = 0;
                   15851:     foreach my $item (keys(%{$categories})) {
                   15852:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15853:         if ($container eq '' && $depth == 0) {
                   15854:             $cats->[$depth][$categories->{$item}] = $cat;
                   15855:         } else {
                   15856:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15857:         }
                   15858:         my ($escitem,$tail) = split(/:/,$item,2);
                   15859:         if ($counters{$tail} eq '') {
                   15860:             $counters{$tail} = $num;
                   15861:             $num ++;
                   15862:         }
                   15863:         if (ref($idx) eq 'HASH') {
                   15864:             $idx->{$item} = $counters{$tail};
                   15865:         }
                   15866:         if (ref($jsarray) eq 'ARRAY') {
                   15867:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15868:         }
                   15869:     }
                   15870:     return;
                   15871: }
                   15872: 
                   15873: =pod
                   15874: 
                   15875: =item * &extract_categories()
                   15876: 
                   15877: Used to generate breadcrumb trails for course categories.
                   15878: 
                   15879: Inputs:
1.663     raeburn  15880: 
1.655     raeburn  15881: categories (reference to hash of category definitions).
1.663     raeburn  15882: 
1.655     raeburn  15883: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15884:       categories and subcategories).
1.663     raeburn  15885: 
1.655     raeburn  15886: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15887: 
1.655     raeburn  15888: allitems (reference to hash - key is category key 
                   15889:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15890: 
1.655     raeburn  15891: idx (reference to hash of counters used in Domain Coordinator interface for
                   15892:       editing Course Categories).
1.663     raeburn  15893: 
1.655     raeburn  15894: jsarray (reference to array of categories used to create Javascript arrays for
                   15895:          Domain Coordinator interface for editing Course Categories).
                   15896: 
1.665     raeburn  15897: subcats (reference to hash of arrays containing all subcategories within each 
                   15898:          category, -recursive)
                   15899: 
1.1075.2.132  raeburn  15900: maxd (reference to hash used to hold max depth for all top-level categories).
                   15901: 
1.655     raeburn  15902: Returns: nothing
                   15903: 
                   15904: Side effects: populates trails and allitems hash references.
                   15905: 
                   15906: =cut
                   15907: 
                   15908: sub extract_categories {
1.1075.2.132  raeburn  15909:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15910:     if (ref($categories) eq 'HASH') {
                   15911:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15912:         if (ref($cats->[0]) eq 'ARRAY') {
                   15913:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15914:                 my $name = $cats->[0][$i];
                   15915:                 my $item = &escape($name).'::0';
                   15916:                 my $trailstr;
                   15917:                 if ($name eq 'instcode') {
                   15918:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15919:                 } elsif ($name eq 'communities') {
                   15920:                     $trailstr = &mt('Communities');
1.655     raeburn  15921:                 } else {
                   15922:                     $trailstr = $name;
                   15923:                 }
                   15924:                 if ($allitems->{$item} eq '') {
                   15925:                     push(@{$trails},$trailstr);
                   15926:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15927:                 }
                   15928:                 my @parents = ($name);
                   15929:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15930:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15931:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15932:                         if (ref($subcats) eq 'HASH') {
                   15933:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15934:                         }
1.1075.2.132  raeburn  15935:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15936:                     }
                   15937:                 } else {
                   15938:                     if (ref($subcats) eq 'HASH') {
                   15939:                         $subcats->{$item} = [];
1.655     raeburn  15940:                     }
1.1075.2.132  raeburn  15941:                     if (ref($maxd) eq 'HASH') {
                   15942:                         $maxd->{$name} = 1;
                   15943:                     }
1.655     raeburn  15944:                 }
                   15945:             }
                   15946:         }
                   15947:     }
                   15948:     return;
                   15949: }
                   15950: 
                   15951: =pod
                   15952: 
1.1075.2.56  raeburn  15953: =item * &recurse_categories()
1.655     raeburn  15954: 
                   15955: Recursively used to generate breadcrumb trails for course categories.
                   15956: 
                   15957: Inputs:
1.663     raeburn  15958: 
1.655     raeburn  15959: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15960:       categories and subcategories).
1.663     raeburn  15961: 
1.655     raeburn  15962: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15963: 
                   15964: category (current course category, for which breadcrumb trail is being generated).
                   15965: 
                   15966: trails (reference to array of breadcrumb trails for each category).
                   15967: 
1.655     raeburn  15968: allitems (reference to hash - key is category key
                   15969:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15970: 
1.655     raeburn  15971: parents (array containing containers directories for current category, 
                   15972:          back to top level). 
                   15973: 
                   15974: Returns: nothing
                   15975: 
                   15976: Side effects: populates trails and allitems hash references
                   15977: 
                   15978: =cut
                   15979: 
                   15980: sub recurse_categories {
1.1075.2.132  raeburn  15981:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15982:     my $shallower = $depth - 1;
                   15983:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15984:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15985:             my $name = $cats->[$depth]{$category}[$k];
                   15986:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 15987:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15988:             if ($allitems->{$item} eq '') {
                   15989:                 push(@{$trails},$trailstr);
                   15990:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15991:             }
                   15992:             my $deeper = $depth+1;
                   15993:             push(@{$parents},$category);
1.665     raeburn  15994:             if (ref($subcats) eq 'HASH') {
                   15995:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15996:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15997:                     my $higher;
                   15998:                     if ($j > 0) {
                   15999:                         $higher = &escape($parents->[$j]).':'.
                   16000:                                   &escape($parents->[$j-1]).':'.$j;
                   16001:                     } else {
                   16002:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16003:                     }
                   16004:                     push(@{$subcats->{$higher}},$subcat);
                   16005:                 }
                   16006:             }
                   16007:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  16008:                                 $subcats,$maxd);
1.655     raeburn  16009:             pop(@{$parents});
                   16010:         }
                   16011:     } else {
                   16012:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  16013:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16014:         if ($allitems->{$item} eq '') {
                   16015:             push(@{$trails},$trailstr);
                   16016:             $allitems->{$item} = scalar(@{$trails})-1;
                   16017:         }
1.1075.2.132  raeburn  16018:         if (ref($maxd) eq 'HASH') {
                   16019:             if ($depth > $maxd->{$parents->[0]}) {
                   16020:                 $maxd->{$parents->[0]} = $depth;
                   16021:             }
                   16022:         }
1.655     raeburn  16023:     }
                   16024:     return;
                   16025: }
                   16026: 
1.663     raeburn  16027: =pod
                   16028: 
1.1075.2.56  raeburn  16029: =item * &assign_categories_table()
1.663     raeburn  16030: 
                   16031: Create a datatable for display of hierarchical categories in a domain,
                   16032: with checkboxes to allow a course to be categorized. 
                   16033: 
                   16034: Inputs:
                   16035: 
                   16036: cathash - reference to hash of categories defined for the domain (from
                   16037:           configuration.db)
                   16038: 
                   16039: currcat - scalar with an & separated list of categories assigned to a course. 
                   16040: 
1.919     raeburn  16041: type    - scalar contains course type (Course or Community).
                   16042: 
1.1075.2.117  raeburn  16043: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16044:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16045: 
1.663     raeburn  16046: Returns: $output (markup to be displayed) 
                   16047: 
                   16048: =cut
                   16049: 
                   16050: sub assign_categories_table {
1.1075.2.117  raeburn  16051:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16052:     my $output;
                   16053:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  16054:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16055:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16056:         $maxdepth = scalar(@cats);
                   16057:         if (@cats > 0) {
                   16058:             my $itemcount = 0;
                   16059:             if (ref($cats[0]) eq 'ARRAY') {
                   16060:                 my @currcategories;
                   16061:                 if ($currcat ne '') {
                   16062:                     @currcategories = split('&',$currcat);
                   16063:                 }
1.919     raeburn  16064:                 my $table;
1.663     raeburn  16065:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16066:                     my $parent = $cats[0][$i];
1.919     raeburn  16067:                     next if ($parent eq 'instcode');
                   16068:                     if ($type eq 'Community') {
                   16069:                         next unless ($parent eq 'communities');
                   16070:                     } else {
                   16071:                         next if ($parent eq 'communities');
                   16072:                     }
1.663     raeburn  16073:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16074:                     my $item = &escape($parent).'::0';
                   16075:                     my $checked = '';
                   16076:                     if (@currcategories > 0) {
                   16077:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16078:                             $checked = ' checked="checked"';
1.663     raeburn  16079:                         }
                   16080:                     }
1.919     raeburn  16081:                     my $parent_title = $parent;
                   16082:                     if ($parent eq 'communities') {
                   16083:                         $parent_title = &mt('Communities');
                   16084:                     }
                   16085:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16086:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16087:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16088:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16089:                     my $depth = 1;
                   16090:                     push(@path,$parent);
1.1075.2.117  raeburn  16091:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16092:                     pop(@path);
1.919     raeburn  16093:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16094:                     $itemcount ++;
                   16095:                 }
1.919     raeburn  16096:                 if ($itemcount) {
                   16097:                     $output = &Apache::loncommon::start_data_table().
                   16098:                               $table.
                   16099:                               &Apache::loncommon::end_data_table();
                   16100:                 }
1.663     raeburn  16101:             }
                   16102:         }
                   16103:     }
                   16104:     return $output;
                   16105: }
                   16106: 
                   16107: =pod
                   16108: 
1.1075.2.56  raeburn  16109: =item * &assign_category_rows()
1.663     raeburn  16110: 
                   16111: Create a datatable row for display of nested categories in a domain,
                   16112: with checkboxes to allow a course to be categorized,called recursively.
                   16113: 
                   16114: Inputs:
                   16115: 
                   16116: itemcount - track row number for alternating colors
                   16117: 
                   16118: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16119:       categories and subcategories.
                   16120: 
                   16121: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16122: 
                   16123: parent - parent of current category item
                   16124: 
                   16125: path - Array containing all categories back up through the hierarchy from the
                   16126:        current category to the top level.
                   16127: 
                   16128: currcategories - reference to array of current categories assigned to the course
                   16129: 
1.1075.2.117  raeburn  16130: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16131:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16132: 
1.663     raeburn  16133: Returns: $output (markup to be displayed).
                   16134: 
                   16135: =cut
                   16136: 
                   16137: sub assign_category_rows {
1.1075.2.117  raeburn  16138:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16139:     my ($text,$name,$item,$chgstr);
                   16140:     if (ref($cats) eq 'ARRAY') {
                   16141:         my $maxdepth = scalar(@{$cats});
                   16142:         if (ref($cats->[$depth]) eq 'HASH') {
                   16143:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16144:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16145:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  16146:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16147:                 for (my $j=0; $j<$numchildren; $j++) {
                   16148:                     $name = $cats->[$depth]{$parent}[$j];
                   16149:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16150:                     my $deeper = $depth+1;
                   16151:                     my $checked = '';
                   16152:                     if (ref($currcategories) eq 'ARRAY') {
                   16153:                         if (@{$currcategories} > 0) {
                   16154:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16155:                                 $checked = ' checked="checked"';
1.663     raeburn  16156:                             }
                   16157:                         }
                   16158:                     }
1.664     raeburn  16159:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16160:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  16161:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16162:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16163:                              '</td><td>';
1.663     raeburn  16164:                     if (ref($path) eq 'ARRAY') {
                   16165:                         push(@{$path},$name);
1.1075.2.117  raeburn  16166:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16167:                         pop(@{$path});
                   16168:                     }
                   16169:                     $text .= '</td></tr>';
                   16170:                 }
                   16171:                 $text .= '</table></td>';
                   16172:             }
                   16173:         }
                   16174:     }
                   16175:     return $text;
                   16176: }
                   16177: 
1.1075.2.69  raeburn  16178: =pod
                   16179: 
                   16180: =back
                   16181: 
                   16182: =cut
                   16183: 
1.655     raeburn  16184: ############################################################
                   16185: ############################################################
                   16186: 
                   16187: 
1.443     albertel 16188: sub commit_customrole {
1.664     raeburn  16189:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16190:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16191:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16192:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16193:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16194:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16195:                  '</b><br />';
                   16196:     return $output;
                   16197: }
                   16198: 
                   16199: sub commit_standardrole {
1.1075.2.31  raeburn  16200:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16201:     my ($output,$logmsg,$linefeed);
                   16202:     if ($context eq 'auto') {
                   16203:         $linefeed = "\n";
                   16204:     } else {
                   16205:         $linefeed = "<br />\n";
                   16206:     }  
1.443     albertel 16207:     if ($three eq 'st') {
1.541     raeburn  16208:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  16209:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16210:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16211:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16212:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16213:         } else {
1.541     raeburn  16214:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16215:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16216:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16217:             if ($context eq 'auto') {
                   16218:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16219:             } else {
                   16220:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16221:                &mt('Add to classlist').': <b>ok</b>';
                   16222:             }
                   16223:             $output .= $linefeed;
1.443     albertel 16224:         }
                   16225:     } else {
                   16226:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16227:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16228:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16229:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16230:         if ($context eq 'auto') {
                   16231:             $output .= $result.$linefeed;
                   16232:         } else {
                   16233:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16234:         }
1.443     albertel 16235:     }
                   16236:     return $output;
                   16237: }
                   16238: 
                   16239: sub commit_studentrole {
1.1075.2.31  raeburn  16240:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16241:         $credits) = @_;
1.626     raeburn  16242:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16243:     if ($context eq 'auto') {
                   16244:         $linefeed = "\n";
                   16245:     } else {
                   16246:         $linefeed = '<br />'."\n";
                   16247:     }
1.443     albertel 16248:     if (defined($one) && defined($two)) {
                   16249:         my $cid=$one.'_'.$two;
                   16250:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16251:         my $secchange = 0;
                   16252:         my $expire_role_result;
                   16253:         my $modify_section_result;
1.628     raeburn  16254:         if ($oldsec ne '-1') { 
                   16255:             if ($oldsec ne $sec) {
1.443     albertel 16256:                 $secchange = 1;
1.628     raeburn  16257:                 my $now = time;
1.443     albertel 16258:                 my $uurl='/'.$cid;
                   16259:                 $uurl=~s/\_/\//g;
                   16260:                 if ($oldsec) {
                   16261:                     $uurl.='/'.$oldsec;
                   16262:                 }
1.626     raeburn  16263:                 $oldsecurl = $uurl;
1.628     raeburn  16264:                 $expire_role_result = 
1.1075.2.161.  .14(raeb 16265:-23):                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
1.628     raeburn  16266:                 if ($env{'request.course.sec'} ne '') { 
                   16267:                     if ($expire_role_result eq 'refused') {
                   16268:                         my @roles = ('st');
                   16269:                         my @statuses = ('previous');
                   16270:                         my @roledoms = ($one);
                   16271:                         my $withsec = 1;
                   16272:                         my %roleshash = 
                   16273:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16274:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16275:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16276:                             my ($oldstart,$oldend) = 
                   16277:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16278:                             if ($oldend > 0 && $oldend <= $now) {
                   16279:                                 $expire_role_result = 'ok';
                   16280:                             }
                   16281:                         }
                   16282:                     }
                   16283:                 }
1.443     albertel 16284:                 $result = $expire_role_result;
                   16285:             }
                   16286:         }
                   16287:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  16288:             $modify_section_result = 
                   16289:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16290:                                                            undef,undef,undef,$sec,
                   16291:                                                            $end,$start,'','',$cid,
                   16292:                                                            '',$context,$credits);
1.443     albertel 16293:             if ($modify_section_result =~ /^ok/) {
                   16294:                 if ($secchange == 1) {
1.628     raeburn  16295:                     if ($sec eq '') {
                   16296:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16297:                     } else {
                   16298:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16299:                     }
1.443     albertel 16300:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16301:                     if ($sec eq '') {
                   16302:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16303:                     } else {
                   16304:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16305:                     }
1.443     albertel 16306:                 } else {
1.628     raeburn  16307:                     if ($sec eq '') {
                   16308:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16309:                     } else {
                   16310:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16311:                     }
1.443     albertel 16312:                 }
                   16313:             } else {
1.628     raeburn  16314:                 if ($secchange) {       
                   16315:                     $$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;
                   16316:                 } else {
                   16317:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16318:                 }
1.443     albertel 16319:             }
                   16320:             $result = $modify_section_result;
                   16321:         } elsif ($secchange == 1) {
1.628     raeburn  16322:             if ($oldsec eq '') {
1.1075.2.20  raeburn  16323:                 $$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  16324:             } else {
                   16325:                 $$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;
                   16326:             }
1.626     raeburn  16327:             if ($expire_role_result eq 'refused') {
                   16328:                 my $newsecurl = '/'.$cid;
                   16329:                 $newsecurl =~ s/\_/\//g;
                   16330:                 if ($sec ne '') {
                   16331:                     $newsecurl.='/'.$sec;
                   16332:                 }
                   16333:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16334:                     if ($sec eq '') {
                   16335:                         $$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;
                   16336:                     } else {
                   16337:                         $$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;
                   16338:                     }
                   16339:                 }
                   16340:             }
1.443     albertel 16341:         }
                   16342:     } else {
1.626     raeburn  16343:         $$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 16344:         $result = "error: incomplete course id\n";
                   16345:     }
                   16346:     return $result;
                   16347: }
                   16348: 
1.1075.2.25  raeburn  16349: sub show_role_extent {
                   16350:     my ($scope,$context,$role) = @_;
                   16351:     $scope =~ s{^/}{};
                   16352:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16353:     push(@courseroles,'co');
                   16354:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16355:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16356:         $scope =~ s{/}{_};
                   16357:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16358:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16359:         my ($audom,$auname) = split(/\//,$scope);
                   16360:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16361:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16362:     } else {
                   16363:         $scope =~ s{/$}{};
                   16364:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16365:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16366:     }
                   16367: }
                   16368: 
1.443     albertel 16369: ############################################################
                   16370: ############################################################
                   16371: 
1.566     albertel 16372: sub check_clone {
1.578     raeburn  16373:     my ($args,$linefeed) = @_;
1.566     albertel 16374:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16375:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16376:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 16377:21):     my $clonetitle;
                   16378:21):     my @clonemsg;
1.566     albertel 16379:     my $can_clone = 0;
1.944     raeburn  16380:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16381:     if ($lctype ne 'community') {
                   16382:         $lctype = 'course';
                   16383:     }
1.566     albertel 16384:     if ($clonehome eq 'no_host') {
1.944     raeburn  16385:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16386:21):             push(@clonemsg,({
                   16387:21):                               mt => 'No new community created.',
                   16388:21):                               args => [],
                   16389:21):                             },
                   16390:21):                             {
                   16391:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16392:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16393:21):                             }));
1.908     raeburn  16394:         } else {
1.1075.2.161.  .1(raebu 16395:21):             push(@clonemsg,({
                   16396:21):                               mt => 'No new course created.',
                   16397:21):                               args => [],
                   16398:21):                             },
                   16399:21):                             {
                   16400:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16401:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16402:21):                             }));
                   16403:21):         }
1.566     albertel 16404:     } else {
                   16405: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 16406:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16407:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16408:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 16409:21):                 push(@clonemsg,({
                   16410:21):                                   mt => 'No new community created.',
                   16411:21):                                   args => [],
                   16412:21):                                 },
                   16413:21):                                 {
                   16414:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16415:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16416:21):                                 }));
                   16417:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16418:             }
                   16419:         }
1.1075.2.119  raeburn  16420: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16421:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16422: 	    $can_clone = 1;
                   16423: 	} else {
1.1075.2.95  raeburn  16424: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16425: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  16426:             if ($clonehash{'cloners'} eq '') {
                   16427:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16428:                 if ($domdefs{'canclone'}) {
                   16429:                     unless ($domdefs{'canclone'} eq 'none') {
                   16430:                         if ($domdefs{'canclone'} eq 'domain') {
                   16431:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16432:                                 $can_clone = 1;
                   16433:                             }
                   16434:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16435:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16436:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16437:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16438:                                 $can_clone = 1;
                   16439:                             }
                   16440:                         }
                   16441:                     }
1.908     raeburn  16442:                 }
1.1075.2.95  raeburn  16443:             } else {
                   16444: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16445:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16446:                     $can_clone = 1;
1.1075.2.95  raeburn  16447:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16448:                     $can_clone = 1;
1.1075.2.96  raeburn  16449:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16450:                     $can_clone = 1;
1.1075.2.95  raeburn  16451:                 }
                   16452:                 unless ($can_clone) {
1.1075.2.96  raeburn  16453:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   16454:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  16455:                         my (%gotdomdefaults,%gotcodedefaults);
                   16456:                         foreach my $cloner (@cloners) {
                   16457:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16458:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16459:                                 my (%codedefaults,@code_order);
                   16460:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16461:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16462:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16463:                                     }
                   16464:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16465:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16466:                                     }
                   16467:                                 } else {
                   16468:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16469:                                                                             \%codedefaults,
                   16470:                                                                             \@code_order);
                   16471:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16472:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16473:                                 }
                   16474:                                 if (@code_order > 0) {
                   16475:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16476:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16477:                                                                                 $args->{'crscode'})) {
                   16478:                                         $can_clone = 1;
                   16479:                                         last;
                   16480:                                     }
                   16481:                                 }
                   16482:                             }
                   16483:                         }
                   16484:                     }
1.1075.2.96  raeburn  16485:                 }
                   16486:             }
                   16487:             unless ($can_clone) {
                   16488:                 my $ccrole = 'cc';
                   16489:                 if ($args->{'crstype'} eq 'Community') {
                   16490:                     $ccrole = 'co';
                   16491:                 }
                   16492:                 my %roleshash =
                   16493:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16494:                                                   $args->{'ccdomain'},
                   16495:                                                   'userroles',['active'],[$ccrole],
                   16496:                                                   [$args->{'clonedomain'}]);
                   16497:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16498:                     $can_clone = 1;
                   16499:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16500:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16501:                     $can_clone = 1;
1.1075.2.95  raeburn  16502:                 }
                   16503:             }
                   16504:             unless ($can_clone) {
                   16505:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 16506:21):                     push(@clonemsg,({
                   16507:21):                                       mt => 'No new community created.',
                   16508:21):                                       args => [],
                   16509:21):                                     },
                   16510:21):                                     {
                   16511: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]).',
                   16512:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16513:21):                                     }));
1.1075.2.95  raeburn  16514:                 } else {
1.1075.2.161.  .1(raebu 16515:21):                     push(@clonemsg,({
                   16516:21):                                       mt => 'No new course created.',
                   16517:21):                                       args => [],
                   16518:21):                                     },
                   16519:21):                                     {
                   16520: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]).',
                   16521:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16522:21):                                     }));
1.578     raeburn  16523: 	        }
1.566     albertel 16524: 	    }
1.578     raeburn  16525:         }
1.566     albertel 16526:     }
1.1075.2.161.  .1(raebu 16527:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16528: }
                   16529: 
1.444     albertel 16530: sub construct_course {
1.1075.2.119  raeburn  16531:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16532:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16533:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16534:     my $linefeed =  '<br />'."\n";
                   16535:     if ($context eq 'auto') {
                   16536:         $linefeed = "\n";
                   16537:     }
1.566     albertel 16538: 
                   16539: #
                   16540: # Are we cloning?
                   16541: #
1.1075.2.161.  .1(raebu 16542:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16543:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16544:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16545:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16546:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16547: 	}
                   16548:     }
                   16549: 
1.444     albertel 16550: #
                   16551: # Open course
                   16552: #
                   16553:     my $crstype = lc($args->{'crstype'});
                   16554:     my %cenv=();
                   16555:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16556:                                              $args->{'cdescr'},
                   16557:                                              $args->{'curl'},
                   16558:                                              $args->{'course_home'},
                   16559:                                              $args->{'nonstandard'},
                   16560:                                              $args->{'crscode'},
                   16561:                                              $args->{'ccuname'}.':'.
                   16562:                                              $args->{'ccdomain'},
1.882     raeburn  16563:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16564:21):                                              $cnum,$context,$category,
                   16565:21):                                              $callercontext);
1.444     albertel 16566: 
                   16567:     # Note: The testing routines depend on this being output; see 
                   16568:     # Utils::Course. This needs to at least be output as a comment
                   16569:     # if anyone ever decides to not show this, and Utils::Course::new
                   16570:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16571:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16572:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16573:21):     } else {
                   16574:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16575:21):     }
1.943     raeburn  16576:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16577:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16578:     }
                   16579: 
1.444     albertel 16580: #
                   16581: # Check if created correctly
                   16582: #
1.479     albertel 16583:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16584:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16585:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16586:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16587:21):             $outcome .= &mt_user($user_lh,
                   16588:21):                             'Course creation failed, unrecognized course home server.');
                   16589:21):         } else {
                   16590:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16591:21):         }
                   16592:21):         $outcome .= $linefeed;
                   16593:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16594:     }
1.541     raeburn  16595:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16596: 
1.444     albertel 16597: #
1.566     albertel 16598: # Do the cloning
1.1075.2.161.  .1(raebu 16599:21): #
                   16600:21):     my @clonemsg;
1.566     albertel 16601:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16602:21):         push(@clonemsg,
                   16603:21):                       {
                   16604:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16605:21):                           args => [$crstype,$clonetitle],
                   16606:21):                       });
1.566     albertel 16607: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16608: # Copy all files
1.1075.2.161.  .1(raebu 16609:21):         my @info =
                   16610:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16611:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16612:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16613:21):                                                      $args->{'tinyurls'});
                   16614:21):         if (@info) {
                   16615:21):             push(@clonemsg,@info);
                   16616:21):         }
1.444     albertel 16617: # Restore URL
1.566     albertel 16618: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16619: # Restore title
1.566     albertel 16620: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16621: # Restore creation date, creator and creation context.
                   16622:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16623:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16624:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16625: # Mark as cloned
1.566     albertel 16626: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16627: # Need to clone grading mode
                   16628:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16629:         $cenv{'grading'}=$newenv{'grading'};
                   16630: # Do not clone these environment entries
                   16631:         &Apache::lonnet::del('environment',
                   16632:                   ['default_enrollment_start_date',
                   16633:                    'default_enrollment_end_date',
                   16634:                    'question.email',
                   16635:                    'policy.email',
                   16636:                    'comment.email',
                   16637:                    'pch.users.denied',
1.725     raeburn  16638:                    'plc.users.denied',
                   16639:                    'hidefromcat',
1.1075.2.36  raeburn  16640:                    'checkforpriv',
1.1075.2.158  raeburn  16641:                    'categories'],
1.638     www      16642:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16643:         if ($args->{'textbook'}) {
                   16644:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16645:         }
1.444     albertel 16646:     }
1.566     albertel 16647: 
1.444     albertel 16648: #
                   16649: # Set environment (will override cloned, if existing)
                   16650: #
                   16651:     my @sections = ();
                   16652:     my @xlists = ();
                   16653:     if ($args->{'crstype'}) {
                   16654:         $cenv{'type'}=$args->{'crstype'};
                   16655:     }
1.1075.2.161.  .17(raeb 16656:-23):     if ($args->{'lti'}) {
                   16657:-23):         $cenv{'internal.lti'}=$args->{'lti'};
                   16658:-23):     }
1.444     albertel 16659:     if ($args->{'crsid'}) {
                   16660:         $cenv{'courseid'}=$args->{'crsid'};
                   16661:     }
                   16662:     if ($args->{'crscode'}) {
                   16663:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16664:     }
                   16665:     if ($args->{'crsquota'} ne '') {
                   16666:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16667:     } else {
                   16668:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16669:     }
                   16670:     if ($args->{'ccuname'}) {
                   16671:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16672:                                         ':'.$args->{'ccdomain'};
                   16673:     } else {
                   16674:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16675:     }
1.1075.2.31  raeburn  16676:     if ($args->{'defaultcredits'}) {
                   16677:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16678:     }
1.444     albertel 16679:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1075.2.161.  .20(raeb 16680:-23):     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 16681:     if ($args->{'crssections'}) {
                   16682:         $cenv{'internal.sectionnums'} = '';
                   16683:         if ($args->{'crssections'} =~ m/,/) {
                   16684:             @sections = split/,/,$args->{'crssections'};
                   16685:         } else {
                   16686:             $sections[0] = $args->{'crssections'};
                   16687:         }
                   16688:         if (@sections > 0) {
                   16689:             foreach my $item (@sections) {
                   16690:                 my ($sec,$gp) = split/:/,$item;
                   16691:                 my $class = $args->{'crscode'}.$sec;
                   16692:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16693:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1075.2.161.  .20(raeb 16694:-23):                 if ($addcheck eq 'ok') {
                   16695:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16696:-23):                         push(@oklcsecs,$gp);
                   16697:-23):                     }
                   16698:-23):                 } else {
1.1075.2.119  raeburn  16699:                     push(@badclasses,$class);
1.444     albertel 16700:                 }
                   16701:             }
                   16702:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16703:         }
                   16704:     }
                   16705: # do not hide course coordinator from staff listing, 
                   16706: # even if privileged
                   16707:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16708: # add course coordinator's domain to domains to check for privileged users
                   16709: # if different to course domain
                   16710:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16711:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16712:     }
1.444     albertel 16713: # add crosslistings
                   16714:     if ($args->{'crsxlist'}) {
                   16715:         $cenv{'internal.crosslistings'}='';
                   16716:         if ($args->{'crsxlist'} =~ m/,/) {
                   16717:             @xlists = split/,/,$args->{'crsxlist'};
                   16718:         } else {
                   16719:             $xlists[0] = $args->{'crsxlist'};
                   16720:         }
                   16721:         if (@xlists > 0) {
                   16722:             foreach my $item (@xlists) {
                   16723:                 my ($xl,$gp) = split/:/,$item;
                   16724:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16725:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1075.2.161.  .20(raeb 16726:-23):                 if ($addcheck eq 'ok') {
                   16727:-23):                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   16728:-23):                         push(@oklcsecs,$gp);
                   16729:-23):                     }
                   16730:-23):                 } else {
1.1075.2.119  raeburn  16731:                     push(@badclasses,$xl);
1.444     albertel 16732:                 }
                   16733:             }
                   16734:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16735:         }
                   16736:     }
                   16737:     if ($args->{'autoadds'}) {
                   16738:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16739:     }
                   16740:     if ($args->{'autodrops'}) {
                   16741:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16742:     }
                   16743: # check for notification of enrollment changes
                   16744:     my @notified = ();
                   16745:     if ($args->{'notify_owner'}) {
                   16746:         if ($args->{'ccuname'} ne '') {
                   16747:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16748:         }
                   16749:     }
                   16750:     if ($args->{'notify_dc'}) {
                   16751:         if ($uname ne '') { 
1.630     raeburn  16752:             push(@notified,$uname.':'.$udom);
1.444     albertel 16753:         }
                   16754:     }
                   16755:     if (@notified > 0) {
                   16756:         my $notifylist;
                   16757:         if (@notified > 1) {
                   16758:             $notifylist = join(',',@notified);
                   16759:         } else {
                   16760:             $notifylist = $notified[0];
                   16761:         }
                   16762:         $cenv{'internal.notifylist'} = $notifylist;
                   16763:     }
                   16764:     if (@badclasses > 0) {
                   16765:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16766:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16767:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16768:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16769:         );
1.1075.2.119  raeburn  16770:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16771:                            &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  16772:         if ($context eq 'auto') {
                   16773:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16774:         } else {
1.566     albertel 16775:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16776:         }
                   16777:         foreach my $item (@badclasses) {
1.541     raeburn  16778:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16779:                 $outcome .= " - $item\n";
1.541     raeburn  16780:             } else {
1.1075.2.119  raeburn  16781:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16782:             }
1.1075.2.119  raeburn  16783:         }
                   16784:         if ($context eq 'auto') {
                   16785:             $outcome .= $linefeed;
                   16786:         } else {
                   16787:             $outcome .= "</ul><br /><br /></div>\n";
                   16788:         }
1.444     albertel 16789:     }
                   16790:     if ($args->{'no_end_date'}) {
                   16791:         $args->{'endaccess'} = 0;
                   16792:     }
1.1075.2.161.  .20(raeb 16793:-23): #  If an official course with institutional sections is created by cloning
                   16794:-23): #  an existing course, section-specific hiding of course totals in student's
                   16795:-23): #  view of grades as copied from cloned course, will be checked for valid
                   16796:-23): #  sections.
                   16797:-23):     if (($can_clone && $cloneid) &&
                   16798:-23):         ($cenv{'internal.coursecode'} ne '') &&
                   16799:-23):         ($cenv{'grading'} eq 'standard') &&
                   16800:-23):         ($cenv{'hidetotals'} ne '') &&
                   16801:-23):         ($cenv{'hidetotals'} ne 'all')) {
                   16802:-23):         my @hidesecs;
                   16803:-23):         my $deletehidetotals;
                   16804:-23):         if (@oklcsecs) {
                   16805:-23):             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   16806:-23):                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   16807:-23):                     push(@hidesecs,$sec);
                   16808:-23):                 }
                   16809:-23):             }
                   16810:-23):             if (@hidesecs) {
                   16811:-23):                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   16812:-23):             } else {
                   16813:-23):                 $deletehidetotals = 1;
                   16814:-23):             }
                   16815:-23):         } else {
                   16816:-23):             $deletehidetotals = 1;
                   16817:-23):         }
                   16818:-23):         if ($deletehidetotals) {
                   16819:-23):             delete($cenv{'hidetotals'});
                   16820:-23):             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   16821:-23):         }
                   16822:-23):     }
1.444     albertel 16823:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16824:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16825:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16826:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16827:     if ($args->{'showphotos'}) {
                   16828:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16829:     }
                   16830:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16831:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16832:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16833:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16834:             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'); 
                   16835:             if ($context eq 'auto') {
                   16836:                 $outcome .= $krb_msg;
                   16837:             } else {
1.566     albertel 16838:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16839:             }
                   16840:             $outcome .= $linefeed;
1.444     albertel 16841:         }
                   16842:     }
                   16843:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16844:        if ($args->{'setpolicy'}) {
                   16845:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16846:        }
                   16847:        if ($args->{'setcontent'}) {
                   16848:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16849:        }
1.1075.2.110  raeburn  16850:        if ($args->{'setcomment'}) {
                   16851:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16852:        }
1.444     albertel 16853:     }
                   16854:     if ($args->{'reshome'}) {
                   16855: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16856: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16857:     }
                   16858: #
                   16859: # course has keyed access
                   16860: #
                   16861:     if ($args->{'setkeys'}) {
                   16862:        $cenv{'keyaccess'}='yes';
                   16863:     }
                   16864: # if specified, key authority is not course, but user
                   16865: # only active if keyaccess is yes
                   16866:     if ($args->{'keyauth'}) {
1.487     albertel 16867: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16868: 	$user = &LONCAPA::clean_username($user);
                   16869: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16870: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16871: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16872: 	}
                   16873:     }
                   16874: 
1.1075.2.59  raeburn  16875: #
                   16876: #  generate and store uniquecode (available to course requester), if course should have one.
                   16877: #
                   16878:     if ($args->{'uniquecode'}) {
                   16879:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16880:         if ($code) {
                   16881:             $cenv{'internal.uniquecode'} = $code;
                   16882:             my %crsinfo =
                   16883:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16884:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16885:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16886:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16887:             }
                   16888:             if (ref($coderef)) {
                   16889:                 $$coderef = $code;
                   16890:             }
                   16891:         }
                   16892:     }
                   16893: 
1.444     albertel 16894:     if ($args->{'disresdis'}) {
                   16895:         $cenv{'pch.roles.denied'}='st';
                   16896:     }
                   16897:     if ($args->{'disablechat'}) {
                   16898:         $cenv{'plc.roles.denied'}='st';
                   16899:     }
                   16900: 
                   16901:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16902:     # course
                   16903:     $cenv{'course.helper.not.run'} = 1;
                   16904:     #
                   16905:     # Use new Randomseed
                   16906:     #
                   16907:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16908:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16909:     #
                   16910:     # The encryption code and receipt prefix for this course
                   16911:     #
                   16912:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16913:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16914:     #
                   16915:     # By default, use standard grading
                   16916:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16917: 
1.541     raeburn  16918:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16919:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16920: #
                   16921: # Open all assignments
                   16922: #
                   16923:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16924:        my $opendate = time;
                   16925:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16926:            $opendate = $args->{'openallfrom'};
                   16927:        }
1.444     albertel 16928:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16929:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16930:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16931:        $outcome .= &mt('All assignments open starting [_1]',
                   16932:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16933:                    &Apache::lonnet::cput
                   16934:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16935:    }
                   16936: #
                   16937: # Set first page
                   16938: #
                   16939:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16940: 	    || ($cloneid)) {
                   16941: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16942: 
                   16943: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16944:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16945: 
1.444     albertel 16946:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16947:         my $title; my $url;
                   16948:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16949: 	    $title=&mt('Syllabus');
1.444     albertel 16950:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16951:         } else {
1.963     raeburn  16952:             $title=&mt('Table of Contents');
1.444     albertel 16953:             $url='/adm/navmaps';
                   16954:         }
1.445     albertel 16955: 
                   16956:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16957: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16958: 
                   16959: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16960:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16961:     }
1.566     albertel 16962: 
1.1075.2.161.  .1(raebu 16963:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16964: }
                   16965: 
1.1075.2.59  raeburn  16966: sub make_unique_code {
                   16967:     my ($cdom,$cnum) = @_;
                   16968:     # get lock on uniquecodes db
                   16969:     my $lockhash = {
                   16970:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16971:                                                   ':'.$env{'user.domain'},
                   16972:                    };
                   16973:     my $tries = 0;
                   16974:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16975:     my ($code,$error);
                   16976: 
                   16977:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16978:         $tries ++;
                   16979:         sleep 1;
                   16980:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16981:     }
                   16982:     if ($gotlock eq 'ok') {
                   16983:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16984:         my $gotcode;
                   16985:         my $attempts = 0;
                   16986:         while ((!$gotcode) && ($attempts < 100)) {
                   16987:             $code = &generate_code();
                   16988:             if (!exists($currcodes{$code})) {
                   16989:                 $gotcode = 1;
                   16990:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16991:                     $error = 'nostore';
                   16992:                 }
                   16993:             }
                   16994:             $attempts ++;
                   16995:         }
                   16996:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16997:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16998:     } else {
                   16999:         $error = 'nolock';
                   17000:     }
                   17001:     return ($code,$error);
                   17002: }
                   17003: 
                   17004: sub generate_code {
                   17005:     my $code;
                   17006:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17007:     for (my $i=0; $i<6; $i++) {
                   17008:         my $lettnum = int (rand 2);
                   17009:         my $item = '';
                   17010:         if ($lettnum) {
                   17011:             $item = $letts[int( rand(18) )];
                   17012:         } else {
                   17013:             $item = 1+int( rand(8) );
                   17014:         }
                   17015:         $code .= $item;
                   17016:     }
                   17017:     return $code;
                   17018: }
                   17019: 
1.444     albertel 17020: ############################################################
                   17021: ############################################################
                   17022: 
1.953     droeschl 17023: #SD
                   17024: # only Community and Course, or anything else?
1.378     raeburn  17025: sub course_type {
                   17026:     my ($cid) = @_;
                   17027:     if (!defined($cid)) {
                   17028:         $cid = $env{'request.course.id'};
                   17029:     }
1.404     albertel 17030:     if (defined($env{'course.'.$cid.'.type'})) {
                   17031:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17032:     } else {
                   17033:         return 'Course';
1.377     raeburn  17034:     }
                   17035: }
1.156     albertel 17036: 
1.406     raeburn  17037: sub group_term {
                   17038:     my $crstype = &course_type();
                   17039:     my %names = (
                   17040:                   'Course' => 'group',
1.865     raeburn  17041:                   'Community' => 'group',
1.406     raeburn  17042:                 );
                   17043:     return $names{$crstype};
                   17044: }
                   17045: 
1.902     raeburn  17046: sub course_types {
1.1075.2.161.  .17(raeb 17047:-23):     my @types = ('official','unofficial','community','textbook','lti');
1.902     raeburn  17048:     my %typename = (
                   17049:                          official   => 'Official course',
                   17050:                          unofficial => 'Unofficial course',
                   17051:                          community  => 'Community',
1.1075.2.59  raeburn  17052:                          textbook   => 'Textbook course',
1.1075.2.161.  .17(raeb 17053:-23):                          lti        => 'LTI provider',
1.902     raeburn  17054:                    );
                   17055:     return (\@types,\%typename);
                   17056: }
                   17057: 
1.156     albertel 17058: sub icon {
                   17059:     my ($file)=@_;
1.505     albertel 17060:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17061:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17062:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17063:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17064: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17065: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17066: 	            $curfext.".gif") {
                   17067: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17068: 		$curfext.".gif";
                   17069: 	}
                   17070:     }
1.249     albertel 17071:     return &lonhttpdurl($iconname);
1.154     albertel 17072: } 
1.84      albertel 17073: 
1.575     albertel 17074: sub lonhttpdurl {
1.692     www      17075: #
                   17076: # Had been used for "small fry" static images on separate port 8080.
                   17077: # Modify here if lightweight http functionality desired again.
                   17078: # Currently eliminated due to increasing firewall issues.
                   17079: #
1.575     albertel 17080:     my ($url)=@_;
1.692     www      17081:     return $url;
1.215     albertel 17082: }
                   17083: 
1.213     albertel 17084: sub connection_aborted {
                   17085:     my ($r)=@_;
                   17086:     $r->print(" ");$r->rflush();
                   17087:     my $c = $r->connection;
                   17088:     return $c->aborted();
                   17089: }
                   17090: 
1.221     foxr     17091: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17092: #    strings as 'strings'.
                   17093: sub escape_single {
1.221     foxr     17094:     my ($input) = @_;
1.223     albertel 17095:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17096:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17097:     return $input;
                   17098: }
1.223     albertel 17099: 
1.222     foxr     17100: #  Same as escape_single, but escape's "'s  This 
                   17101: #  can be used for  "strings"
                   17102: sub escape_double {
                   17103:     my ($input) = @_;
                   17104:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17105:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17106:     return $input;
                   17107: }
1.223     albertel 17108:  
1.222     foxr     17109: #   Escapes the last element of a full URL.
                   17110: sub escape_url {
                   17111:     my ($url)   = @_;
1.238     raeburn  17112:     my @urlslices = split(/\//, $url,-1);
1.369     www      17113:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  17114:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17115: }
1.462     albertel 17116: 
1.820     raeburn  17117: sub compare_arrays {
                   17118:     my ($arrayref1,$arrayref2) = @_;
                   17119:     my (@difference,%count);
                   17120:     @difference = ();
                   17121:     %count = ();
                   17122:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17123:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17124:         foreach my $element (keys(%count)) {
                   17125:             if ($count{$element} == 1) {
                   17126:                 push(@difference,$element);
                   17127:             }
                   17128:         }
                   17129:     }
                   17130:     return @difference;
                   17131: }
                   17132: 
1.1075.2.152  raeburn  17133: sub lon_status_items {
                   17134:     my %defaults = (
                   17135:                      E         => 100,
                   17136:                      W         => 4,
                   17137:                      N         => 1,
                   17138:                      U         => 5,
                   17139:                      threshold => 200,
                   17140:                      sysmail   => 2500,
                   17141:                    );
                   17142:     my %names = (
                   17143:                    E => 'Errors',
                   17144:                    W => 'Warnings',
                   17145:                    N => 'Notices',
                   17146:                    U => 'Unsent',
                   17147:                 );
                   17148:     return (\%defaults,\%names);
                   17149: }
                   17150: 
1.817     bisitz   17151: # -------------------------------------------------------- Initialize user login
1.462     albertel 17152: sub init_user_environment {
1.463     albertel 17153:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17154:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17155: 
                   17156:     my $public=($username eq 'public' && $domain eq 'public');
                   17157: 
                   17158: # See if old ID present, if so, remove
                   17159: 
1.1075.2.161.  .22(raeb 17160:-24):     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17161:-24):         $coauthorenv);
1.462     albertel 17162:     my $now=time;
                   17163: 
                   17164:     if ($public) {
                   17165: 	my $max_public=100;
                   17166: 	my $oldest;
                   17167: 	my $oldest_time=0;
                   17168: 	for(my $next=1;$next<=$max_public;$next++) {
                   17169: 	    if (-e $lonids."/publicuser_$next.id") {
                   17170: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17171: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17172: 		    $oldest_time=$mtime;
                   17173: 		    $oldest=$next;
                   17174: 		}
                   17175: 	    } else {
                   17176: 		$cookie="publicuser_$next";
                   17177: 		last;
                   17178: 	    }
                   17179: 	}
                   17180: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17181:     } else {
1.463     albertel 17182: 	# if this isn't a robot, kill any existing non-robot sessions
                   17183: 	if (!$args->{'robot'}) {
                   17184: 	    opendir(DIR,$lonids);
                   17185: 	    while ($filename=readdir(DIR)) {
                   17186: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  17187:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17188:                             &GDBM_READER(),0640)) {
                   17189:                         my $linkedfile;
                   17190:                         if (exists($oldenv{'user.linkedenv'})) {
                   17191:                             $linkedfile = $oldenv{'user.linkedenv'};
                   17192:                         }
                   17193:                         untie(%oldenv);
                   17194:                         if (unlink("$lonids/$filename")) {
                   17195:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17196:                                 if (-l "$lonids/$linkedfile.id") {
                   17197:                                     unlink("$lonids/$linkedfile.id");
                   17198:                                 }
                   17199:                             }
                   17200:                         }
                   17201:                     } else {
                   17202:                         unlink($lonids.'/'.$filename);
                   17203:                     }
1.463     albertel 17204: 		}
1.462     albertel 17205: 	    }
1.463     albertel 17206: 	    closedir(DIR);
1.1075.2.84  raeburn  17207: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17208:             my $namespace = 'nohist_courseeditor';
                   17209:             my $lockingkey = 'paste'."\0".'locked_num';
                   17210:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17211:                                                 $domain,$username);
                   17212:             if (exists($lockhash{$lockingkey})) {
                   17213:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17214:                 unless ($delresult eq 'ok') {
                   17215:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17216:                 }
                   17217:             }
1.462     albertel 17218: 	}
                   17219: # Give them a new cookie
1.463     albertel 17220: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17221: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17222: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17223:     
                   17224: # Initialize roles
                   17225: 
1.1075.2.161.  .22(raeb 17226:-24): 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17227:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17228:     }
                   17229: # ------------------------------------ Check browser type and MathML capability
                   17230: 
1.1075.2.77  raeburn  17231:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17232:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17233: 
                   17234: # ------------------------------------------------------------- Get environment
                   17235: 
                   17236:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17237:     my ($tmp) = keys(%userenv);
                   17238:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   17239:     } else {
                   17240: 	undef(%userenv);
                   17241:     }
                   17242:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17243: 	$form->{'interface'}=$userenv{'interface'};
                   17244:     }
                   17245:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17246: 
                   17247: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17248:     foreach my $option ('interface','localpath','localres') {
                   17249:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17250:     }
                   17251: # --------------------------------------------------------- Write first profile
                   17252: 
                   17253:     {
1.1075.2.150  raeburn  17254:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 17255: 	my %initial_env = 
                   17256: 	    ("user.name"          => $username,
                   17257: 	     "user.domain"        => $domain,
                   17258: 	     "user.home"          => $authhost,
                   17259: 	     "browser.type"       => $clientbrowser,
                   17260: 	     "browser.version"    => $clientversion,
                   17261: 	     "browser.mathml"     => $clientmathml,
                   17262: 	     "browser.unicode"    => $clientunicode,
                   17263: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  17264:              "browser.mobile"     => $clientmobile,
                   17265:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  17266:              "browser.osversion"  => $clientosversion,
1.462     albertel 17267: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17268: 	     "request.course.fn"  => '',
                   17269: 	     "request.course.uri" => '',
                   17270: 	     "request.course.sec" => '',
                   17271: 	     "request.role"       => 'cm',
                   17272: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  17273: 	     "request.host"       => $ip,);
1.462     albertel 17274: 
                   17275:         if ($form->{'localpath'}) {
                   17276: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17277: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17278:         }
                   17279: 	
                   17280: 	if ($form->{'interface'}) {
                   17281: 	    $form->{'interface'}=~s/\W//gs;
                   17282: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17283: 	    $env{'browser.interface'}=$form->{'interface'};
                   17284: 	}
                   17285: 
1.1075.2.54  raeburn  17286:         if ($form->{'iptoken'}) {
                   17287:             my $lonhost = $r->dir_config('lonHostID');
                   17288:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17289:             $env{'user.noloadbalance'} = $lonhost;
                   17290:         }
                   17291: 
1.1075.2.120  raeburn  17292:         if ($form->{'noloadbalance'}) {
                   17293:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17294:             my $hosthere = $form->{'noloadbalance'};
                   17295:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17296:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17297:                 $env{'user.noloadbalance'} = $hosthere;
                   17298:             }
                   17299:         }
                   17300: 
1.1016    raeburn  17301:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  17302:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17303:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  17304: 
1.1075.2.161.  .10(raeb 17305:-22):             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1075.2.125  raeburn  17306:                 $userenv{'availabletools.'.$tool} = 
                   17307:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17308:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17309:             }
1.724     raeburn  17310: 
1.1075.2.161.  .17(raeb 17311:-23):             foreach my $crstype ('official','unofficial','community','textbook','lti') {
1.1075.2.125  raeburn  17312:                 $userenv{'canrequest.'.$crstype} =
                   17313:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17314:                                                       'reload','requestcourses',
                   17315:                                                       \%userenv,\%domdef,\%is_adv);
                   17316:             }
1.765     raeburn  17317: 
1.1075.2.161.  .21(raeb 17318:-24):             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   17319:-24):                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   17320:-24):                 if ($userenv{'authoreditors'}) {
                   17321:-24):                     $userenv{'editors'} = $userenv{'authoreditors'};
                   17322:-24):                 } elsif ($domdef{'editors'} ne '') {
                   17323:-24):                     $userenv{'editors'} = $domdef{'editors'};
                   17324:-24):                 } else {
                   17325:-24):                     $userenv{'editors'} = 'edit,xml';
                   17326:-24):                 }
          .25(raeb 17327:-24):                 if ($userenv{'authorarchive'}) {
                   17328:-24):                     $userenv{'canarchive'} = 1;
                   17329:-24):                 } elsif (($userenv{'authorarchive'} eq '') &&
                   17330:-24):                          ($domdef{'archive'})) {
                   17331:-24):                     $userenv{'canarchive'} = 1;
                   17332:-24):                 }
          .21(raeb 17333:-24):             }
                   17334:-24): 
1.1075.2.125  raeburn  17335:             $userenv{'canrequest.author'} =
                   17336:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17337:                                                   'reload','requestauthor',
                   17338:                                                   \%userenv,\%domdef,\%is_adv);
                   17339:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17340:                                                  $domain,$username);
                   17341:             my $reqstatus = $reqauthor{'author_status'};
                   17342:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   17343:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17344:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17345:                                                       $reqauthor{'author'}{'timestamp'};
                   17346:                 }
1.1075.2.14  raeburn  17347:             }
                   17348:         }
                   17349: 
1.462     albertel 17350: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17351: 
1.462     albertel 17352: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17353: 		 &GDBM_WRCREAT(),0640)) {
                   17354: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17355: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17356: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17357:             if (ref($firstaccenv) eq 'HASH') {
                   17358:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17359:             }
                   17360:             if (ref($timerintenv) eq 'HASH') {
                   17361:                 &_add_to_env(\%disk_env,$timerintenv);
                   17362:             }
1.1075.2.161.  .22(raeb 17363:-24):             if (ref($coauthorenv) eq 'HASH') {
                   17364:-24):                 if (keys(%{$coauthorenv})) {
                   17365:-24):                     &_add_to_env(\%disk_env,$coauthorenv);
                   17366:-24):                 }
                   17367:-24):             }
1.463     albertel 17368: 	    if (ref($args->{'extra_env'})) {
                   17369: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17370: 	    }
1.462     albertel 17371: 	    untie(%disk_env);
                   17372: 	} else {
1.705     tempelho 17373: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17374: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17375: 	    return 'error: '.$!;
                   17376: 	}
                   17377:     }
                   17378:     $env{'request.role'}='cm';
                   17379:     $env{'request.role.adv'}=$env{'user.adv'};
                   17380:     $env{'browser.type'}=$clientbrowser;
                   17381: 
                   17382:     return $cookie;
                   17383: 
                   17384: }
                   17385: 
                   17386: sub _add_to_env {
                   17387:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17388:     if (ref($env_data) eq 'HASH') {
                   17389:         while (my ($key,$value) = each(%$env_data)) {
                   17390: 	    $idf->{$prefix.$key} = $value;
                   17391: 	    $env{$prefix.$key}   = $value;
                   17392:         }
1.462     albertel 17393:     }
                   17394: }
                   17395: 
1.685     tempelho 17396: # --- Get the symbolic name of a problem and the url
                   17397: sub get_symb {
                   17398:     my ($request,$silent) = @_;
1.726     raeburn  17399:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17400:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17401:     if ($symb eq '') {
                   17402:         if (!$silent) {
1.1071    raeburn  17403:             if (ref($request)) { 
                   17404:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17405:             }
1.685     tempelho 17406:             return ();
                   17407:         }
                   17408:     }
                   17409:     &Apache::lonenc::check_decrypt(\$symb);
                   17410:     return ($symb);
                   17411: }
                   17412: 
                   17413: # --------------------------------------------------------------Get annotation
                   17414: 
                   17415: sub get_annotation {
                   17416:     my ($symb,$enc) = @_;
                   17417: 
                   17418:     my $key = $symb;
                   17419:     if (!$enc) {
                   17420:         $key =
                   17421:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17422:     }
                   17423:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17424:     return $annotation{$key};
                   17425: }
                   17426: 
                   17427: sub clean_symb {
1.731     raeburn  17428:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17429: 
                   17430:     &Apache::lonenc::check_decrypt(\$symb);
                   17431:     my $enc = $env{'request.enc'};
1.731     raeburn  17432:     if ($delete_enc) {
1.730     raeburn  17433:         delete($env{'request.enc'});
                   17434:     }
1.685     tempelho 17435: 
                   17436:     return ($symb,$enc);
                   17437: }
1.462     albertel 17438: 
1.1075.2.69  raeburn  17439: ############################################################
                   17440: ############################################################
                   17441: 
                   17442: =pod
                   17443: 
                   17444: =head1 Routines for building display used to search for courses
                   17445: 
                   17446: 
                   17447: =over 4
                   17448: 
                   17449: =item * &build_filters()
                   17450: 
                   17451: Create markup for a table used to set filters to use when selecting
                   17452: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17453: and quotacheck.pl
                   17454: 
                   17455: 
                   17456: Inputs:
                   17457: 
                   17458: filterlist - anonymous array of fields to include as potential filters
                   17459: 
                   17460: crstype - course type
                   17461: 
                   17462: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17463:               to pop-open a course selector (will contain "extra element").
                   17464: 
                   17465: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17466: 
                   17467: filter - anonymous hash of criteria and their values
                   17468: 
                   17469: action - form action
                   17470: 
                   17471: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17472: 
                   17473: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   17474: 
                   17475: cloneruname - username of owner of new course who wants to clone
                   17476: 
                   17477: clonerudom - domain of owner of new course who wants to clone
                   17478: 
                   17479: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   17480: 
                   17481: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17482: 
                   17483: codedom - domain
                   17484: 
                   17485: formname - value of form element named "form".
                   17486: 
                   17487: fixeddom - domain, if fixed.
                   17488: 
                   17489: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   17490: 
                   17491: cnameelement - name of form element in form on opener page which will receive title of selected course
                   17492: 
                   17493: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17494: 
                   17495: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17496: 
                   17497: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17498: 
                   17499: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17500: 
                   17501: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17502: 
                   17503: 
                   17504: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17505: 
                   17506: 
                   17507: Side Effects: None
                   17508: 
                   17509: =cut
                   17510: 
                   17511: # ---------------------------------------------- search for courses based on last activity etc.
                   17512: 
                   17513: sub build_filters {
                   17514:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17515:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17516:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17517:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17518:         $clonetext,$clonewarning) = @_;
                   17519:     my ($list,$jscript);
                   17520:     my $onchange = 'javascript:updateFilters(this)';
                   17521:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17522:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17523:         $typeselectform,$instcodetitle);
                   17524:     if ($formname eq '') {
                   17525:         $formname = $caller;
                   17526:     }
                   17527:     foreach my $item (@{$filterlist}) {
                   17528:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17529:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17530:             if ($item eq 'domainfilter') {
                   17531:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17532:             } elsif ($item eq 'coursefilter') {
                   17533:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17534:             } elsif ($item eq 'ownerfilter') {
                   17535:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17536:             } elsif ($item eq 'ownerdomfilter') {
                   17537:                 $filter->{'ownerdomfilter'} =
                   17538:                     &LONCAPA::clean_domain($filter->{$item});
                   17539:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17540:                                                        'ownerdomfilter',1);
                   17541:             } elsif ($item eq 'personfilter') {
                   17542:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17543:             } elsif ($item eq 'persondomfilter') {
                   17544:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17545:                                                         'persondomfilter',1);
                   17546:             } else {
                   17547:                 $filter->{$item} =~ s/\W//g;
                   17548:             }
                   17549:             if (!$filter->{$item}) {
                   17550:                 $filter->{$item} = '';
                   17551:             }
                   17552:         }
                   17553:         if ($item eq 'domainfilter') {
                   17554:             my $allow_blank = 1;
                   17555:             if ($formname eq 'portform') {
                   17556:                 $allow_blank=0;
                   17557:             } elsif ($formname eq 'studentform') {
                   17558:                 $allow_blank=0;
                   17559:             }
                   17560:             if ($fixeddom) {
                   17561:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17562:                                     ' value="'.$codedom.'" />'.
                   17563:                                     &Apache::lonnet::domain($codedom,'description');
                   17564:             } else {
                   17565:                 $domainselectform = &select_dom_form($filter->{$item},
                   17566:                                                      'domainfilter',
                   17567:                                                       $allow_blank,'',$onchange);
                   17568:             }
                   17569:         } else {
                   17570:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17571:         }
                   17572:     }
                   17573: 
                   17574:     # last course activity filter and selection
                   17575:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17576: 
                   17577:     # course created filter and selection
                   17578:     if (exists($filter->{'createdfilter'})) {
                   17579:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17580:     }
                   17581: 
                   17582:     my %lt = &Apache::lonlocal::texthash(
                   17583:                 'cac' => "$crstype Activity",
                   17584:                 'ccr' => "$crstype Created",
                   17585:                 'cde' => "$crstype Title",
                   17586:                 'cdo' => "$crstype Domain",
                   17587:                 'ins' => 'Institutional Code',
                   17588:                 'inc' => 'Institutional Categorization',
                   17589:                 'cow' => "$crstype Owner/Co-owner",
                   17590:                 'cop' => "$crstype Personnel Includes",
                   17591:                 'cog' => 'Type',
                   17592:              );
                   17593: 
                   17594:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17595:         my $typeval = 'Course';
                   17596:         if ($crstype eq 'Community') {
                   17597:             $typeval = 'Community';
                   17598:         }
                   17599:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17600:     } else {
                   17601:         $typeselectform =  '<select name="type" size="1"';
                   17602:         if ($onchange) {
                   17603:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17604:         }
                   17605:         $typeselectform .= '>'."\n";
                   17606:         foreach my $posstype ('Course','Community') {
                   17607:             $typeselectform.='<option value="'.$posstype.'"'.
                   17608:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17609:         }
                   17610:         $typeselectform.="</select>";
                   17611:     }
                   17612: 
                   17613:     my ($cloneableonlyform,$cloneabletitle);
                   17614:     if (exists($filter->{'cloneableonly'})) {
                   17615:         my $cloneableon = '';
                   17616:         my $cloneableoff = ' checked="checked"';
                   17617:         if ($filter->{'cloneableonly'}) {
                   17618:             $cloneableon = $cloneableoff;
                   17619:             $cloneableoff = '';
                   17620:         }
                   17621:         $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>';
                   17622:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17623:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17624:         } else {
                   17625:             $cloneabletitle = &mt('Cloneable by you');
                   17626:         }
                   17627:     }
                   17628:     my $officialjs;
                   17629:     if ($crstype eq 'Course') {
                   17630:         if (exists($filter->{'instcodefilter'})) {
                   17631: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17632: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17633:             if ($codedom) {
                   17634:                 $officialjs = 1;
                   17635:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17636:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17637:                                                                   $officialjs,$codetitlesref);
                   17638:                 if ($jscript) {
                   17639:                     $jscript = '<script type="text/javascript">'."\n".
                   17640:                                '// <![CDATA['."\n".
                   17641:                                $jscript."\n".
                   17642:                                '// ]]>'."\n".
                   17643:                                '</script>'."\n";
                   17644:                 }
                   17645:             }
                   17646:             if ($instcodeform eq '') {
                   17647:                 $instcodeform =
                   17648:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17649:                     $list->{'instcodefilter'}.'" />';
                   17650:                 $instcodetitle = $lt{'ins'};
                   17651:             } else {
                   17652:                 $instcodetitle = $lt{'inc'};
                   17653:             }
                   17654:             if ($fixeddom) {
                   17655:                 $instcodetitle .= '<br />('.$codedom.')';
                   17656:             }
                   17657:         }
                   17658:     }
                   17659:     my $output = qq|
                   17660: <form method="post" name="filterpicker" action="$action">
                   17661: <input type="hidden" name="form" value="$formname" />
                   17662: |;
                   17663:     if ($formname eq 'modifycourse') {
                   17664:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17665:                    '<input type="hidden" name="prevphase" value="'.
                   17666:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17667:     } elsif ($formname eq 'quotacheck') {
                   17668:         $output .= qq|
                   17669: <input type="hidden" name="sortby" value="" />
                   17670: <input type="hidden" name="sortorder" value="" />
                   17671: |;
                   17672:     } else {
1.1075.2.69  raeburn  17673:         my $name_input;
                   17674:         if ($cnameelement ne '') {
                   17675:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17676:                           $cnameelement.'" />';
                   17677:         }
                   17678:         $output .= qq|
                   17679: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17680: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17681: $name_input
                   17682: $roleelement
                   17683: $multelement
                   17684: $typeelement
                   17685: |;
                   17686:         if ($formname eq 'portform') {
                   17687:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17688:         }
                   17689:     }
                   17690:     if ($fixeddom) {
                   17691:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17692:     }
                   17693:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17694:     if ($sincefilterform) {
                   17695:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17696:                   .$sincefilterform
                   17697:                   .&Apache::lonhtmlcommon::row_closure();
                   17698:     }
                   17699:     if ($createdfilterform) {
                   17700:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17701:                   .$createdfilterform
                   17702:                   .&Apache::lonhtmlcommon::row_closure();
                   17703:     }
                   17704:     if ($domainselectform) {
                   17705:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17706:                   .$domainselectform
                   17707:                   .&Apache::lonhtmlcommon::row_closure();
                   17708:     }
                   17709:     if ($typeselectform) {
                   17710:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17711:             $output .= $typeselectform;
                   17712:         } else {
                   17713:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17714:                       .$typeselectform
                   17715:                       .&Apache::lonhtmlcommon::row_closure();
                   17716:         }
                   17717:     }
                   17718:     if ($instcodeform) {
                   17719:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17720:                   .$instcodeform
                   17721:                   .&Apache::lonhtmlcommon::row_closure();
                   17722:     }
                   17723:     if (exists($filter->{'ownerfilter'})) {
                   17724:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17725:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17726:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17727:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17728:                    $ownerdomselectform.'</td></tr></table>'.
                   17729:                    &Apache::lonhtmlcommon::row_closure();
                   17730:     }
                   17731:     if (exists($filter->{'personfilter'})) {
                   17732:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17733:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17734:                    '<input type="text" name="personfilter" size="20" value="'.
                   17735:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17736:                    $persondomselectform.'</td></tr></table>'.
                   17737:                    &Apache::lonhtmlcommon::row_closure();
                   17738:     }
                   17739:     if (exists($filter->{'coursefilter'})) {
                   17740:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17741:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17742:                   .$list->{'coursefilter'}.'" />'
                   17743:                   .&Apache::lonhtmlcommon::row_closure();
                   17744:     }
                   17745:     if ($cloneableonlyform) {
                   17746:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17747:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17748:     }
                   17749:     if (exists($filter->{'descriptfilter'})) {
                   17750:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17751:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17752:                   .$list->{'descriptfilter'}.'" />'
                   17753:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17754:     }
                   17755:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17756:                '<input type="hidden" name="updater" value="" />'."\n".
                   17757:                '<input type="submit" name="gosearch" value="'.
                   17758:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17759:     return $jscript.$clonewarning.$output;
                   17760: }
                   17761: 
                   17762: =pod
                   17763: 
                   17764: =item * &timebased_select_form()
                   17765: 
                   17766: Create markup for a dropdown list used to select a time-based
                   17767: filter e.g., Course Activity, Course Created, when searching for courses
                   17768: or communities
                   17769: 
                   17770: Inputs:
                   17771: 
                   17772: item - name of form element (sincefilter or createdfilter)
                   17773: 
                   17774: filter - anonymous hash of criteria and their values
                   17775: 
                   17776: Returns: HTML for a select box contained a blank, then six time selections,
                   17777:          with value set in incoming form variables currently selected.
                   17778: 
                   17779: Side Effects: None
                   17780: 
                   17781: =cut
                   17782: 
                   17783: sub timebased_select_form {
                   17784:     my ($item,$filter) = @_;
                   17785:     if (ref($filter) eq 'HASH') {
                   17786:         $filter->{$item} =~ s/[^\d-]//g;
                   17787:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17788:         return &select_form(
                   17789:                             $filter->{$item},
                   17790:                             $item,
                   17791:                             {      '-1' => '',
                   17792:                                 '86400' => &mt('today'),
                   17793:                                '604800' => &mt('last week'),
                   17794:                               '2592000' => &mt('last month'),
                   17795:                               '7776000' => &mt('last three months'),
                   17796:                              '15552000' => &mt('last six months'),
                   17797:                              '31104000' => &mt('last year'),
                   17798:                     'select_form_order' =>
                   17799:                            ['-1','86400','604800','2592000','7776000',
                   17800:                             '15552000','31104000']});
                   17801:     }
                   17802: }
                   17803: 
                   17804: =pod
                   17805: 
                   17806: =item * &js_changer()
                   17807: 
                   17808: Create script tag containing Javascript used to submit course search form
                   17809: when course type or domain is changed, and also to hide 'Searching ...' on
                   17810: page load completion for page showing search result.
                   17811: 
                   17812: Inputs: None
                   17813: 
                   17814: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17815: 
                   17816: Side Effects: None
                   17817: 
                   17818: =cut
                   17819: 
                   17820: sub js_changer {
                   17821:     return <<ENDJS;
                   17822: <script type="text/javascript">
                   17823: // <![CDATA[
                   17824: function updateFilters(caller) {
                   17825:     if (typeof(caller) != "undefined") {
                   17826:         document.filterpicker.updater.value = caller.name;
                   17827:     }
                   17828:     document.filterpicker.submit();
                   17829: }
                   17830: 
                   17831: function hideSearching() {
                   17832:     if (document.getElementById('searching')) {
                   17833:         document.getElementById('searching').style.display = 'none';
                   17834:     }
                   17835:     return;
                   17836: }
                   17837: 
                   17838: // ]]>
                   17839: </script>
                   17840: 
                   17841: ENDJS
                   17842: }
                   17843: 
                   17844: =pod
                   17845: 
                   17846: =item * &search_courses()
                   17847: 
                   17848: Process selected filters form course search form and pass to lonnet::courseiddump
                   17849: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17850: 
                   17851: Inputs:
                   17852: 
                   17853: dom - domain being searched
                   17854: 
                   17855: type - course type ('Course' or 'Community' or '.' if any).
                   17856: 
                   17857: filter - anonymous hash of criteria and their values
                   17858: 
                   17859: numtitles - for institutional codes - number of categories
                   17860: 
                   17861: cloneruname - optional username of new course owner
                   17862: 
                   17863: clonerudom - optional domain of new course owner
                   17864: 
1.1075.2.95  raeburn  17865: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17866:             (used when DC is using course creation form)
                   17867: 
                   17868: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17869: 
1.1075.2.95  raeburn  17870: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17871:            (and so can clone automatically)
                   17872: 
                   17873: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17874: 
                   17875: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17876:               courses to clone
1.1075.2.69  raeburn  17877: 
                   17878: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17879: 
                   17880: 
                   17881: Side Effects: None
                   17882: 
                   17883: =cut
                   17884: 
                   17885: 
                   17886: sub search_courses {
1.1075.2.95  raeburn  17887:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17888:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17889:     my (%courses,%showcourses,$cloner);
                   17890:     if (($filter->{'ownerfilter'} ne '') ||
                   17891:         ($filter->{'ownerdomfilter'} ne '')) {
                   17892:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17893:                                        $filter->{'ownerdomfilter'};
                   17894:     }
                   17895:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17896:         if (!$filter->{$item}) {
                   17897:             $filter->{$item}='.';
                   17898:         }
                   17899:     }
                   17900:     my $now = time;
                   17901:     my $timefilter =
                   17902:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17903:     my ($createdbefore,$createdafter);
                   17904:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17905:         $createdbefore = $now;
                   17906:         $createdafter = $now-$filter->{'createdfilter'};
                   17907:     }
                   17908:     my ($instcodefilter,$regexpok);
                   17909:     if ($numtitles) {
                   17910:         if ($env{'form.official'} eq 'on') {
                   17911:             $instcodefilter =
                   17912:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17913:             $regexpok = 1;
                   17914:         } elsif ($env{'form.official'} eq 'off') {
                   17915:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17916:             unless ($instcodefilter eq '') {
                   17917:                 $regexpok = -1;
                   17918:             }
                   17919:         }
                   17920:     } else {
                   17921:         $instcodefilter = $filter->{'instcodefilter'};
                   17922:     }
                   17923:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17924:     if ($type eq '') { $type = '.'; }
                   17925: 
                   17926:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17927:         $cloner = $cloneruname.':'.$clonerudom;
                   17928:     }
                   17929:     %courses = &Apache::lonnet::courseiddump($dom,
                   17930:                                              $filter->{'descriptfilter'},
                   17931:                                              $timefilter,
                   17932:                                              $instcodefilter,
                   17933:                                              $filter->{'combownerfilter'},
                   17934:                                              $filter->{'coursefilter'},
                   17935:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17936:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17937:                                              $filter->{'cloneableonly'},
                   17938:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17939:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17940:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17941:         my $ccrole;
                   17942:         if ($type eq 'Community') {
                   17943:             $ccrole = 'co';
                   17944:         } else {
                   17945:             $ccrole = 'cc';
                   17946:         }
                   17947:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17948:                                                      $filter->{'persondomfilter'},
                   17949:                                                      'userroles',undef,
                   17950:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17951:                                                      $dom);
                   17952:         foreach my $role (keys(%rolehash)) {
                   17953:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17954:             my $cid = $cdom.'_'.$cnum;
                   17955:             if (exists($courses{$cid})) {
                   17956:                 if (ref($courses{$cid}) eq 'HASH') {
                   17957:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17958:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17959:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17960:                         }
                   17961:                     } else {
                   17962:                         $courses{$cid}{roles} = [$courserole];
                   17963:                     }
                   17964:                     $showcourses{$cid} = $courses{$cid};
                   17965:                 }
                   17966:             }
                   17967:         }
                   17968:         %courses = %showcourses;
                   17969:     }
                   17970:     return %courses;
                   17971: }
                   17972: 
                   17973: =pod
                   17974: 
                   17975: =back
                   17976: 
1.1075.2.88  raeburn  17977: =head1 Routines for version requirements for current course.
                   17978: 
                   17979: =over 4
                   17980: 
                   17981: =item * &check_release_required()
                   17982: 
                   17983: Compares required LON-CAPA version with version on server, and
                   17984: if required version is newer looks for a server with the required version.
                   17985: 
                   17986: Looks first at servers in user's owen domain; if none suitable, looks at
                   17987: servers in course's domain are permitted to host sessions for user's domain.
                   17988: 
                   17989: Inputs:
                   17990: 
                   17991: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17992: 
                   17993: $courseid - Course ID of current course
                   17994: 
                   17995: $rolecode - User's current role in course (for switchserver query string).
                   17996: 
                   17997: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17998: 
                   17999: 
                   18000: Returns:
                   18001: 
                   18002: $switchserver - query string tp append to /adm/switchserver call (if
                   18003:                 current server's LON-CAPA version is too old.
                   18004: 
                   18005: $warning - Message is displayed if no suitable server could be found.
                   18006: 
                   18007: =cut
                   18008: 
                   18009: sub check_release_required {
                   18010:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18011:     my ($switchserver,$warning);
                   18012:     if ($required ne '') {
                   18013:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18014:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18015:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18016:             my $otherserver;
                   18017:             if (($major eq '' && $minor eq '') ||
                   18018:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18019:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18020:                 my $switchlcrev =
                   18021:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18022:                                                            $userdomserver);
                   18023:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18024:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18025:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18026:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18027:                     if ($cdom ne $env{'user.domain'}) {
                   18028:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18029:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18030:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18031:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18032:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18033:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18034:                         my $canhost =
                   18035:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18036:                                                               $coursedomserver,
                   18037:                                                               $remoterev,
                   18038:                                                               $udomdefaults{'remotesessions'},
                   18039:                                                               $defdomdefaults{'hostedsessions'});
                   18040: 
                   18041:                         if ($canhost) {
                   18042:                             $otherserver = $coursedomserver;
                   18043:                         } else {
                   18044:                             $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.");
                   18045:                         }
                   18046:                     } else {
                   18047:                         $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).");
                   18048:                     }
                   18049:                 } else {
                   18050:                     $otherserver = $userdomserver;
                   18051:                 }
                   18052:             }
                   18053:             if ($otherserver ne '') {
                   18054:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18055:             }
                   18056:         }
                   18057:     }
                   18058:     return ($switchserver,$warning);
                   18059: }
                   18060: 
                   18061: =pod
                   18062: 
                   18063: =item * &check_release_result()
                   18064: 
                   18065: Inputs:
                   18066: 
                   18067: $switchwarning - Warning message if no suitable server found to host session.
                   18068: 
                   18069: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18070:                 and current role.
                   18071: 
                   18072: Returns: HTML to display with information about requirement to switch server.
                   18073:          Either displaying warning with link to Roles/Courses screen or
                   18074:          display link to switchserver.
                   18075: 
1.1075.2.69  raeburn  18076: =cut
                   18077: 
1.1075.2.88  raeburn  18078: sub check_release_result {
                   18079:     my ($switchwarning,$switchserver) = @_;
                   18080:     my $output = &start_page('Selected course unavailable on this server').
                   18081:                  '<p class="LC_warning">';
                   18082:     if ($switchwarning) {
                   18083:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18084:         if (&show_course()) {
                   18085:             $output .= &mt('Display courses');
                   18086:         } else {
                   18087:             $output .= &mt('Display roles');
                   18088:         }
                   18089:         $output .= '</a>';
                   18090:     } elsif ($switchserver) {
                   18091:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18092:                    '<br />'.
                   18093:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18094:                    &mt('Switch Server').
                   18095:                    '</a>';
                   18096:     }
                   18097:     $output .= '</p>'.&end_page();
                   18098:     return $output;
                   18099: }
                   18100: 
                   18101: =pod
                   18102: 
                   18103: =item * &needs_coursereinit()
                   18104: 
                   18105: Determine if course contents stored for user's session needs to be
                   18106: refreshed, because content has changed since "Big Hash" last tied.
                   18107: 
                   18108: Check for change is made if time last checked is more than 10 minutes ago
                   18109: (by default).
                   18110: 
                   18111: Inputs:
                   18112: 
                   18113: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18114: 
                   18115: $interval (optional) - Time which may elapse (in s) between last check for content
                   18116:                        change in current course. (default: 600 s).
                   18117: 
                   18118: Returns: an array; first element is:
                   18119: 
                   18120: =over 4
                   18121: 
                   18122: 'switch' - if content updates mean user's session
                   18123:            needs to be switched to a server running a newer LON-CAPA version
                   18124: 
                   18125: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18126:            on current server hosting user's session
                   18127: 
                   18128: ''       - if no action required.
                   18129: 
                   18130: =back
                   18131: 
                   18132: If first item element is 'switch':
                   18133: 
                   18134: second item is $switchwarning - Warning message if no suitable server found to host session.
                   18135: 
                   18136: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18137:                               and current role.
                   18138: 
                   18139: otherwise: no other elements returned.
                   18140: 
                   18141: =back
                   18142: 
                   18143: =cut
                   18144: 
                   18145: sub needs_coursereinit {
                   18146:     my ($loncaparev,$interval) = @_;
                   18147:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18148:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18149:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18150:     my $now = time;
                   18151:     if ($interval eq '') {
                   18152:         $interval = 600;
                   18153:     }
                   18154:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   18155:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 18156:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 18157:21):         if ($blocked) {
                   18158:21):             return ();
                   18159:21):         }
          .13(raeb 18160:-23):         my $update;
                   18161:-23):         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18162:-23):         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18163:-23):         if ($lastmainchange > $env{'request.course.tied'}) {
                   18164:-23):             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18165:-23):             if ($needswitch) {
                   18166:-23):                 return ('switch',$switchwarning,$switchserver);
                   18167:-23):             }
                   18168:-23):             $update = 'main';
                   18169:-23):         }
                   18170:-23):         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18171:-23):             if ($update) {
                   18172:-23):                 $update = 'both';
                   18173:-23):             } else {
                   18174:-23):                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18175:-23):                 if ($needswitch) {
                   18176:-23):                     return ('switch',$switchwarning,$switchserver);
                   18177:-23):                 } else {
                   18178:-23):                     $update = 'supp';
1.1075.2.88  raeburn  18179:                 }
                   18180:             }
1.1075.2.161.  .13(raeb 18181:-23):             return ($update);
                   18182:-23):         }
                   18183:-23):     }
                   18184:-23):     return ();
                   18185:-23): }
                   18186:-23): 
                   18187:-23): sub switch_for_update {
                   18188:-23):     my ($loncaparev,$cdom,$cnum) = @_;
                   18189:-23):     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18190:-23):     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18191:-23):         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18192:-23):         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18193:-23):             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18194:-23):                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18195:-23):             my ($switchserver,$switchwarning) =
                   18196:-23):                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18197:-23):                                         $curr_reqd_hash{'internal.releaserequired'});
                   18198:-23):             if ($switchwarning ne '' || $switchserver ne '') {
                   18199:-23):                 return ('switch',$switchwarning,$switchserver);
                   18200:-23):             }
1.1075.2.88  raeburn  18201:         }
                   18202:     }
                   18203:     return ();
                   18204: }
1.1075.2.69  raeburn  18205: 
1.1075.2.11  raeburn  18206: sub update_content_constraints {
                   18207:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18208:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18209:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   18210:     my %checkresponsetypes;
                   18211:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   18212:         my ($item,$name,$value) = split(/:/,$key);
                   18213:         if ($item eq 'resourcetag') {
                   18214:             if ($name eq 'responsetype') {
                   18215:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18216:             }
                   18217:         }
                   18218:     }
                   18219:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18220:     if (defined($navmap)) {
                   18221:         my %allresponses;
                   18222:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   18223:             my %responses = $res->responseTypes();
                   18224:             foreach my $key (keys(%responses)) {
                   18225:                 next unless(exists($checkresponsetypes{$key}));
                   18226:                 $allresponses{$key} += $responses{$key};
                   18227:             }
                   18228:         }
                   18229:         foreach my $key (keys(%allresponses)) {
                   18230:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18231:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18232:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18233:             }
                   18234:         }
                   18235:         undef($navmap);
                   18236:     }
                   18237:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18238:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18239:     }
                   18240:     return;
                   18241: }
                   18242: 
1.1075.2.27  raeburn  18243: sub allmaps_incourse {
                   18244:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18245:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18246:         $cid = $env{'request.course.id'};
                   18247:         $cdom = $env{'course.'.$cid.'.domain'};
                   18248:         $cnum = $env{'course.'.$cid.'.num'};
                   18249:         $chome = $env{'course.'.$cid.'.home'};
                   18250:     }
                   18251:     my %allmaps = ();
                   18252:     my $lastchange =
                   18253:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18254:     if ($lastchange > $env{'request.course.tied'}) {
                   18255:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18256:         unless ($ferr) {
                   18257:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   18258:         }
                   18259:     }
                   18260:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18261:     if (defined($navmap)) {
                   18262:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18263:             $allmaps{$res->src()} = 1;
                   18264:         }
                   18265:     }
                   18266:     return \%allmaps;
                   18267: }
                   18268: 
1.1075.2.11  raeburn  18269: sub parse_supplemental_title {
                   18270:     my ($title) = @_;
                   18271: 
                   18272:     my ($foldertitle,$renametitle);
                   18273:     if ($title =~ /&amp;&amp;&amp;/) {
                   18274:         $title = &HTML::Entites::decode($title);
                   18275:     }
                   18276:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18277:         $renametitle=$4;
                   18278:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18279:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18280:         my $name =  &plainname($uname,$udom);
                   18281:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18282:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1075.2.161.  .16(raeb 18283:-23):         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
                   18284:-23):         if ($foldertitle ne '') {
                   18285:-23):             $title .= ': <br />'.$foldertitle;
                   18286:-23):         }
1.1075.2.11  raeburn  18287:     }
                   18288:     if (wantarray) {
                   18289:         return ($title,$foldertitle,$renametitle);
                   18290:     }
                   18291:     return $title;
                   18292: }
                   18293: 
1.1075.2.161.  .13(raeb 18294:-23): sub get_supplemental {
                   18295:-23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18296:-23):     my $hashid=$cnum.':'.$cdom;
                   18297:-23):     my ($supplemental,$cached,$set_httprefs);
                   18298:-23):     unless ($ignorecache) {
                   18299:-23):         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18300:-23):     }
                   18301:-23):     unless (defined($cached)) {
                   18302:-23):         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18303:-23):         unless ($chome eq 'no_host') {
                   18304:-23):             my @order = @LONCAPA::map::order;
                   18305:-23):             my @resources = @LONCAPA::map::resources;
                   18306:-23):             my @resparms = @LONCAPA::map::resparms;
                   18307:-23):             my @zombies = @LONCAPA::map::zombies;
                   18308:-23):             my ($errors,%ids,%hidden);
                   18309:-23):             $errors =
                   18310:-23):                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   18311:-23):                                       $errors,$possdel,\%ids,\%hidden);
                   18312:-23):             @LONCAPA::map::order = @order;
                   18313:-23):             @LONCAPA::map::resources = @resources;
                   18314:-23):             @LONCAPA::map::resparms = @resparms;
                   18315:-23):             @LONCAPA::map::zombies = @zombies;
                   18316:-23):             $set_httprefs = 1;
                   18317:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18318:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18319:-23):             }
                   18320:-23):             $supplemental = {
                   18321:-23):                                ids => \%ids,
                   18322:-23):                                hidden => \%hidden,
                   18323:-23):                             };
                   18324:-23):             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   18325:-23):         }
                   18326:-23):     }
                   18327:-23):     return ($supplemental,$set_httprefs);
                   18328:-23): }
                   18329:-23): 
1.1075.2.43  raeburn  18330: sub recurse_supplemental {
1.1075.2.161.  .13(raeb 18331:-23):     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18332:-23):     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18333:-23):         my $mapnum;
                   18334:-23):         if ($suppmap eq 'supplemental.sequence') {
                   18335:-23):             $mapnum = 0;
                   18336:-23):         } else {
                   18337:-23):             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18338:-23):         }
1.1075.2.43  raeburn  18339:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18340:         if ($fatal) {
                   18341:             $errors ++;
                   18342:         } else {
1.1075.2.161.  .13(raeb 18343:-23):             my @order = @LONCAPA::map::order;
                   18344:-23):             if (@order > 0) {
                   18345:-23):                 my @resources = @LONCAPA::map::resources;
                   18346:-23):                 my @resparms = @LONCAPA::map::resparms;
                   18347:-23):                 foreach my $idx (@order) {
                   18348:-23):                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1075.2.43  raeburn  18349:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.161.  .13(raeb 18350:-23):                         my $id = $mapnum.':'.$idx;
                   18351:-23):                         push(@{$suppids->{$src}},$id);
                   18352:-23):                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18353:-23):                             $hiddensupp->{$id} = 1;
                   18354:-23):                         }
1.1075.2.46  raeburn  18355:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1075.2.161.  .13(raeb 18356:-23):                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18357:-23):                                                             $hiddensupp,$hiddensupp->{$id});
1.1075.2.43  raeburn  18358:                         } else {
1.1075.2.161.  .13(raeb 18359:-23):                             my $allowed;
                   18360:-23):                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18361:-23):                                 $allowed = 1;
                   18362:-23):                             } elsif ($possdel) {
                   18363:-23):                                 foreach my $item (@{$suppids->{$src}}) {
                   18364:-23):                                     next if ($item eq $id);
                   18365:-23):                                     unless ($hiddensupp->{$item}) {
                   18366:-23):                                        $allowed = 1;
                   18367:-23):                                        last;
                   18368:-23):                                     }
                   18369:-23):                                 }
                   18370:-23):                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18371:-23):                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18372:-23):                                 }
                   18373:-23):                             }
                   18374:-23):                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18375:-23):                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18376:-23):                             }
                   18377:-23):                         }
                   18378:-23):                     }
                   18379:-23):                 }
                   18380:-23):             }
                   18381:-23):         }
                   18382:-23):     }
                   18383:-23):     return $errors;
                   18384:-23): }
                   18385:-23): 
                   18386:-23): sub set_supp_httprefs {
                   18387:-23):     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18388:-23):     if (ref($supplemental) eq 'HASH') {
                   18389:-23):         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18390:-23):             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18391:-23):                 next if ($src =~ /\.sequence$/);
                   18392:-23):                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18393:-23):                     my $allowed;
                   18394:-23):                     if ($env{'request.role.adv'}) {
                   18395:-23):                         $allowed = 1;
                   18396:-23):                     } else {
                   18397:-23):                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18398:-23):                             unless ($supplemental->{'hidden'}->{$id}) {
                   18399:-23):                                 $allowed = 1;
                   18400:-23):                                 last;
                   18401:-23):                             }
                   18402:-23):                         }
                   18403:-23):                     }
                   18404:-23):                     if (exists($env{'httpref.'.$src})) {
                   18405:-23):                         if ($possdel) {
                   18406:-23):                             unless ($allowed) {
                   18407:-23):                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18408:-23):                             }
1.1075.2.43  raeburn  18409:                         }
1.1075.2.161.  .13(raeb 18410:-23):                     } elsif ($allowed) {
                   18411:-23):                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1075.2.43  raeburn  18412:                     }
                   18413:                 }
                   18414:             }
1.1075.2.161.  .13(raeb 18415:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18416:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18417:-23):             }
1.1075.2.43  raeburn  18418:         }
                   18419:     }
1.1075.2.161.  .13(raeb 18420:-23): }
                   18421:-23): 
                   18422:-23): sub get_supp_parameter {
                   18423:-23):     my ($resparm,$name)=@_;
                   18424:-23):     return if ($resparm eq '');
                   18425:-23):     my $value=undef;
                   18426:-23):     my $ptype=undef;
                   18427:-23):     foreach (split('&&&',$resparm)) {
                   18428:-23):         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18429:-23):         if ($thisname eq $name) {
                   18430:-23):             $value=$thisvalue;
                   18431:-23):             $ptype=$thistype;
                   18432:-23):         }
                   18433:-23):     }
                   18434:-23):     return $value;
1.1075.2.43  raeburn  18435: }
                   18436: 
1.1075.2.18  raeburn  18437: sub symb_to_docspath {
1.1075.2.119  raeburn  18438:     my ($symb,$navmapref) = @_;
                   18439:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  18440:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18441:     if ($resurl=~/\.(sequence|page)$/) {
                   18442:         $mapurl=$resurl;
                   18443:     } elsif ($resurl eq 'adm/navmaps') {
                   18444:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18445:     }
                   18446:     my $mapresobj;
1.1075.2.119  raeburn  18447:     unless (ref($$navmapref)) {
                   18448:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18449:     }
                   18450:     if (ref($$navmapref)) {
                   18451:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  18452:     }
                   18453:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18454:     my $type=$2;
                   18455:     my $path;
                   18456:     if (ref($mapresobj)) {
                   18457:         my $pcslist = $mapresobj->map_hierarchy();
                   18458:         if ($pcslist ne '') {
                   18459:             foreach my $pc (split(/,/,$pcslist)) {
                   18460:                 next if ($pc <= 1);
1.1075.2.119  raeburn  18461:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  18462:                 if (ref($res)) {
                   18463:                     my $thisurl = $res->src();
                   18464:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18465:                     my $thistitle = $res->title();
                   18466:                     $path .= '&'.
                   18467:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  18468:                              &escape($thistitle).
1.1075.2.18  raeburn  18469:                              ':'.$res->randompick().
                   18470:                              ':'.$res->randomout().
                   18471:                              ':'.$res->encrypted().
                   18472:                              ':'.$res->randomorder().
                   18473:                              ':'.$res->is_page();
                   18474:                 }
                   18475:             }
                   18476:         }
                   18477:         $path =~ s/^\&//;
                   18478:         my $maptitle = $mapresobj->title();
                   18479:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18480:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18481:         }
                   18482:         $path .= (($path ne '')? '&' : '').
                   18483:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18484:                  &escape($maptitle).
1.1075.2.18  raeburn  18485:                  ':'.$mapresobj->randompick().
                   18486:                  ':'.$mapresobj->randomout().
                   18487:                  ':'.$mapresobj->encrypted().
                   18488:                  ':'.$mapresobj->randomorder().
                   18489:                  ':'.$mapresobj->is_page();
                   18490:     } else {
                   18491:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18492:         my $ispage = (($type eq 'page')? 1 : '');
                   18493:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  18494:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  18495:         }
                   18496:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  18497:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  18498:     }
                   18499:     unless ($mapurl eq 'default') {
                   18500:         $path = 'default&'.
1.1075.2.46  raeburn  18501:                 &escape('Main Content').
1.1075.2.18  raeburn  18502:                 ':::::&'.$path;
                   18503:     }
                   18504:     return $path;
                   18505: }
                   18506: 
1.1075.2.161.  .13(raeb 18507:-23): sub validate_folderpath {
                   18508:-23):     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18509:-23):     if ($env{'form.folderpath'} ne '') {
                   18510:-23):         my @items = split(/\&/,$env{'form.folderpath'});
                   18511:-23):         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
                   18512:-23):         for (my $i=0; $i<@items; $i++) {
                   18513:-23):             my $odd = $i%2;
                   18514:-23):             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18515:-23):                 $badpath = 1;
                   18516:-23):             } elsif ($odd && $supplementalflag) {
                   18517:-23):                 my $idx = $i-1;
                   18518:-23):                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18519:-23):                     my $esc_name = $1;
                   18520:-23):                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18521:-23):                         $supppath .= '&'.$esc_name;
                   18522:-23):                         $changed = 1;
                   18523:-23):                     } else {
                   18524:-23):                         $supppath .= '&'.$items[$i];
                   18525:-23):                     }
                   18526:-23):                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18527:-23):                     $changed = 1;
                   18528:-23):                     my $is_hidden;
                   18529:-23):                     unless ($got_supp) {
                   18530:-23):                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
                   18531:-23):                         if (ref($supplemental) eq 'HASH') {
                   18532:-23):                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18533:-23):                                 %supphidden = %{$supplemental->{'hidden'}};
                   18534:-23):                             }
                   18535:-23):                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18536:-23):                                 %suppids = %{$supplemental->{'ids'}};
                   18537:-23):                             }
                   18538:-23):                         }
                   18539:-23):                         $got_supp = 1;
                   18540:-23):                     }
                   18541:-23):                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18542:-23):                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18543:-23):                         if ($supphidden{$mapid}) {
                   18544:-23):                             $is_hidden = 1;
                   18545:-23):                         }
                   18546:-23):                     }
                   18547:-23):                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18548:-23):                 } else {
                   18549:-23):                     $supppath .= '&'.$items[$i];
                   18550:-23):                 }
                   18551:-23):             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18552:-23):                 $badpath = 1;
                   18553:-23):             } elsif ($supplementalflag) {
                   18554:-23):                 $supppath .= '&'.$items[$i];
                   18555:-23):             }
                   18556:-23):             last if ($badpath);
                   18557:-23):         }
                   18558:-23):         if ($badpath) {
                   18559:-23):             delete($env{'form.folderpath'});
                   18560:-23):         } elsif ($changed && $supplementalflag) {
                   18561:-23):             $supppath =~ s/^\&//;
                   18562:-23):             $env{'form.folderpath'} = $supppath;
                   18563:-23):         }
                   18564:-23):     }
                   18565:-23):     return;
                   18566:-23): }
                   18567:-23): 
1.1075.2.14  raeburn  18568: sub captcha_display {
1.1075.2.137  raeburn  18569:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18570:     my ($output,$error);
1.1075.2.107  raeburn  18571:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  18572:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18573:     if ($captcha eq 'original') {
                   18574:         $output = &create_captcha();
                   18575:         unless ($output) {
                   18576:             $error = 'captcha';
                   18577:         }
                   18578:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18579:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  18580:         unless ($output) {
                   18581:             $error = 'recaptcha';
                   18582:         }
                   18583:     }
1.1075.2.107  raeburn  18584:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  18585: }
                   18586: 
                   18587: sub captcha_response {
1.1075.2.137  raeburn  18588:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18589:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  18590:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18591:     if ($captcha eq 'original') {
                   18592:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18593:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18594:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  18595:     } else {
                   18596:         $captcha_chk = 1;
                   18597:     }
                   18598:     return ($captcha_chk,$captcha_error);
                   18599: }
                   18600: 
                   18601: sub get_captcha_config {
1.1075.2.137  raeburn  18602:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  18603:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  18604:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18605:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18606:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18607:     if ($context eq 'usercreation') {
                   18608:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18609:         if (ref($domconfig{$context}) eq 'HASH') {
                   18610:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18611:             if (ref($hashtocheck) eq 'HASH') {
                   18612:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18613:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18614:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18615:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18616:                     }
                   18617:                     if ($privkey && $pubkey) {
                   18618:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  18619:                         $version = $hashtocheck->{'recaptchaversion'};
                   18620:                         if ($version ne '2') {
                   18621:                             $version = 1;
                   18622:                         }
1.1075.2.14  raeburn  18623:                     } else {
                   18624:                         $captcha = 'original';
                   18625:                     }
                   18626:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18627:                     $captcha = 'original';
                   18628:                 }
                   18629:             }
                   18630:         } else {
                   18631:             $captcha = 'captcha';
                   18632:         }
                   18633:     } elsif ($context eq 'login') {
                   18634:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18635:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18636:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18637:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   18638:             if ($privkey && $pubkey) {
                   18639:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  18640:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18641:                 if ($version ne '2') {
                   18642:                     $version = 1;
                   18643:                 }
1.1075.2.14  raeburn  18644:             } else {
                   18645:                 $captcha = 'original';
                   18646:             }
                   18647:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18648:             $captcha = 'original';
                   18649:         }
1.1075.2.137  raeburn  18650:     } elsif ($context eq 'passwords') {
                   18651:         if ($dom_in_effect) {
                   18652:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18653:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18654:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18655:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18656:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18657:                 }
                   18658:                 if ($privkey && $pubkey) {
                   18659:                     $captcha = 'recaptcha';
                   18660:                     $version = $passwdconf{'recaptchaversion'};
                   18661:                     if ($version ne '2') {
                   18662:                         $version = 1;
                   18663:                     }
                   18664:                 } else {
                   18665:                     $captcha = 'original';
                   18666:                 }
                   18667:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18668:                 $captcha = 'original';
                   18669:             }
                   18670:         }
1.1075.2.14  raeburn  18671:     }
1.1075.2.107  raeburn  18672:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  18673: }
                   18674: 
                   18675: sub create_captcha {
                   18676:     my %captcha_params = &captcha_settings();
                   18677:     my ($output,$maxtries,$tries) = ('',10,0);
                   18678:     while ($tries < $maxtries) {
                   18679:         $tries ++;
                   18680:         my $captcha = Authen::Captcha->new (
                   18681:                                            output_folder => $captcha_params{'output_dir'},
                   18682:                                            data_folder   => $captcha_params{'db_dir'},
                   18683:                                           );
                   18684:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18685: 
                   18686:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18687:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  18688:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  18689:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.161.  .15(raeb 18690:-23):                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1075.2.158  raeburn  18691:                       '</span><br />'.
1.1075.2.66  raeburn  18692:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  18693:             last;
                   18694:         }
                   18695:     }
1.1075.2.158  raeburn  18696:     if ($output eq '') {
                   18697:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18698:     }
1.1075.2.14  raeburn  18699:     return $output;
                   18700: }
                   18701: 
                   18702: sub captcha_settings {
                   18703:     my %captcha_params = (
                   18704:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18705:                            www_output_dir => "/captchaspool",
                   18706:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18707:                            numchars       => '5',
                   18708:                          );
                   18709:     return %captcha_params;
                   18710: }
                   18711: 
                   18712: sub check_captcha {
                   18713:     my ($captcha_chk,$captcha_error);
                   18714:     my $code = $env{'form.code'};
                   18715:     my $md5sum = $env{'form.crypt'};
                   18716:     my %captcha_params = &captcha_settings();
                   18717:     my $captcha = Authen::Captcha->new(
                   18718:                       output_folder => $captcha_params{'output_dir'},
                   18719:                       data_folder   => $captcha_params{'db_dir'},
                   18720:                   );
1.1075.2.26  raeburn  18721:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  18722:     my %captcha_hash = (
                   18723:                         0       => 'Code not checked (file error)',
                   18724:                        -1      => 'Failed: code expired',
                   18725:                        -2      => 'Failed: invalid code (not in database)',
                   18726:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18727:     );
                   18728:     if ($captcha_chk != 1) {
                   18729:         $captcha_error = $captcha_hash{$captcha_chk}
                   18730:     }
                   18731:     return ($captcha_chk,$captcha_error);
                   18732: }
                   18733: 
                   18734: sub create_recaptcha {
1.1075.2.107  raeburn  18735:     my ($pubkey,$version) = @_;
                   18736:     if ($version >= 2) {
1.1075.2.158  raeburn  18737:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18738:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  18739:     } else {
                   18740:         my $use_ssl;
                   18741:         if ($ENV{'SERVER_PORT'} == 443) {
                   18742:             $use_ssl = 1;
                   18743:         }
                   18744:         my $captcha = Captcha::reCAPTCHA->new;
                   18745:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18746:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18747:                &mt('If the text is hard to read, [_1] will replace them.',
                   18748:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18749:                '<br /><br />';
                   18750:      }
1.1075.2.14  raeburn  18751: }
                   18752: 
                   18753: sub check_recaptcha {
1.1075.2.107  raeburn  18754:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  18755:     my $captcha_chk;
1.1075.2.150  raeburn  18756:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  18757:     if ($version >= 2) {
                   18758:         my $ua = LWP::UserAgent->new;
                   18759:         $ua->timeout(10);
                   18760:         my %info = (
                   18761:                      secret   => $privkey,
                   18762:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  18763:                      remoteip => $ip,
1.1075.2.107  raeburn  18764:                    );
                   18765:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   18766:         if ($response->is_success)  {
                   18767:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18768:             if (ref($data) eq 'HASH') {
                   18769:                 if ($data->{'success'}) {
                   18770:                     $captcha_chk = 1;
                   18771:                 }
                   18772:             }
                   18773:         }
                   18774:     } else {
                   18775:         my $captcha = Captcha::reCAPTCHA->new;
                   18776:         my $captcha_result =
                   18777:             $captcha->check_answer(
                   18778:                                     $privkey,
1.1075.2.150  raeburn  18779:                                     $ip,
1.1075.2.107  raeburn  18780:                                     $env{'form.recaptcha_challenge_field'},
                   18781:                                     $env{'form.recaptcha_response_field'},
                   18782:                                   );
                   18783:         if ($captcha_result->{is_valid}) {
                   18784:             $captcha_chk = 1;
                   18785:         }
1.1075.2.14  raeburn  18786:     }
                   18787:     return $captcha_chk;
                   18788: }
                   18789: 
1.1075.2.64  raeburn  18790: sub emailusername_info {
1.1075.2.103  raeburn  18791:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18792:     my %titles = &Apache::lonlocal::texthash (
                   18793:                      lastname      => 'Last Name',
                   18794:                      firstname     => 'First Name',
                   18795:                      institution   => 'School/college/university',
                   18796:                      location      => "School's city, state/province, country",
                   18797:                      web           => "School's web address",
                   18798:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18799:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18800:                  );
                   18801:     return (\@fields,\%titles);
                   18802: }
                   18803: 
1.1075.2.56  raeburn  18804: sub cleanup_html {
                   18805:     my ($incoming) = @_;
                   18806:     my $outgoing;
                   18807:     if ($incoming ne '') {
                   18808:         $outgoing = $incoming;
                   18809:         $outgoing =~ s/;/&#059;/g;
                   18810:         $outgoing =~ s/\#/&#035;/g;
                   18811:         $outgoing =~ s/\&/&#038;/g;
                   18812:         $outgoing =~ s/</&#060;/g;
                   18813:         $outgoing =~ s/>/&#062;/g;
                   18814:         $outgoing =~ s/\(/&#040/g;
                   18815:         $outgoing =~ s/\)/&#041;/g;
                   18816:         $outgoing =~ s/"/&#034;/g;
                   18817:         $outgoing =~ s/'/&#039;/g;
                   18818:         $outgoing =~ s/\$/&#036;/g;
                   18819:         $outgoing =~ s{/}{&#047;}g;
                   18820:         $outgoing =~ s/=/&#061;/g;
                   18821:         $outgoing =~ s/\\/&#092;/g
                   18822:     }
                   18823:     return $outgoing;
                   18824: }
                   18825: 
1.1075.2.74  raeburn  18826: # Checks for critical messages and returns a redirect url if one exists.
                   18827: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18828:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18829: sub critical_redirect {
1.1075.2.161.  .1(raebu 18830:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18831:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18832:         return ();
                   18833:     }
1.1075.2.74  raeburn  18834:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18835:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18836:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18837:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18838:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18839:21):             if ($blocked) {
                   18840:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18841:21):                 if ($env{'request.course.sec'} ne '') {
                   18842:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18843:21):                 }
                   18844:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18845:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18846:21):                     return;
                   18847:21):                 }
                   18848:21):             }
                   18849:21):         }
1.1075.2.74  raeburn  18850:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18851:                                         $env{'user.name'});
                   18852:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18853:         my $redirecturl;
                   18854:         if ($what[0]) {
1.1075.2.158  raeburn  18855:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18856:                 $redirecturl='/adm/email?critical=display';
                   18857:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18858:                 return (1, $url);
                   18859:             }
                   18860:         }
                   18861:     }
                   18862:     return ();
                   18863: }
                   18864: 
1.1075.2.64  raeburn  18865: # Use:
                   18866: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18867: #
                   18868: ##################################################
                   18869: #          password associated functions         #
                   18870: ##################################################
                   18871: sub des_keys {
                   18872:     # Make a new key for DES encryption.
                   18873:     # Each key has two parts which are returned separately.
                   18874:     # Please note:  Each key must be passed through the &hex function
                   18875:     # before it is output to the web browser.  The hex versions cannot
                   18876:     # be used to decrypt.
                   18877:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18878:                 '8','9','a','b','c','d','e','f');
                   18879:     my $lkey='';
                   18880:     for (0..7) {
                   18881:         $lkey.=$hexstr[rand(15)];
                   18882:     }
                   18883:     my $ukey='';
                   18884:     for (0..7) {
                   18885:         $ukey.=$hexstr[rand(15)];
                   18886:     }
                   18887:     return ($lkey,$ukey);
                   18888: }
                   18889: 
                   18890: sub des_decrypt {
                   18891:     my ($key,$cyphertext) = @_;
                   18892:     my $keybin=pack("H16",$key);
                   18893:     my $cypher;
                   18894:     if ($Crypt::DES::VERSION>=2.03) {
                   18895:         $cypher=new Crypt::DES $keybin;
                   18896:     } else {
                   18897:         $cypher=new DES $keybin;
                   18898:     }
1.1075.2.106  raeburn  18899:     my $plaintext='';
                   18900:     my $cypherlength = length($cyphertext);
                   18901:     my $numchunks = int($cypherlength/32);
                   18902:     for (my $j=0; $j<$numchunks; $j++) {
                   18903:         my $start = $j*32;
                   18904:         my $cypherblock = substr($cyphertext,$start,32);
                   18905:         my $chunk =
                   18906:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18907:         $chunk .=
                   18908:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18909:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18910:         $plaintext .= $chunk;
                   18911:     }
1.1075.2.64  raeburn  18912:     return $plaintext;
                   18913: }
                   18914: 
1.1075.2.161.  .1(raebu 18915:21): sub get_requested_shorturls {
                   18916:21):     my ($cdom,$cnum,$navmap) = @_;
                   18917:21):     return unless (ref($navmap));
                   18918:21):     my ($numnew,$errors);
                   18919:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18920:21):     if (@toshorten) {
                   18921:21):         my (%maps,%resources,%titles);
                   18922:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18923:21):                                                                'shorturls',$cdom,$cnum);
                   18924:21):         if (keys(%resources)) {
                   18925:21):             my %tocreate;
                   18926:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18927:21):                 my $symb = $resources{$item};
                   18928:21):                 if ($symb) {
                   18929:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18930:21):                 }
                   18931:21):             }
                   18932:21):             if (keys(%tocreate)) {
                   18933:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18934:21):                                                       \%tocreate);
                   18935:21):             }
                   18936:21):         }
                   18937:21):     }
                   18938:21):     return ($numnew,$errors);
                   18939:21): }
                   18940:21): 
                   18941:21): sub make_short_symbs {
                   18942:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18943:21):     my ($numnew,@errors);
                   18944:21):     if (ref($tocreateref) eq 'HASH') {
                   18945:21):         my %tocreate = %{$tocreateref};
                   18946:21):         if (keys(%tocreate)) {
                   18947:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18948:21):             my $su = Short::URL->new(no_vowels => 1);
                   18949:21):             my $init = '';
                   18950:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   18951:21):             # get lock on tiny db
                   18952:21):             my $now = time;
                   18953:21):             if ($lockuser eq '') {
                   18954:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18955:21):             }
                   18956:21):             my $lockhash = {
                   18957:21):                                 "lock\0$now" => $lockuser,
                   18958:21):                             };
                   18959:21):             my $tries = 0;
                   18960:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18961:21):             my ($code,$error);
                   18962:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   18963:21):                 $tries ++;
                   18964:21):                 sleep 1;
                   18965:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18966:21):             }
                   18967:21):             if ($gotlock eq 'ok') {
                   18968:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18969:21):                                        \%addcourse,\%courseonly,\%failed);
                   18970:21):                 if (keys(%failed)) {
                   18971:21):                     my $numfailed = scalar(keys(%failed));
                   18972:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18973:21):                 }
                   18974:21):                 if (keys(%newunique)) {
                   18975:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18976:21):                     if ($putres eq 'ok') {
                   18977:21):                         $numnew = scalar(keys(%newunique));
                   18978:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18979:21):                         unless ($newputres eq 'ok') {
                   18980:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18981:21):                         }
                   18982:21):                     } else {
                   18983:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18984:21):                     }
                   18985:21):                 }
                   18986:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18987:21):                 unless ($dellockres eq 'ok') {
                   18988:21):                     push(@errors,&mt('error: could not release lockfile'));
                   18989:21):                 }
                   18990:21):             } else {
                   18991:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   18992:21):             }
                   18993:21):             if (keys(%courseonly)) {
                   18994:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18995:21):                 if ($result ne 'ok') {
                   18996:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18997:21):                 }
                   18998:21):             }
                   18999:21):         }
                   19000:21):     }
                   19001:21):     return ($numnew,\@errors);
                   19002:21): }
                   19003:21): 
                   19004:21): sub shorten_symbs {
                   19005:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19006:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19007:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19008:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19009:21):     my (%possibles,%collisions);
                   19010:21):     foreach my $key (keys(%{$tocreate})) {
                   19011:21):         my $num = String::CRC32::crc32($key);
                   19012:21):         my $tiny = $su->encode($num,$init);
                   19013:21):         if ($tiny) {
                   19014:21):             $possibles{$tiny} = $key;
                   19015:21):         }
                   19016:21):     }
                   19017:21):     if (!$init) {
                   19018:21):         $init = 1;
                   19019:21):     } else {
                   19020:21):         $init ++;
                   19021:21):     }
                   19022:21):     if (keys(%possibles)) {
                   19023:21):         my @posstiny = keys(%possibles);
                   19024:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19025:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19026:21):         if (keys(%currtiny)) {
                   19027:21):             foreach my $key (keys(%currtiny)) {
                   19028:21):                 next if ($currtiny{$key} eq '');
                   19029:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   19030:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19031:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19032:21):                         $courseonly->{$tsymb} = $key;
                   19033:21):                     }
                   19034:21):                 } else {
                   19035:21):                     $collisions{$possibles{$key}} = 1;
                   19036:21):                 }
                   19037:21):                 delete($possibles{$key});
                   19038:21):             }
                   19039:21):         }
                   19040:21):         foreach my $key (keys(%possibles)) {
                   19041:21):             $newunique->{$key} = $possibles{$key};
                   19042:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19043:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19044:21):                 $addcourse->{$tsymb} = $key;
                   19045:21):             }
                   19046:21):         }
                   19047:21):     }
                   19048:21):     if (keys(%collisions)) {
                   19049:21):         if ($init <5) {
                   19050:21):             if (!$init) {
                   19051:21):                 $init = 1;
                   19052:21):             } else {
                   19053:21):                 $init ++;
                   19054:21):             }
                   19055:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19056:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   19057:21):         } else {
                   19058:21):             foreach my $key (keys(%collisions)) {
                   19059:21):                 $failed->{$key} = 1;
                   19060:21):                 $failed->{$key} = 1;
                   19061:21):             }
                   19062:21):         }
                   19063:21):     }
                   19064:21):     return $init;
                   19065:21): }
                   19066:21): 
1.1075.2.135  raeburn  19067: sub is_nonframeable {
                   19068:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19069:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   19070:     return if (($remprotocol eq '') || ($remhost eq ''));
                   19071: 
                   19072:     $remprotocol = lc($remprotocol);
                   19073:     $remhost = lc($remhost);
                   19074:     my $remport = 80;
                   19075:     if ($remprotocol eq 'https') {
                   19076:         $remport = 443;
                   19077:     }
                   19078:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   19079:     if ($cached) {
                   19080:         unless ($nocache) {
                   19081:             if ($result) {
                   19082:                 return 1;
                   19083:             } else {
                   19084:                 return 0;
                   19085:             }
                   19086:         }
                   19087:     }
                   19088:     my $uselink;
                   19089:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  19090:     my $ua = LWP::UserAgent->new;
                   19091:     $ua->timeout(5);
                   19092:     my $response=$ua->request($request);
1.1075.2.135  raeburn  19093:     if ($response->is_success()) {
                   19094:         my $secpolicy = lc($response->header('content-security-policy'));
                   19095:         my $xframeop = lc($response->header('x-frame-options'));
                   19096:         $secpolicy =~ s/^\s+|\s+$//g;
                   19097:         $xframeop =~ s/^\s+|\s+$//g;
                   19098:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   19099:             my $remotehost = $remprotocol.'://'.$remhost;
                   19100:             my ($origin,$protocol,$port);
                   19101:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19102:                 $port = $ENV{'SERVER_PORT'};
                   19103:             } else {
                   19104:                 $port = 80;
                   19105:             }
                   19106:             if ($absolute eq '') {
                   19107:                 $protocol = 'http:';
                   19108:                 if ($port == 443) {
                   19109:                     $protocol = 'https:';
                   19110:                 }
                   19111:                 $origin = $protocol.'//'.lc($hostname);
                   19112:             } else {
                   19113:                 $origin = lc($absolute);
                   19114:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19115:             }
                   19116:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19117:                 my $framepolicy = $1;
                   19118:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19119:                 my @policies = split(/\s+/,$framepolicy);
                   19120:                 if (@policies) {
                   19121:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19122:                         $uselink = 1;
                   19123:                     } else {
                   19124:                         $uselink = 1;
                   19125:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19126:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19127:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19128:                             undef($uselink);
                   19129:                         }
                   19130:                         if ($uselink) {
                   19131:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19132:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19133:                                     undef($uselink);
                   19134:                                 }
                   19135:                             }
                   19136:                         }
                   19137:                         if ($uselink) {
                   19138:                             my @possok;
                   19139:                             if ($ip ne '') {
                   19140:                                 push(@possok,$ip);
                   19141:                             }
                   19142:                             my $hoststr = '';
                   19143:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19144:                                 if ($hoststr eq '') {
                   19145:                                     $hoststr = $part;
                   19146:                                 } else {
                   19147:                                     $hoststr = "$part.$hoststr";
                   19148:                                 }
                   19149:                                 if ($hoststr eq $hostname) {
                   19150:                                     push(@possok,$hostname);
                   19151:                                 } else {
                   19152:                                     push(@possok,"*.$hoststr");
                   19153:                                 }
                   19154:                             }
                   19155:                             if (@possok) {
                   19156:                                 foreach my $poss (@possok) {
                   19157:                                     last if (!$uselink);
                   19158:                                     foreach my $policy (@policies) {
                   19159:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19160:                                             undef($uselink);
                   19161:                                             last;
                   19162:                                         }
                   19163:                                     }
                   19164:                                 }
                   19165:                             }
                   19166:                         }
                   19167:                     }
                   19168:                 }
                   19169:             } elsif ($xframeop ne '') {
                   19170:                 $uselink = 1;
                   19171:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19172:                 if (@policies) {
                   19173:                     unless (grep(/^deny$/,@policies)) {
                   19174:                         if ($origin ne '') {
                   19175:                             if (grep(/^sameorigin$/,@policies)) {
                   19176:                                 if ($remotehost eq $origin) {
                   19177:                                     undef($uselink);
                   19178:                                 }
                   19179:                             }
                   19180:                             if ($uselink) {
                   19181:                                 foreach my $policy (@policies) {
                   19182:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19183:                                         my $allowfrom = $1;
                   19184:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19185:                                             undef($uselink);
                   19186:                                             last;
                   19187:                                         }
                   19188:                                     }
                   19189:                                 }
                   19190:                             }
                   19191:                         }
                   19192:                     }
                   19193:                 }
                   19194:             }
                   19195:         }
                   19196:     }
                   19197:     if ($nocache) {
                   19198:         if ($cached) {
                   19199:             my $devalidate;
                   19200:             if ($uselink && !$result) {
                   19201:                 $devalidate = 1;
                   19202:             } elsif (!$uselink && $result) {
                   19203:                 $devalidate = 1;
                   19204:             }
                   19205:             if ($devalidate) {
                   19206:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19207:             }
                   19208:         }
                   19209:     } else {
                   19210:         if ($uselink) {
                   19211:             $result = 1;
                   19212:         } else {
                   19213:             $result = 0;
                   19214:         }
                   19215:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19216:     }
                   19217:     return $uselink;
                   19218: }
                   19219: 
1.1075.2.161.  .1(raebu 19220:21): sub page_menu {
                   19221:21):     my ($menucolls,$menunum) = @_;
                   19222:21):     my %menu;
                   19223:21):     foreach my $item (split(/;/,$menucolls)) {
                   19224:21):         my ($num,$value) = split(/\%/,$item);
                   19225:21):         if ($num eq $menunum) {
                   19226:21):             my @entries = split(/\&/,$value);
                   19227:21):             foreach my $entry (@entries) {
                   19228:21):                 my ($name,$fields) = split(/=/,$entry);
                   19229:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   19230:21):                     $menu{$name} = $fields;
                   19231:21):                 } else {
                   19232:21):                     my @shown;
                   19233:21):                     if ($fields =~ /,/) {
                   19234:21):                         @shown = split(/,/,$fields);
                   19235:21):                     } else {
                   19236:21):                         @shown = ($fields);
                   19237:21):                     }
                   19238:21):                     if (@shown) {
                   19239:21):                         foreach my $field (@shown) {
                   19240:21):                             next if ($field eq '');
                   19241:21):                             $menu{$field} = 1;
                   19242:21):                         }
                   19243:21):                     }
                   19244:21):                 }
                   19245:21):             }
                   19246:21):         }
                   19247:21):     }
                   19248:21):     return %menu;
                   19249:21): }
                   19250:21): 
1.112     bowersj2 19251: 1;
                   19252: __END__;
1.41      ng       19253: 

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