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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1414  ! raeburn     4: # $Id: loncommon.pm,v 1.1413 2023/09/28 15:56:48 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.1383    raeburn    64: 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.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1409    raeburn    74: use LONCAPA::ltiutils;
1.1280    raeburn    75: use LONCAPA::LWPReq;
1.1395    raeburn    76: use LONCAPA::map();
1.1328    raeburn    77: use HTTP::Request;
1.657     raeburn    78: use DateTime::TimeZone;
1.1241    raeburn    79: use DateTime::Locale;
1.1220    raeburn    80: use Encode();
1.1091    foxr       81: use Text::Aspell;
1.1094    raeburn    82: use Authen::Captcha;
                     83: use Captcha::reCAPTCHA;
1.1234    raeburn    84: use JSON::DWIW;
1.1174    raeburn    85: use Crypt::DES;
                     86: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   87: use MIME::Lite;
                     88: use MIME::Types;
1.1292    raeburn    89: use File::Copy();
1.1300    raeburn    90: use File::Path();
1.1309    raeburn    91: use String::CRC32();
                     92: use Short::URL();
1.117     www        93: 
1.517     raeburn    94: # ---------------------------------------------- Designs
                     95: use vars qw(%defaultdesign);
                     96: 
1.22      www        97: my $readit;
                     98: 
1.517     raeburn    99: 
1.157     matthew   100: ##
                    101: ## Global Variables
                    102: ##
1.46      matthew   103: 
1.643     foxr      104: 
                    105: # ----------------------------------------------- SSI with retries:
                    106: #
                    107: 
                    108: =pod
                    109: 
1.648     raeburn   110: =head1 Server Side include with retries:
1.643     foxr      111: 
                    112: =over 4
                    113: 
1.648     raeburn   114: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      115: 
                    116: Performs an ssi with some number of retries.  Retries continue either
                    117: until the result is ok or until the retry count supplied by the
                    118: caller is exhausted.  
                    119: 
                    120: Inputs:
1.648     raeburn   121: 
                    122: =over 4
                    123: 
1.643     foxr      124: resource   - Identifies the resource to insert.
1.648     raeburn   125: 
1.643     foxr      126: retries    - Count of the number of retries allowed.
1.648     raeburn   127: 
1.643     foxr      128: form       - Hash that identifies the rendering options.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: Returns:
                    133: 
                    134: =over 4
                    135: 
1.643     foxr      136: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   137: 
1.643     foxr      138: response   - The response from the last attempt (which may or may not have been successful.
                    139: 
1.648     raeburn   140: =back
                    141: 
                    142: =back
                    143: 
1.643     foxr      144: =cut
                    145: 
                    146: sub ssi_with_retries {
                    147:     my ($resource, $retries, %form) = @_;
                    148: 
                    149: 
                    150:     my $ok = 0;			# True if we got a good response.
                    151:     my $content;
                    152:     my $response;
                    153: 
                    154:     # Try to get the ssi done. within the retries count:
                    155: 
                    156:     do {
                    157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    158: 	$ok      = $response->is_success;
1.650     www       159:         if (!$ok) {
                    160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    161:         }
1.643     foxr      162: 	$retries--;
                    163:     } while (!$ok && ($retries > 0));
                    164: 
                    165:     if (!$ok) {
                    166: 	$content = '';		# On error return an empty content.
                    167:     }
                    168:     return ($content, $response);
                    169: 
                    170: }
                    171: 
                    172: 
                    173: 
1.20      www       174: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  175: my %language;
1.124     www       176: my %supported_language;
1.1088    foxr      177: my %supported_codes;
1.1048    foxr      178: my %latex_language;		# For choosing hyphenation in <transl..>
                    179: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  180: my %cprtag;
1.192     taceyjo1  181: my %scprtag;
1.351     www       182: my %fe; my %fd; my %fm;
1.41      ng        183: my %category_extensions;
1.12      harris41  184: 
1.46      matthew   185: # ---------------------------------------------- Thesaurus variables
1.144     matthew   186: #
                    187: # %Keywords:
                    188: #      A hash used by &keyword to determine if a word is considered a keyword.
                    189: # $thesaurus_db_file 
                    190: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   191: 
                    192: my %Keywords;
                    193: my $thesaurus_db_file;
                    194: 
1.144     matthew   195: #
                    196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    197: # thesaurus.tab, and filecategories.tab.
                    198: #
1.18      www       199: BEGIN {
1.46      matthew   200:     # Variable initialization
                    201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    202:     #
1.22      www       203:     unless ($readit) {
1.12      harris41  204: # ------------------------------------------------------------------- languages
                    205:     {
1.158     raeburn   206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    207:                                    '/language.tab';
1.1317    raeburn   208:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  209:             while (my $line = <$fh>) {
                    210:                 next if ($line=~/^\#/);
                    211:                 chomp($line);
1.1088    foxr      212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   213:                 $language{$key}=$val.' - '.$enc;
                    214:                 if ($sup) {
                    215:                     $supported_language{$key}=$sup;
1.1088    foxr      216: 		    $supported_codes{$key}   = $code;
1.158     raeburn   217:                 }
1.1048    foxr      218: 		if ($latex) {
                    219: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      220: 		    $latex_language{$code} = $latex;
1.1048    foxr      221: 		}
1.158     raeburn   222:             }
                    223:             close($fh);
                    224:         }
1.12      harris41  225:     }
                    226: # ------------------------------------------------------------------ copyrights
                    227:     {
1.158     raeburn   228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    229:                                   '/copyright.tab';
1.1317    raeburn   230:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  231:             while (my $line = <$fh>) {
                    232:                 next if ($line=~/^\#/);
                    233:                 chomp($line);
                    234:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   235:                 $cprtag{$key}=$val;
                    236:             }
                    237:             close($fh);
                    238:         }
1.12      harris41  239:     }
1.351     www       240: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  241:     {
                    242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    243:                                   '/source_copyright.tab';
1.1317    raeburn   244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  245:             while (my $line = <$fh>) {
                    246:                 next if ($line =~ /^\#/);
                    247:                 chomp($line);
                    248:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  249:                 $scprtag{$key}=$val;
                    250:             }
                    251:             close($fh);
                    252:         }
                    253:     }
1.63      www       254: 
1.517     raeburn   255: # -------------------------------------------------------------- default domain designs
1.63      www       256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   257:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   258:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   259:         while (my $line = <$fh>) {
                    260:             next if ($line =~ /^\#/);
                    261:             chomp($line);
                    262:             my ($key,$val)=(split(/\=/,$line));
                    263:             if ($val) { $defaultdesign{$key}=$val; }
                    264:         }
                    265:         close($fh);
1.63      www       266:     }
                    267: 
1.15      harris41  268: # ------------------------------------------------------------- file categories
                    269:     {
1.158     raeburn   270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    271:                                   '/filecategories.tab';
1.1317    raeburn   272:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  273: 	    while (my $line = <$fh>) {
                    274: 		next if ($line =~ /^\#/);
                    275: 		chomp($line);
                    276:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   277:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   278:             }
                    279:             close($fh);
                    280:         }
                    281: 
1.15      harris41  282:     }
1.12      harris41  283: # ------------------------------------------------------------------ file types
                    284:     {
1.158     raeburn   285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    286:                '/filetypes.tab';
1.1317    raeburn   287:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  288:             while (my $line = <$fh>) {
                    289: 		next if ($line =~ /^\#/);
                    290: 		chomp($line);
                    291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   292:                 if ($descr ne '') {
                    293:                     $fe{$ending}=lc($emb);
                    294:                     $fd{$ending}=$descr;
1.351     www       295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   296:                 }
                    297:             }
                    298:             close($fh);
                    299:         }
1.12      harris41  300:     }
1.22      www       301:     &Apache::lonnet::logthis(
1.705     tempelho  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       303:     $readit=1;
1.46      matthew   304:     }  # end of unless($readit) 
1.32      matthew   305:     
                    306: }
1.112     bowersj2  307: 
1.42      matthew   308: ###############################################################
                    309: ##           HTML and Javascript Helper Functions            ##
                    310: ###############################################################
                    311: 
                    312: =pod 
                    313: 
1.112     bowersj2  314: =head1 HTML and Javascript Functions
1.42      matthew   315: 
1.112     bowersj2  316: =over 4
                    317: 
1.648     raeburn   318: =item * &browser_and_searcher_javascript()
1.112     bowersj2  319: 
                    320: X<browsing, javascript>X<searching, javascript>Returns a string
                    321: containing javascript with two functions, C<openbrowser> and
                    322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    323: tags.
1.42      matthew   324: 
1.648     raeburn   325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   326: 
                    327: inputs: formname, elementname, only, omit
                    328: 
                    329: formname and elementname indicate the name of the html form and name of
                    330: the element that the results of the browsing selection are to be placed in. 
                    331: 
                    332: Specifying 'only' will restrict the browser to displaying only files
1.185     www       333: with the given extension.  Can be a comma separated list.
1.42      matthew   334: 
                    335: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       336: with the given extension.  Can be a comma separated list.
1.42      matthew   337: 
1.648     raeburn   338: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   339: 
                    340: Inputs: formname, elementname
                    341: 
                    342: formname and elementname specify the name of the html form and the name
                    343: of the element the selection from the search results will be placed in.
1.542     raeburn   344: 
1.42      matthew   345: =cut
                    346: 
                    347: sub browser_and_searcher_javascript {
1.199     albertel  348:     my ($mode)=@_;
                    349:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  350:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   351:     return <<END;
1.219     albertel  352: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   353:     var editbrowser = null;
1.135     albertel  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       355:         var url = '$resurl/?';
1.42      matthew   356:         if (editbrowser == null) {
                    357:             url += 'launch=1&';
                    358:         }
                    359:         url += 'catalogmode=interactive&';
1.199     albertel  360:         url += 'mode=$mode&';
1.611     albertel  361:         url += 'inhibitmenu=yes&';
1.42      matthew   362:         url += 'form=' + formname + '&';
                    363:         if (only != null) {
                    364:             url += 'only=' + only + '&';
1.217     albertel  365:         } else {
                    366:             url += 'only=&';
                    367: 	}
1.42      matthew   368:         if (omit != null) {
                    369:             url += 'omit=' + omit + '&';
1.217     albertel  370:         } else {
                    371:             url += 'omit=&';
                    372: 	}
1.135     albertel  373:         if (titleelement != null) {
                    374:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  375:         } else {
                    376: 	    url += 'titleelement=&';
                    377: 	}
1.42      matthew   378:         url += 'element=' + elementname + '';
                    379:         var title = 'Browser';
1.435     albertel  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   381:         options += ',width=700,height=600';
                    382:         editbrowser = open(url,title,options,'1');
                    383:         editbrowser.focus();
                    384:     }
                    385:     var editsearcher;
1.135     albertel  386:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   387:         var url = '/adm/searchcat?';
                    388:         if (editsearcher == null) {
                    389:             url += 'launch=1&';
                    390:         }
                    391:         url += 'catalogmode=interactive&';
1.199     albertel  392:         url += 'mode=$mode&';
1.42      matthew   393:         url += 'form=' + formname + '&';
1.135     albertel  394:         if (titleelement != null) {
                    395:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  396:         } else {
                    397: 	    url += 'titleelement=&';
                    398: 	}
1.42      matthew   399:         url += 'element=' + elementname + '';
                    400:         var title = 'Search';
1.435     albertel  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   402:         options += ',width=700,height=600';
                    403:         editsearcher = open(url,title,options,'1');
                    404:         editsearcher.focus();
                    405:     }
1.219     albertel  406: // END LON-CAPA Internal -->
1.42      matthew   407: END
1.170     www       408: }
                    409: 
                    410: sub lastresurl {
1.258     albertel  411:     if ($env{'environment.lastresurl'}) {
                    412: 	return $env{'environment.lastresurl'}
1.170     www       413:     } else {
                    414: 	return '/res';
                    415:     }
                    416: }
                    417: 
                    418: sub storeresurl {
                    419:     my $resurl=&Apache::lonnet::clutter(shift);
                    420:     unless ($resurl=~/^\/res/) { return 0; }
                    421:     $resurl=~s/\/$//;
                    422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       424:     return 1;
1.42      matthew   425: }
                    426: 
1.74      www       427: sub studentbrowser_javascript {
1.111     www       428:    unless (
1.258     albertel  429:             (($env{'request.course.id'}) && 
1.302     albertel  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    432: 					  '/'.$env{'request.course.sec'})
                    433: 	      ))
1.258     albertel  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       435:           ) { return ''; }  
1.74      www       436:    return (<<'ENDSTDBRW');
1.776     bisitz    437: <script type="text/javascript" language="Javascript">
1.824     bisitz    438: // <![CDATA[
1.74      www       439:     var stdeditbrowser;
1.1413    raeburn   440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       441:         var url = '/adm/pickstudent?';
                    442:         var filter;
1.558     albertel  443: 	if (!ignorefilter) {
                    444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    445: 	}
1.74      www       446:         if (filter != null) {
                    447:            if (filter != '') {
                    448:                url += 'filter='+filter+'&';
                    449: 	   }
                    450:         }
                    451:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       452:                                     '&udomelement='+udom+
                    453:                                     '&clicker='+clicker;
1.111     www       454: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   455:         if (courseadv == 'condition') {
                    456:             if (document.getElementById('courseadv')) {
                    457:                 courseadv = document.getElementById('courseadv').value;
                    458:             }
                    459:         }
                    460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1413    raeburn   461:         if (uident !== '') { url+="&identelement="+uident; } 
1.102     www       462:         var title = 'Student_Browser';
1.74      www       463:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    464:         options += ',width=700,height=600';
                    465:         stdeditbrowser = open(url,title,options,'1');
                    466:         stdeditbrowser.focus();
                    467:     }
1.824     bisitz    468: // ]]>
1.74      www       469: </script>
                    470: ENDSTDBRW
                    471: }
1.42      matthew   472: 
1.1003    www       473: sub resourcebrowser_javascript {
                    474:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       475:    return (<<'ENDRESBRW');
1.1003    www       476: <script type="text/javascript" language="Javascript">
                    477: // <![CDATA[
                    478:     var reseditbrowser;
1.1004    www       479:     function openresbrowser(formname,reslink) {
1.1005    www       480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       481:         var title = 'Resource_Browser';
                    482:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       483:         options += ',width=700,height=500';
1.1004    www       484:         reseditbrowser = open(url,title,options,'1');
                    485:         reseditbrowser.focus();
1.1003    www       486:     }
                    487: // ]]>
                    488: </script>
1.1004    www       489: ENDRESBRW
1.1003    www       490: }
                    491: 
1.74      www       492: sub selectstudent_link {
1.1413    raeburn   493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  497:    if ($env{'request.course.id'}) {  
1.302     albertel  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    500: 					'/'.$env{'request.course.sec'})) {
1.111     www       501: 	   return '';
                    502:        }
1.999     www       503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   504:        if ($courseadv eq 'only') {
                    505:            $callargs .= ",'',1,'$courseadv'";
                    506:        } elsif ($courseadv eq 'none') {
                    507:            $callargs .= ",'','','$courseadv'";
                    508:        } elsif ($courseadv eq 'condition') {
                    509:            $callargs .= ",'','','$courseadv'";
1.1413    raeburn   510:        } elsif ($identelem ne '') {
                    511:            $callargs .= ",'','',''";
                    512:        }
                    513:        if ($identelem ne '') {
                    514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   515:        }
                    516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.74      www       519:    }
1.258     albertel  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       521:        $callargs .= ",'',1"; 
1.793     raeburn   522:        return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    524:               &mt('Select User').'</a></span>';
1.111     www       525:    }
                    526:    return '';
1.91      www       527: }
                    528: 
1.1004    www       529: sub selectresource_link {
                    530:    my ($form,$reslink,$arg)=@_;
                    531:    
                    532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    534:    unless ($env{'request.course.id'}) { return $arg; }
                    535:    return '<span class="LC_nobreak">'.
                    536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    537:               $arg.'</a></span>';
                    538: }
                    539: 
                    540: 
                    541: 
1.653     raeburn   542: sub authorbrowser_javascript {
                    543:     return <<"ENDAUTHORBRW";
1.776     bisitz    544: <script type="text/javascript" language="JavaScript">
1.824     bisitz    545: // <![CDATA[
1.653     raeburn   546: var stdeditbrowser;
                    547: 
                    548: function openauthorbrowser(formname,udom) {
                    549:     var url = '/adm/pickauthor?';
                    550:     url += 'form='+formname+'&roledom='+udom;
                    551:     var title = 'Author_Browser';
                    552:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    553:     options += ',width=700,height=600';
                    554:     stdeditbrowser = open(url,title,options,'1');
                    555:     stdeditbrowser.focus();
                    556: }
                    557: 
1.824     bisitz    558: // ]]>
1.653     raeburn   559: </script>
                    560: ENDAUTHORBRW
                    561: }
                    562: 
1.91      www       563: sub coursebrowser_javascript {
1.1116    raeburn   564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   565:         $credits_element,$instcode) = @_;
1.932     raeburn   566:     my $wintitle = 'Course_Browser';
1.931     raeburn   567:     if ($crstype eq 'Community') {
1.932     raeburn   568:         $wintitle = 'Community_Browser';
1.909     raeburn   569:     }
1.876     raeburn   570:     my $id_functions = &javascript_index_functions();
                    571:     my $output = '
1.776     bisitz    572: <script type="text/javascript" language="JavaScript">
1.824     bisitz    573: // <![CDATA[
1.468     raeburn   574:     var stdeditbrowser;'."\n";
1.876     raeburn   575: 
                    576:     $output .= <<"ENDSTDBRW";
1.909     raeburn   577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       578:         var url = '/adm/pickcourse?';
1.895     raeburn   579:         var formid = getFormIdByName(formname);
1.876     raeburn   580:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  581:         if (domainfilter != null) {
                    582:            if (domainfilter != '') {
                    583:                url += 'domainfilter='+domainfilter+'&';
                    584: 	   }
                    585:         }
1.91      www       586:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  587: 	                            '&cdomelement='+udom+
                    588:                                     '&cnameelement='+desc;
1.468     raeburn   589:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   590:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   591:                 url += '&roleelement='+extra_element;
                    592:                 if (domainfilter == null || domainfilter == '') {
                    593:                     url += '&domainfilter='+extra_element;
                    594:                 }
1.234     raeburn   595:             }
1.468     raeburn   596:             else {
                    597:                 if (formname == 'portform') {
                    598:                     url += '&setroles='+extra_element;
1.800     raeburn   599:                 } else {
                    600:                     if (formname == 'rules') {
                    601:                         url += '&fixeddom='+extra_element; 
                    602:                     }
1.468     raeburn   603:                 }
                    604:             }     
1.230     raeburn   605:         }
1.909     raeburn   606:         if (type != null && type != '') {
                    607:             url += '&type='+type;
                    608:         }
                    609:         if (type_elem != null && type_elem != '') {
                    610:             url += '&typeelement='+type_elem;
                    611:         }
1.872     raeburn   612:         if (formname == 'ccrs') {
                    613:             var ownername = document.forms[formid].ccuname.value;
                    614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   615:             url += '&cloner='+ownername+':'+ownerdom;
                    616:             if (type == 'Course') {
                    617:                 url += '&crscode='+document.forms[formid].crscode.value;
                    618:             }
1.1221    raeburn   619:         }
                    620:         if (formname == 'requestcrs') {
                    621:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   622:         }
1.293     raeburn   623:         if (multflag !=null && multflag != '') {
                    624:             url += '&multiple='+multflag;
                    625:         }
1.909     raeburn   626:         var title = '$wintitle';
1.91      www       627:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    628:         options += ',width=700,height=600';
                    629:         stdeditbrowser = open(url,title,options,'1');
                    630:         stdeditbrowser.focus();
                    631:     }
1.876     raeburn   632: $id_functions
                    633: ENDSTDBRW
1.1116    raeburn   634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    636:                                       $credits_element);
1.876     raeburn   637:     }
                    638:     $output .= '
                    639: // ]]>
                    640: </script>';
                    641:     return $output;
                    642: }
                    643: 
                    644: sub javascript_index_functions {
                    645:     return <<"ENDJS";
                    646: 
                    647: function getFormIdByName(formname) {
                    648:     for (var i=0;i<document.forms.length;i++) {
                    649:         if (document.forms[i].name == formname) {
                    650:             return i;
                    651:         }
                    652:     }
                    653:     return -1;
                    654: }
                    655: 
                    656: function getIndexByName(formid,item) {
                    657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    658:         if (document.forms[formid].elements[i].name == item) {
                    659:             return i;
                    660:         }
                    661:     }
                    662:     return -1;
                    663: }
1.468     raeburn   664: 
1.876     raeburn   665: function getDomainFromSelectbox(formname,udom) {
                    666:     var userdom;
                    667:     var formid = getFormIdByName(formname);
                    668:     if (formid > -1) {
                    669:         var domid = getIndexByName(formid,udom);
                    670:         if (domid > -1) {
                    671:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    673:             }
                    674:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    675:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   676:             }
                    677:         }
                    678:     }
1.876     raeburn   679:     return userdom;
                    680: }
                    681: 
                    682: ENDJS
1.468     raeburn   683: 
1.876     raeburn   684: }
                    685: 
1.1017    raeburn   686: sub javascript_array_indexof {
1.1018    raeburn   687:     return <<ENDJS;
1.1017    raeburn   688: <script type="text/javascript" language="JavaScript">
                    689: // <![CDATA[
                    690: 
                    691: if (!Array.prototype.indexOf) {
                    692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    693:         "use strict";
                    694:         if (this === void 0 || this === null) {
                    695:             throw new TypeError();
                    696:         }
                    697:         var t = Object(this);
                    698:         var len = t.length >>> 0;
                    699:         if (len === 0) {
                    700:             return -1;
                    701:         }
                    702:         var n = 0;
                    703:         if (arguments.length > 0) {
                    704:             n = Number(arguments[1]);
1.1088    foxr      705:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   706:                 n = 0;
                    707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    709:             }
                    710:         }
                    711:         if (n >= len) {
                    712:             return -1;
                    713:         }
                    714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    715:         for (; k < len; k++) {
                    716:             if (k in t && t[k] === searchElement) {
                    717:                 return k;
                    718:             }
                    719:         }
                    720:         return -1;
                    721:     }
                    722: }
                    723: 
                    724: // ]]>
                    725: </script>
                    726: 
                    727: ENDJS
                    728: 
                    729: }
                    730: 
1.876     raeburn   731: sub userbrowser_javascript {
                    732:     my $id_functions = &javascript_index_functions();
                    733:     return <<"ENDUSERBRW";
                    734: 
1.888     raeburn   735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   736:     var url = '/adm/pickuser?';
                    737:     var userdom = getDomainFromSelectbox(formname,udom);
                    738:     if (userdom != null) {
                    739:        if (userdom != '') {
                    740:            url += 'srchdom='+userdom+'&';
                    741:        }
                    742:     }
                    743:     url += 'form=' + formname + '&unameelement='+uname+
                    744:                                 '&udomelement='+udom+
                    745:                                 '&ulastelement='+ulast+
                    746:                                 '&ufirstelement='+ufirst+
                    747:                                 '&uemailelement='+uemail+
1.881     raeburn   748:                                 '&hideudomelement='+hideudom+
                    749:                                 '&coursedom='+crsdom;
1.888     raeburn   750:     if ((caller != null) && (caller != undefined)) {
                    751:         url += '&caller='+caller;
                    752:     }
1.876     raeburn   753:     var title = 'User_Browser';
                    754:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    755:     options += ',width=700,height=600';
                    756:     var stdeditbrowser = open(url,title,options,'1');
                    757:     stdeditbrowser.focus();
                    758: }
                    759: 
1.888     raeburn   760: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   761:     var formid = getFormIdByName(formname);
                    762:     if (formid > -1) {
1.888     raeburn   763:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   764:         var domid = getIndexByName(formid,udom);
                    765:         var hidedomid = getIndexByName(formid,origdom);
                    766:         if (hidedomid > -1) {
                    767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   768:             var unameval = document.forms[formid].elements[unameid].value;
                    769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    770:                 if (domid > -1) {
                    771:                     var slct = document.forms[formid].elements[domid];
                    772:                     if (slct.type == 'select-one') {
                    773:                         var i;
                    774:                         for (i=0;i<slct.length;i++) {
                    775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    776:                         }
                    777:                     }
                    778:                     if (slct.type == 'hidden') {
                    779:                         slct.value = fixeddom;
1.876     raeburn   780:                     }
                    781:                 }
1.468     raeburn   782:             }
                    783:         }
                    784:     }
1.876     raeburn   785:     return;
                    786: }
                    787: 
                    788: $id_functions
                    789: ENDUSERBRW
1.468     raeburn   790: }
                    791: 
                    792: sub setsec_javascript {
1.1116    raeburn   793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    795:         $communityrolestr);
                    796:     if ($role_element ne '') {
                    797:         my @allroles = ('st','ta','ep','in','ad');
                    798:         foreach my $crstype ('Course','Community') {
                    799:             if ($crstype eq 'Community') {
                    800:                 foreach my $role (@allroles) {
                    801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    802:                 }
                    803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    804:             } else {
                    805:                 foreach my $role (@allroles) {
                    806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    807:                 }
                    808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    809:             }
                    810:         }
                    811:         $rolestr = '"'.join('","',@allroles).'"';
                    812:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    814:     }
1.468     raeburn   815:     my $setsections = qq|
                    816: function setSect(sectionlist) {
1.629     raeburn   817:     var sectionsArray = new Array();
                    818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    819:         sectionsArray = sectionlist.split(",");
                    820:     }
1.468     raeburn   821:     var numSections = sectionsArray.length;
                    822:     document.$formname.$sec_element.length = 0;
                    823:     if (numSections == 0) {
                    824:         document.$formname.$sec_element.multiple=false;
                    825:         document.$formname.$sec_element.size=1;
                    826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    827:     } else {
                    828:         if (numSections == 1) {
                    829:             document.$formname.$sec_element.multiple=false;
                    830:             document.$formname.$sec_element.size=1;
                    831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    834:         } else {
                    835:             for (var i=0; i<numSections; i++) {
                    836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    837:             }
                    838:             document.$formname.$sec_element.multiple=true
                    839:             if (numSections < 3) {
                    840:                 document.$formname.$sec_element.size=numSections;
                    841:             } else {
                    842:                 document.$formname.$sec_element.size=3;
                    843:             }
                    844:             document.$formname.$sec_element.options[0].selected = false
                    845:         }
                    846:     }
1.91      www       847: }
1.905     raeburn   848: 
                    849: function setRole(crstype) {
1.468     raeburn   850: |;
1.905     raeburn   851:     if ($role_element eq '') {
                    852:         $setsections .= '    return;
                    853: }
                    854: ';
                    855:     } else {
                    856:         $setsections .= qq|
                    857:     var elementLength = document.$formname.$role_element.length;
                    858:     var allroles = Array($rolestr);
                    859:     var courserolenames = Array($courserolestr);
                    860:     var communityrolenames = Array($communityrolestr);
                    861:     if (elementLength != undefined) {
                    862:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    863:             if (crstype == 'Course') {
                    864:                 return;
                    865:             } else {
                    866:                 allroles[5] = 'co';
                    867:                 for (var i=0; i<6; i++) {
                    868:                     document.$formname.$role_element.options[i].value = allroles[i];
                    869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    870:                 }
                    871:             }
                    872:         } else {
                    873:             if (crstype == 'Community') {
                    874:                 return;
                    875:             } else {
                    876:                 allroles[5] = 'cc';
                    877:                 for (var i=0; i<6; i++) {
                    878:                     document.$formname.$role_element.options[i].value = allroles[i];
                    879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    880:                 }
                    881:             }
                    882:         }
                    883:     }
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.1116    raeburn   888:     if ($credits_element) {
                    889:         $setsections .= qq|
                    890: function setCredits(defaultcredits) {
                    891:     document.$formname.$credits_element.value = defaultcredits;
                    892:     return;
                    893: }
                    894: |;
                    895:     }
1.468     raeburn   896:     return $setsections;
                    897: }
                    898: 
1.91      www       899: sub selectcourse_link {
1.909     raeburn   900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    901:        $typeelement) = @_;
                    902:    my $type = $selecttype;
1.871     raeburn   903:    my $linktext = &mt('Select Course');
                    904:    if ($selecttype eq 'Community') {
1.909     raeburn   905:        $linktext = &mt('Select Community');
1.1239    raeburn   906:    } elsif ($selecttype eq 'Placement') {
                    907:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   908:    } elsif ($selecttype eq 'Course/Community') {
                    909:        $linktext = &mt('Select Course/Community');
1.909     raeburn   910:        $type = '';
1.1019    raeburn   911:    } elsif ($selecttype eq 'Select') {
                    912:        $linktext = &mt('Select');
                    913:        $type = '';
1.871     raeburn   914:    }
1.787     bisitz    915:    return '<span class="LC_nobreak">'
                    916:          ."<a href='"
                    917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   920:          ."'>".$linktext.'</a>'
1.787     bisitz    921:          .'</span>';
1.74      www       922: }
1.42      matthew   923: 
1.653     raeburn   924: sub selectauthor_link {
                    925:    my ($form,$udom)=@_;
                    926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    927:           &mt('Select Author').'</a>';
                    928: }
                    929: 
1.876     raeburn   930: sub selectuser_link {
1.881     raeburn   931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   932:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   935:            ');">'.$linktext.'</a>';
1.876     raeburn   936: }
                    937: 
1.273     raeburn   938: sub check_uncheck_jscript {
                    939:     my $jscript = <<"ENDSCRT";
                    940: function checkAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   943:             if (!field[i].disabled) { 
                    944:                 field[i].checked = true;
                    945:             }
1.273     raeburn   946:         }
                    947:     } else {
1.1093    raeburn   948:         if (!field.disabled) { 
                    949:             field.checked = true;
                    950:         }
1.273     raeburn   951:     }
                    952: }
                    953:  
                    954: function uncheckAll(field) {
                    955:     if (field.length > 0) {
                    956:         for (i = 0; i < field.length; i++) {
                    957:             field[i].checked = false ;
1.543     albertel  958:         }
                    959:     } else {
1.273     raeburn   960:         field.checked = false ;
                    961:     }
                    962: }
                    963: ENDSCRT
                    964:     return $jscript;
                    965: }
                    966: 
1.656     www       967: sub select_timezone {
1.1387    raeburn   968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   970:    if ($includeempty) {
                    971:        $output .= '<option value=""';
                    972:        if (($selected eq '') || ($selected eq 'local')) {
                    973:            $output .= ' selected="selected" ';
                    974:        }
                    975:        $output .= '> </option>';
                    976:    }
1.657     raeburn   977:    my @timezones = DateTime::TimeZone->all_names;
                    978:    foreach my $tzone (@timezones) {
                    979:        $output.= '<option value="'.$tzone.'"';
                    980:        if ($tzone eq $selected) {
                    981:            $output.=' selected="selected"';
                    982:        }
                    983:        $output.=">$tzone</option>\n";
1.656     www       984:    }
                    985:    $output.="</select>";
                    986:    return $output;
                    987: }
1.273     raeburn   988: 
1.687     raeburn   989: sub select_datelocale {
1.1256    raeburn   990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   992:     if ($includeempty) {
                    993:         $output .= '<option value=""';
                    994:         if ($selected eq '') {
                    995:             $output .= ' selected="selected" ';
                    996:         }
                    997:         $output .= '> </option>';
                    998:     }
1.1241    raeburn   999:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn  1000:     my (@possibles,%locale_names);
1.1241    raeburn  1001:     my @locales = DateTime::Locale->ids();
                   1002:     foreach my $id (@locales) {
                   1003:         if ($id ne '') {
                   1004:             my ($en_terr,$native_terr);
                   1005:             my $loc = DateTime::Locale->load($id);
                   1006:             if (ref($loc)) {
                   1007:                 $en_terr = $loc->name();
                   1008:                 $native_terr = $loc->native_name();
1.687     raeburn  1009:                 if (grep(/^en$/,@languages) || !@languages) {
                   1010:                     if ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     } elsif ($native_terr ne '') {
                   1013:                         $locale_names{$id} = $native_terr;
                   1014:                     }
                   1015:                 } else {
                   1016:                     if ($native_terr ne '') {
                   1017:                         $locale_names{$id} = $native_terr.' ';
                   1018:                     } elsif ($en_terr ne '') {
                   1019:                         $locale_names{$id} = '('.$en_terr.')';
                   1020:                     }
                   1021:                 }
1.1220    raeburn  1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1023:                 push(@possibles,$id);
                   1024:             } 
1.687     raeburn  1025:         }
                   1026:     }
                   1027:     foreach my $item (sort(@possibles)) {
                   1028:         $output.= '<option value="'.$item.'"';
                   1029:         if ($item eq $selected) {
                   1030:             $output.=' selected="selected"';
                   1031:         }
                   1032:         $output.=">$item";
                   1033:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1034:             $output.='  '.$locale_names{$item};
1.687     raeburn  1035:         }
                   1036:         $output.="</option>\n";
                   1037:     }
                   1038:     $output.="</select>";
                   1039:     return $output;
                   1040: }
                   1041: 
1.792     raeburn  1042: sub select_language {
1.1256    raeburn  1043:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1044:     my %langchoices;
                   1045:     if ($includeempty) {
1.1117    raeburn  1046:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1047:     }
                   1048:     foreach my $id (&languageids()) {
                   1049:         my $code = &supportedlanguagecode($id);
                   1050:         if ($code) {
                   1051:             $langchoices{$code} = &plainlanguagedescription($id);
                   1052:         }
                   1053:     }
1.1117    raeburn  1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1056: }
                   1057: 
1.42      matthew  1058: =pod
1.36      matthew  1059: 
1.1088    foxr     1060: 
                   1061: =item * &list_languages()
                   1062: 
                   1063: Returns an array reference that is suitable for use in language prompters.
                   1064: Each array element is itself a two element array.  The first element
                   1065: is the language code.  The second element a descsriptiuon of the 
                   1066: language itself.  This is suitable for use in e.g.
                   1067: &Apache::edit::select_arg (once dereferenced that is).
                   1068: 
                   1069: =cut 
                   1070: 
                   1071: sub list_languages {
                   1072:     my @lang_choices;
                   1073: 
                   1074:     foreach my $id (&languageids()) {
                   1075: 	my $code = &supportedlanguagecode($id);
                   1076: 	if ($code) {
                   1077: 	    my $selector    = $supported_codes{$id};
                   1078: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1079: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1080: 	}
                   1081:     }
                   1082:     return \@lang_choices;
                   1083: }
                   1084: 
                   1085: =pod
                   1086: 
1.648     raeburn  1087: =item * &linked_select_forms(...)
1.36      matthew  1088: 
                   1089: linked_select_forms returns a string containing a <script></script> block
                   1090: and html for two <select> menus.  The select menus will be linked in that
                   1091: changing the value of the first menu will result in new values being placed
                   1092: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1093: order unless a defined order is provided.
1.36      matthew  1094: 
                   1095: linked_select_forms takes the following ordered inputs:
                   1096: 
                   1097: =over 4
                   1098: 
1.112     bowersj2 1099: =item * $formname, the name of the <form> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1102: 
1.112     bowersj2 1103: =item * $firstdefault, the default value for the first menu
1.36      matthew  1104: 
1.112     bowersj2 1105: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1106: 
1.112     bowersj2 1107: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1108: 
1.112     bowersj2 1109: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1110: 
1.609     raeburn  1111: =item * $menuorder, the order of values in the first menu
                   1112: 
1.1115    raeburn  1113: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1114:         event for the first <select> tag
                   1115: 
                   1116: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1117:         event for the second <select> tag
                   1118: 
1.1245    raeburn  1119: =item * $suffix, to differentiate separate uses of select2data javascript
                   1120:         objects in a page.
                   1121: 
1.41      ng       1122: =back 
                   1123: 
1.36      matthew  1124: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1126: values for the first select menu.  The text that coincides with the 
1.41      ng       1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1128: and text for the second menu are given in the hash pointed to by 
                   1129: $menu{$choice1}->{'select2'}.  
                   1130: 
1.112     bowersj2 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1132:                        default => "B3",
                   1133:                        select2 => { 
                   1134:                            B1 => "Choice B1",
                   1135:                            B2 => "Choice B2",
                   1136:                            B3 => "Choice B3",
                   1137:                            B4 => "Choice B4"
1.609     raeburn  1138:                            },
                   1139:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1140:                    },
                   1141:                A2 => { text =>"Choice A2" ,
                   1142:                        default => "C2",
                   1143:                        select2 => { 
                   1144:                            C1 => "Choice C1",
                   1145:                            C2 => "Choice C2",
                   1146:                            C3 => "Choice C3"
1.609     raeburn  1147:                            },
                   1148:                        order => ['C2','C1','C3'],
1.112     bowersj2 1149:                    },
                   1150:                A3 => { text =>"Choice A3" ,
                   1151:                        default => "D6",
                   1152:                        select2 => { 
                   1153:                            D1 => "Choice D1",
                   1154:                            D2 => "Choice D2",
                   1155:                            D3 => "Choice D3",
                   1156:                            D4 => "Choice D4",
                   1157:                            D5 => "Choice D5",
                   1158:                            D6 => "Choice D6",
                   1159:                            D7 => "Choice D7"
1.609     raeburn  1160:                            },
                   1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1162:                    }
                   1163:                );
1.36      matthew  1164: 
                   1165: =cut
                   1166: 
                   1167: sub linked_select_forms {
                   1168:     my ($formname,
                   1169:         $middletext,
                   1170:         $firstdefault,
                   1171:         $firstselectname,
                   1172:         $secondselectname, 
1.609     raeburn  1173:         $hashref,
                   1174:         $menuorder,
1.1115    raeburn  1175:         $onchangefirst,
1.1245    raeburn  1176:         $onchangesecond,
                   1177:         $suffix
1.36      matthew  1178:         ) = @_;
                   1179:     my $second = "document.$formname.$secondselectname";
                   1180:     my $first = "document.$formname.$firstselectname";
                   1181:     # output the javascript to do the changing
                   1182:     my $result = '';
1.776     bisitz   1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1184:     $result.="// <![CDATA[\n";
1.1245    raeburn  1185:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1186:     $" = '","';
                   1187:     my $debug = '';
                   1188:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1191:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1195:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1196:         }
1.36      matthew  1197:         $result.="\"@s2values\");\n";
1.1245    raeburn  1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1199:         my @s2texts;
                   1200:         foreach my $value (@s2values) {
1.1263    raeburn  1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1202:         }
                   1203:         $result.="\"@s2texts\");\n";
                   1204:     }
                   1205:     $"=' ';
                   1206:     $result.= <<"END";
                   1207: 
1.1245    raeburn  1208: function select1${suffix}_changed() {
1.36      matthew  1209:     // Determine new choice
1.1245    raeburn  1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1211:     // update select2
1.1245    raeburn  1212:     var values     = select2data${suffix}[newvalue].values;
                   1213:     var texts      = select2data${suffix}[newvalue].texts;
                   1214:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1215:     var i;
                   1216:     // out with the old
1.1245    raeburn  1217:     $second.options.length = 0;
                   1218:     // in with the new
1.36      matthew  1219:     for (i=0;i<values.length; i++) {
                   1220:         $second.options[i] = new Option(values[i]);
1.143     matthew  1221:         $second.options[i].value = values[i];
1.36      matthew  1222:         $second.options[i].text = texts[i];
                   1223:         if (values[i] == select2def) {
                   1224:             $second.options[i].selected = true;
                   1225:         }
                   1226:     }
                   1227: }
1.824     bisitz   1228: // ]]>
1.36      matthew  1229: </script>
                   1230: END
                   1231:     # output the initial values for the selection lists
1.1245    raeburn  1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1233:     my @order = sort(keys(%{$hashref}));
                   1234:     if (ref($menuorder) eq 'ARRAY') {
                   1235:         @order = @{$menuorder};
                   1236:     }
                   1237:     foreach my $value (@order) {
1.36      matthew  1238:         $result.="    <option value=\"$value\" ";
1.253     albertel 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1241:     }
                   1242:     $result .= "</select>\n";
1.1400    raeburn  1243:     my %select2;
                   1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1247:         }
                   1248:     }
1.36      matthew  1249:     $result .= $middletext;
1.1115    raeburn  1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1251:     if ($onchangesecond) {
                   1252:         $result .= ' onchange="'.$onchangesecond.'"';
                   1253:     }
                   1254:     $result .= ">\n";
1.36      matthew  1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1256:     
                   1257:     my @secondorder = sort(keys(%select2));
                   1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1260:     }
                   1261:     foreach my $value (@secondorder) {
1.36      matthew  1262:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1264:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1265:     }
                   1266:     $result .= "</select>\n";
                   1267:     #    return $debug;
                   1268:     return $result;
                   1269: }   #  end of sub linked_select_forms {
                   1270: 
1.45      matthew  1271: =pod
1.44      bowersj2 1272: 
1.1381    raeburn  1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1274: 
1.112     bowersj2 1275: Returns a string corresponding to an HTML link to the given help
                   1276: $topic, where $topic corresponds to the name of a .tex file in
                   1277: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1278: spaces. 
                   1279: 
                   1280: $text will optionally be linked to the same topic, allowing you to
                   1281: link text in addition to the graphic. If you do not want to link
                   1282: text, but wish to specify one of the later parameters, pass an
                   1283: empty string. 
                   1284: 
                   1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1286: the link will not open a new window. If false, the link will open
                   1287: a new window using Javascript. (Default is false.) 
                   1288: 
                   1289: $width and $height are optional numerical parameters that will
                   1290: override the width and height of the popped up window, which may
1.973     raeburn  1291: be useful for certain help topics with big pictures included.
                   1292: 
                   1293: $imgid is the id of the img tag used for the help icon. This may be
                   1294: used in a javascript call to switch the image src.  See 
                   1295: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1296: 
1.1381    raeburn  1297: $links_target will optionally be set to a target (_top, _parent or _self).
                   1298: 
1.44      bowersj2 1299: =cut
                   1300: 
                   1301: sub help_open_topic {
1.1381    raeburn  1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1303:     $text = "" if (not defined $text);
1.44      bowersj2 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1305:     $width = 500 if (not defined $width);
1.44      bowersj2 1306:     $height = 400 if (not defined $height);
                   1307:     my $filename = $topic;
                   1308:     $filename =~ s/ /_/g;
                   1309: 
1.48      bowersj2 1310:     my $template = "";
                   1311:     my $link;
1.572     banghart 1312:     
1.159     www      1313:     $topic=~s/\W/\_/g;
1.44      bowersj2 1314: 
1.572     banghart 1315:     if (!$stayOnPage) {
1.1033    www      1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1317:     } elsif ($stayOnPage eq 'popup') {
                   1318:         $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 1319:     } else {
1.48      bowersj2 1320: 	$link = "/adm/help/${filename}.hlp";
                   1321:     }
                   1322: 
                   1323:     # Add the text
1.1314    raeburn  1324:     my $target = ' target="_top"';
1.1381    raeburn  1325:     if ($links_target) {
                   1326:         $target = ' target="'.$links_target.'"';
                   1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1329:         $target = '';
1.1378    raeburn  1330:     }
1.1380    raeburn  1331:     if ($text ne "") {
1.763     bisitz   1332: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1333:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1334:                   .$text.'</a>';
1.48      bowersj2 1335:     }
                   1336: 
1.763     bisitz   1337:     # (Always) Add the graphic
1.179     matthew  1338:     my $title = &mt('Online Help');
1.667     raeburn  1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1340:     if ($imgid ne '') {
                   1341:         $imgid = ' id="'.$imgid.'"';
                   1342:     }
1.1314    raeburn  1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1344:               .'<img src="'.$helpicon.'" border="0"'
                   1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1347:               .' /></a>';
                   1348:     if ($text ne "") {	
                   1349:         $template.='</span>';
                   1350:     }
1.44      bowersj2 1351:     return $template;
                   1352: 
1.106     bowersj2 1353: }
                   1354: 
                   1355: # This is a quicky function for Latex cheatsheet editing, since it 
                   1356: # appears in at least four places
                   1357: sub helpLatexCheatsheet {
1.1037    www      1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1359:     my $out;
1.106     bowersj2 1360:     my $addOther = '';
1.732     raeburn  1361:     if ($topic) {
1.1037    www      1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1363:     }
                   1364:     $out = '<span>' # Start cheatsheet
                   1365: 	  .$addOther
                   1366:           .'<span>'
1.1037    www      1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1368: 	  .'</span> <span>'
1.1037    www      1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1370: 	  .'</span>';
1.732     raeburn  1371:     unless ($not_author) {
1.1186    kruse    1372:         $out .= '<span>'
                   1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1374:                .'</span> <span>'
                   1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1376: 	       .'</span>';
1.732     raeburn  1377:     }
1.763     bisitz   1378:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1379:     return $out;
1.172     www      1380: }
                   1381: 
1.430     albertel 1382: sub general_help {
                   1383:     my $helptopic='Student_Intro';
                   1384:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1385: 	$helptopic='Authoring_Intro';
1.907     raeburn  1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1387: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1388:     } elsif ($env{'request.role'}=~/^dc/) {
                   1389:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1390:     }
                   1391:     return $helptopic;
                   1392: }
                   1393: 
                   1394: sub update_help_link {
                   1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1396:     my $origurl = $ENV{'REQUEST_URI'};
                   1397:     $origurl=~s|^/~|/priv/|;
                   1398:     my $timestamp = time;
                   1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1400:         $$datum = &escape($$datum);
                   1401:     }
                   1402: 
                   1403:     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";
                   1404:     my $output .= <<"ENDOUTPUT";
                   1405: <script type="text/javascript">
1.824     bisitz   1406: // <![CDATA[
1.430     albertel 1407: banner_link = '$banner_link';
1.824     bisitz   1408: // ]]>
1.430     albertel 1409: </script>
                   1410: ENDOUTPUT
                   1411:     return $output;
                   1412: }
                   1413: 
                   1414: # now just updates the help link and generates a blue icon
1.193     raeburn  1415: sub help_open_menu {
1.1381    raeburn  1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1417: 	= @_;    
1.949     droeschl 1418:     $stayOnPage = 1;
1.430     albertel 1419:     my $output;
                   1420:     if ($component_help) {
                   1421: 	if (!$text) {
                   1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1423: 				       $width,$height,'',$links_target);
1.430     albertel 1424: 	} else {
                   1425: 	    my $help_text;
                   1426: 	    $help_text=&unescape($topic);
                   1427: 	    $output='<table><tr><td>'.
                   1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1430: 	}
                   1431:     }
                   1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1433:     return $output.$banner_link;
                   1434: }
                   1435: 
                   1436: sub top_nav_help {
1.1369    raeburn  1437:     my ($text,$linkattr) = @_;
1.436     albertel 1438:     $text = &mt($text);
1.949     droeschl 1439:     my $stay_on_page = 1;
                   1440: 
1.1168    raeburn  1441:     my ($link,$banner_link);
                   1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1444: 	                         : "javascript:helpMenu('open')";
                   1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1446:     }
1.201     raeburn  1447:     my $title = &mt('Get help');
1.1168    raeburn  1448:     if ($link) {
                   1449:         return <<"END";
1.436     albertel 1450: $banner_link
1.1369    raeburn  1451: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1452: END
1.1168    raeburn  1453:     } else {
                   1454:         return '&nbsp;'.$text.'&nbsp;';
                   1455:     }
1.436     albertel 1456: }
                   1457: 
                   1458: sub help_menu_js {
1.1154    raeburn  1459:     my ($httphost) = @_;
1.949     droeschl 1460:     my $stayOnPage = 1;
1.436     albertel 1461:     my $width = 620;
                   1462:     my $height = 600;
1.430     albertel 1463:     my $helptopic=&general_help();
1.1154    raeburn  1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1466:     my $start_page =
                   1467:         &Apache::loncommon::start_page('Help Menu', undef,
                   1468: 				       {'frameset'    => 1,
                   1469: 					'js_ready'    => 1,
1.1154    raeburn  1470:                                         'use_absolute' => $httphost,
1.331     albertel 1471: 					'add_entries' => {
1.1168    raeburn  1472: 					    'border' => '0', 
1.579     raeburn  1473: 					    'rows'   => "110,*",},});
1.331     albertel 1474:     my $end_page =
                   1475:         &Apache::loncommon::end_page({'frameset' => 1,
                   1476: 				      'js_ready' => 1,});
                   1477: 
1.436     albertel 1478:     my $template .= <<"ENDTEMPLATE";
                   1479: <script type="text/javascript">
1.877     bisitz   1480: // <![CDATA[
1.253     albertel 1481: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1482: var banner_link = '';
1.243     raeburn  1483: function helpMenu(target) {
                   1484:     var caller = this;
                   1485:     if (target == 'open') {
                   1486:         var newWindow = null;
                   1487:         try {
1.262     albertel 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1489:         }
                   1490:         catch(error) {
                   1491:             writeHelp(caller);
                   1492:             return;
                   1493:         }
                   1494:         if (newWindow) {
                   1495:             caller = newWindow;
                   1496:         }
1.193     raeburn  1497:     }
1.243     raeburn  1498:     writeHelp(caller);
                   1499:     return;
                   1500: }
                   1501: function writeHelp(caller) {
1.1168    raeburn  1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1504:     caller.document.close();
                   1505:     caller.focus();
1.193     raeburn  1506: }
1.877     bisitz   1507: // END LON-CAPA Internal -->
1.253     albertel 1508: // ]]>
1.436     albertel 1509: </script>
1.193     raeburn  1510: ENDTEMPLATE
                   1511:     return $template;
                   1512: }
                   1513: 
1.172     www      1514: sub help_open_bug {
                   1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1516:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1518:     $text = "" if (not defined $text);
                   1519: 	$stayOnPage=1;
1.184     albertel 1520:     $width = 600 if (not defined $width);
                   1521:     $height = 600 if (not defined $height);
1.172     www      1522: 
                   1523:     $topic=~s/\W+/\+/g;
                   1524:     my $link='';
                   1525:     my $template='';
1.379     albertel 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1528:     if (!$stayOnPage)
                   1529:     {
                   1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1531:     }
                   1532:     else
                   1533:     {
                   1534: 	$link = $url;
                   1535:     }
1.1314    raeburn  1536: 
1.1382    raeburn  1537:     my $target = '_top';
                   1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1540:         $target = '_blank';
1.1378    raeburn  1541:     }
1.1382    raeburn  1542: 
1.172     www      1543:     # Add the text
                   1544:     if ($text ne "")
                   1545:     {
                   1546: 	$template .= 
                   1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1549:     }
                   1550: 
                   1551:     # Add the graphic
1.179     matthew  1552:     my $title = &mt('Report a Bug');
1.215     albertel 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1554:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1556: ENDTEMPLATE
                   1557:     if ($text ne '') { $template.='</td></tr></table>' };
                   1558:     return $template;
                   1559: 
                   1560: }
                   1561: 
                   1562: sub help_open_faq {
                   1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1564:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1566:     $text = "" if (not defined $text);
                   1567: 	$stayOnPage=1;
                   1568:     $width = 350 if (not defined $width);
                   1569:     $height = 400 if (not defined $height);
                   1570: 
                   1571:     $topic=~s/\W+/\+/g;
                   1572:     my $link='';
                   1573:     my $template='';
                   1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1575:     if (!$stayOnPage)
                   1576:     {
                   1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1578:     }
                   1579:     else
                   1580:     {
                   1581: 	$link = $url;
                   1582:     }
                   1583: 
                   1584:     # Add the text
                   1585:     if ($text ne "")
                   1586:     {
                   1587: 	$template .= 
1.173     www      1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1590:     }
                   1591: 
                   1592:     # Add the graphic
1.179     matthew  1593:     my $title = &mt('View the FAQ');
1.215     albertel 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1595:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1597: ENDTEMPLATE
                   1598:     if ($text ne '') { $template.='</td></tr></table>' };
                   1599:     return $template;
                   1600: 
1.44      bowersj2 1601: }
1.37      matthew  1602: 
1.180     matthew  1603: ###############################################################
                   1604: ###############################################################
                   1605: 
1.45      matthew  1606: =pod
                   1607: 
1.648     raeburn  1608: =item * &change_content_javascript():
1.256     matthew  1609: 
                   1610: This and the next function allow you to create small sections of an
                   1611: otherwise static HTML page that you can update on the fly with
                   1612: Javascript, even in Netscape 4.
                   1613: 
                   1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1615: must be written to the HTML page once. It will prove the Javascript
                   1616: function "change(name, content)". Calling the change function with the
                   1617: name of the section 
                   1618: you want to update, matching the name passed to C<changable_area>, and
                   1619: the new content you want to put in there, will put the content into
                   1620: that area.
                   1621: 
                   1622: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1623: to contain room for the original contents. You need to "make space"
                   1624: for whatever changes you wish to make, and be B<sure> to check your
                   1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1626: it's adequate for updating a one-line status display, but little more.
                   1627: This script will set the space to 100% width, so you only need to
                   1628: worry about height in Netscape 4.
                   1629: 
                   1630: Modern browsers are much less limiting, and if you can commit to the
                   1631: user not using Netscape 4, this feature may be used freely with
                   1632: pretty much any HTML.
                   1633: 
                   1634: =cut
                   1635: 
                   1636: sub change_content_javascript {
                   1637:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1638:     if ($env{'browser.type'} eq 'netscape' &&
                   1639: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1640: 	return (<<NETSCAPE4);
                   1641: 	function change(name, content) {
                   1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1643: 	    doc.open();
                   1644: 	    doc.write(content);
                   1645: 	    doc.close();
                   1646: 	}
                   1647: NETSCAPE4
                   1648:     } else {
                   1649: 	# Otherwise, we need to use semi-standards-compliant code
                   1650: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1651: 	# is really scary, and every useful browser supports it
                   1652: 	return (<<DOMBASED);
                   1653: 	function change(name, content) {
                   1654: 	    element = document.getElementById(name);
                   1655: 	    element.innerHTML = content;
                   1656: 	}
                   1657: DOMBASED
                   1658:     }
                   1659: }
                   1660: 
                   1661: =pod
                   1662: 
1.648     raeburn  1663: =item * &changable_area($name,$origContent):
1.256     matthew  1664: 
                   1665: This provides a "changable area" that can be modified on the fly via
                   1666: the Javascript code provided in C<change_content_javascript>. $name is
                   1667: the name you will use to reference the area later; do not repeat the
                   1668: same name on a given HTML page more then once. $origContent is what
                   1669: the area will originally contain, which can be left blank.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: sub changable_area {
                   1674:     my ($name, $origContent) = @_;
                   1675: 
1.258     albertel 1676:     if ($env{'browser.type'} eq 'netscape' &&
                   1677: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1678: 	# If this is netscape 4, we need to use the Layer tag
                   1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1680:     } else {
                   1681: 	return "<span id='$name'>$origContent</span>";
                   1682:     }
                   1683: }
                   1684: 
                   1685: =pod
                   1686: 
1.648     raeburn  1687: =item * &viewport_geometry_js 
1.590     raeburn  1688: 
                   1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1690: 
                   1691: =cut
                   1692: 
                   1693: 
                   1694: sub viewport_geometry_js { 
                   1695:     return <<"GEOMETRY";
                   1696: var Geometry = {};
                   1697: function init_geometry() {
                   1698:     if (Geometry.init) { return };
                   1699:     Geometry.init=1;
                   1700:     if (window.innerHeight) {
                   1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1705:     }
                   1706:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1707:         Geometry.getViewportHeight =
                   1708:             function() { return document.documentElement.clientHeight; };
                   1709:         Geometry.getViewportWidth =
                   1710:             function() { return document.documentElement.clientWidth; };
                   1711: 
                   1712:         Geometry.getHorizontalScroll =
                   1713:             function() { return document.documentElement.scrollLeft; };
                   1714:         Geometry.getVerticalScroll =
                   1715:             function() { return document.documentElement.scrollTop; };
                   1716:     }
                   1717:     else if (document.body.clientHeight) {
                   1718:         Geometry.getViewportHeight =
                   1719:             function() { return document.body.clientHeight; };
                   1720:         Geometry.getViewportWidth =
                   1721:             function() { return document.body.clientWidth; };
                   1722:         Geometry.getHorizontalScroll =
                   1723:             function() { return document.body.scrollLeft; };
                   1724:         Geometry.getVerticalScroll =
                   1725:             function() { return document.body.scrollTop; };
                   1726:     }
                   1727: }
                   1728: 
                   1729: GEOMETRY
                   1730: }
                   1731: 
                   1732: =pod
                   1733: 
1.648     raeburn  1734: =item * &viewport_size_js()
1.590     raeburn  1735: 
                   1736: 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. 
                   1737: 
                   1738: =cut
                   1739: 
                   1740: sub viewport_size_js {
                   1741:     my $geometry = &viewport_geometry_js();
                   1742:     return <<"DIMS";
                   1743: 
                   1744: $geometry
                   1745: 
                   1746: function getViewportDims(width,height) {
                   1747:     init_geometry();
                   1748:     width.value = Geometry.getViewportWidth();
                   1749:     height.value = Geometry.getViewportHeight();
                   1750:     return;
                   1751: }
                   1752: 
                   1753: DIMS
                   1754: }
                   1755: 
                   1756: =pod
                   1757: 
1.648     raeburn  1758: =item * &resize_textarea_js()
1.565     albertel 1759: 
                   1760: emits the needed javascript to resize a textarea to be as big as possible
                   1761: 
                   1762: creates a function resize_textrea that takes two IDs first should be
                   1763: the id of the element to resize, second should be the id of a div that
                   1764: surrounds everything that comes after the textarea, this routine needs
                   1765: to be attached to the <body> for the onload and onresize events.
                   1766: 
1.648     raeburn  1767: =back
1.565     albertel 1768: 
                   1769: =cut
                   1770: 
                   1771: sub resize_textarea_js {
1.590     raeburn  1772:     my $geometry = &viewport_geometry_js();
1.565     albertel 1773:     return <<"RESIZE";
                   1774:     <script type="text/javascript">
1.824     bisitz   1775: // <![CDATA[
1.590     raeburn  1776: $geometry
1.565     albertel 1777: 
1.588     albertel 1778: function getX(element) {
                   1779:     var x = 0;
                   1780:     while (element) {
                   1781: 	x += element.offsetLeft;
                   1782: 	element = element.offsetParent;
                   1783:     }
                   1784:     return x;
                   1785: }
                   1786: function getY(element) {
                   1787:     var y = 0;
                   1788:     while (element) {
                   1789: 	y += element.offsetTop;
                   1790: 	element = element.offsetParent;
                   1791:     }
                   1792:     return y;
                   1793: }
                   1794: 
                   1795: 
1.565     albertel 1796: function resize_textarea(textarea_id,bottom_id) {
                   1797:     init_geometry();
                   1798:     var textarea        = document.getElementById(textarea_id);
                   1799:     //alert(textarea);
                   1800: 
1.588     albertel 1801:     var textarea_top    = getY(textarea);
1.565     albertel 1802:     var textarea_height = textarea.offsetHeight;
                   1803:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1804:     var bottom_top      = getY(bottom);
1.565     albertel 1805:     var bottom_height   = bottom.offsetHeight;
                   1806:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1807:     var fudge           = 23;
1.565     albertel 1808:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1809:     if (new_height < 300) {
                   1810: 	new_height = 300;
                   1811:     }
                   1812:     textarea.style.height=new_height+'px';
                   1813: }
1.824     bisitz   1814: // ]]>
1.565     albertel 1815: </script>
                   1816: RESIZE
                   1817: 
                   1818: }
                   1819: 
1.1205    golterma 1820: sub colorfuleditor_js {
1.1248    raeburn  1821:     my $browse_or_search;
                   1822:     my $respath;
                   1823:     my ($cnum,$cdom) = &crsauthor_url();
                   1824:     if ($cnum) {
                   1825:         $respath = "/res/$cdom/$cnum/";
                   1826:         my %js_lt = &Apache::lonlocal::texthash(
                   1827:             sunm => 'Sub-directory name',
                   1828:             save => 'Save page to make this permanent',
                   1829:         );
                   1830:         &js_escape(\%js_lt);
1.1400    raeburn  1831:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1832:         $browse_or_search = <<"END";
                   1833: 
1.1400    raeburn  1834:     $showfile_js
                   1835: 
1.1248    raeburn  1836:     function toggleChooser(form,element,titleid,only,search) {
                   1837:         var disp = 'none';
                   1838:         if (document.getElementById('chooser_'+element)) {
                   1839:             var curr = document.getElementById('chooser_'+element).style.display;
                   1840:             if (curr == 'none') {
                   1841:                 disp='inline';
                   1842:                 if (form.elements['chooser_'+element].length) {
                   1843:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1844:                         form.elements['chooser_'+element][i].checked = false;
                   1845:                     }
                   1846:                 }
                   1847:                 toggleResImport(form,element);
                   1848:             }
                   1849:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1850:             var dirsel = '';
                   1851:             var filesel = '';
                   1852:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1853:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1854:                 if (currcrsres == 'none') {
                   1855:                     dirsel = 'coursepath_'+element;
                   1856:                     var filesel = 'coursefile_'+element;
                   1857:                     var include;
                   1858:                     if (document.getElementById('crsres_include_'+element)) {
                   1859:                         include = document.getElementById('crsres_include_'+element).value;
                   1860:                     }
1.1402    raeburn  1861:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1862:                 }
                   1863:             }
                   1864:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1865:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1866:                 if (currcrsupload == 'none') {
                   1867:                     dirsel = 'crsauthorpath_'+element;
                   1868:                     filesel = '';
1.1402    raeburn  1869:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1870:                 }
                   1871:             }
1.1248    raeburn  1872:         }
                   1873:     }
                   1874: 
1.1400    raeburn  1875:     function toggleCrsFile(form,element) {
1.1248    raeburn  1876:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1877:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1878:             if (curr == 'none') {
1.1400    raeburn  1879:                 if (document.getElementById('coursepath_'+element)) {
                   1880:                     var numdirs;
                   1881:                     if (document.getElementById('coursepath_'+element).length) {
                   1882:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1883:                     }
1.1402    raeburn  1884:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1885:                         (document.getElementById('nocrsres_'+element))) {
                   1886:                         if (numdirs) {
                   1887:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1888:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1889:                         } else {
                   1890:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1891:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1892:                         }
                   1893:                     }
1.1248    raeburn  1894:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1895:                     if (numdirs > 1) {
1.1400    raeburn  1896:                         var selelem = form.elements['coursefile_'+element];
                   1897:                         var i, len = selelem.options.length -1;
                   1898:                         if (len >=0) {
                   1899:                             for (i = len; i >= 0; i--) {
                   1900:                                 selelem.remove(i);
                   1901:                             }
                   1902:                             selelem.options[0] = new Option('','');
                   1903:                         }
1.1248    raeburn  1904:                     }
                   1905:                 }
1.1400    raeburn  1906:             }
1.1248    raeburn  1907:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1908:         }
                   1909:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1910:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1911:             if (document.getElementById('uploadcrsres_'+element)) {
                   1912:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1913:             }
                   1914:         }
                   1915:         return;
                   1916:     }
                   1917: 
1.1400    raeburn  1918:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1919:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1920:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1921:         }
                   1922:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1923:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1924:             if (curr == 'none') {
1.1400    raeburn  1925:                 form.elements['newsubdir_'+element][0].checked = true;
                   1926:                 toggleNewsubdir(form,element);
                   1927:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1928:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1929:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1930:                 }
                   1931:             }
                   1932:         }
                   1933:         return;
                   1934:     }
                   1935: 
                   1936:     function toggleResImport(form,element) {
                   1937:         var choices = new Array('crsres','upload');
                   1938:         for (var i=0; i<choices.length; i++) {
                   1939:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1940:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1941:             }
                   1942:         }
                   1943:     }
                   1944: 
                   1945:     function toggleNewsubdir(form,element) {
                   1946:         var newsub = form.elements['newsubdir_'+element];
                   1947:         if (newsub) {
                   1948:             if (newsub.length) {
                   1949:                 for (var j=0; j<newsub.length; j++) {
                   1950:                     if (newsub[j].checked) {
                   1951:                         if (document.getElementById('newsubdirname_'+element)) {
                   1952:                             if (newsub[j].value == '1') {
                   1953:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1954:                                 if (document.getElementById('newsubdir_'+element)) {
                   1955:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1956:                                 }
                   1957:                             } else {
                   1958:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1959:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1960:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1961:                             }
                   1962:                         }
                   1963:                         break; 
                   1964:                     }
                   1965:                 }
                   1966:             }
                   1967:         }
                   1968:     }
                   1969: 
                   1970:     function updateCrsFile(form,element) {
                   1971:         var directory = form.elements['coursepath_'+element];
                   1972:         var filename = form.elements['coursefile_'+element];
                   1973:         var path = directory.options[directory.selectedIndex].value;
                   1974:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1975:         if (file != '') {
                   1976:             form.elements[element].value = '$respath';
                   1977:             if (path == '/') {
                   1978:                 form.elements[element].value += file;
                   1979:             } else {
                   1980:                 form.elements[element].value += path+'/'+file;
                   1981:             }
                   1982:             unClean();
                   1983:             if (document.getElementById('previewimg_'+element)) {
                   1984:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1985:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1986:             }
                   1987:             if (document.getElementById('showimg_'+element)) {
                   1988:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1989:             }
1.1248    raeburn  1990:         }
                   1991:         toggleChooser(form,element);
                   1992:         return;
                   1993:     }
                   1994: 
                   1995:     function uploadDone(suffix,name) {
                   1996:         if (name) {
                   1997: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1998:             unClean();
                   1999:             toggleChooser(document.forms["lonhomework"],suffix);
                   2000:         }
                   2001:     }
                   2002: 
                   2003: \$(document).ready(function(){
                   2004: 
                   2005:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2006:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2007:             var buttonId = this.id;
                   2008:             var suffix = buttonId.toString();
                   2009:             suffix = suffix.replace(/^crsupload_/,'');
                   2010:             event.preventDefault();
                   2011:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2012:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2013:             \$(this.form).submit();
                   2014:             document.lonhomework.target = '';
                   2015:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2016:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2017:             }
                   2018:             return false;
                   2019:         }
                   2020:     });
                   2021: });
                   2022: END
                   2023:     }
1.1205    golterma 2024:     return <<"COLORFULEDIT"
                   2025: <script type="text/javascript">
                   2026: // <![CDATA[>
                   2027:     function fold_box(curDepth, lastresource){
                   2028: 
                   2029:     // we need a list because there can be several blocks you need to fold in one tag
                   2030:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2031:     // but there is only one folding button per tag
                   2032:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2033: 
                   2034:         if(block.item(0).style.display == 'none'){
                   2035: 
                   2036:             foldbutton.value = '@{[&mt("Hide")]}';
                   2037:             for (i = 0; i < block.length; i++){
                   2038:                 block.item(i).style.display = '';
                   2039:             }
                   2040:         }else{
                   2041: 
                   2042:             foldbutton.value = '@{[&mt("Show")]}';
                   2043:             for (i = 0; i < block.length; i++){
                   2044:                 // block.item(i).style.visibility = 'collapse';
                   2045:                 block.item(i).style.display = 'none';
                   2046:             }
                   2047:         };
                   2048:         saveState(lastresource);
                   2049:     }
                   2050: 
                   2051:     function saveState (lastresource) {
                   2052: 
                   2053:         var tag_list = getTagList();
                   2054:         if(tag_list != null){
                   2055:             var timestamp = new Date().getTime();
                   2056:             var key = lastresource;
                   2057: 
                   2058:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2059:             // starting with timestamp
                   2060:             var value = timestamp+';';
                   2061: 
                   2062:             // building the list of key-value pairs
                   2063:             for(var i = 0; i < tag_list.length; i++){
                   2064:                 value += tag_list[i]+',';
                   2065:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2066:             }
                   2067: 
                   2068:             // only iterate whole storage if nothing to override
                   2069:             if(localStorage.getItem(key) == null){        
                   2070: 
                   2071:                 // prevent storage from growing large
                   2072:                 if(localStorage.length > 50){
                   2073:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2074:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2075:                     var oldest_key;
                   2076:                     
                   2077:                     for(var i = 1; i < localStorage.length; i++){
                   2078:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2079:                             oldest_key = localStorage.key(i);
                   2080:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2081:                         }
                   2082:                     }
                   2083:                     localStorage.removeItem(oldest_key);
                   2084:                 }
                   2085:             }
                   2086:             localStorage.setItem(key,value);
                   2087:         }
                   2088:     }
                   2089: 
                   2090:     // restore folding status of blocks (on page load)
                   2091:     function restoreState (lastresource) {
                   2092:         if(localStorage.getItem(lastresource) != null){
                   2093:             var key = lastresource;
                   2094:             var value = localStorage.getItem(key);
                   2095:             var regex_delTimestamp = /^\d+;/;
                   2096: 
                   2097:             value.replace(regex_delTimestamp, '');
                   2098: 
                   2099:             var valueArr = value.split(';');
                   2100:             var pairs;
                   2101:             var elements;
                   2102:             for (var i = 0; i < valueArr.length; i++){
                   2103:                 pairs = valueArr[i].split(',');
                   2104:                 elements = document.getElementsByName(pairs[0]);
                   2105: 
                   2106:                 for (var j = 0; j < elements.length; j++){  
                   2107:                     elements[j].style.display = pairs[1];
                   2108:                     if (pairs[1] == "none"){
                   2109:                         var regex_id = /([_\\d]+)\$/;
                   2110:                         regex_id.exec(pairs[0]);
                   2111:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2112:                     }
                   2113:                 }
                   2114:             }
                   2115:         }
                   2116:     }
                   2117: 
                   2118:     function getTagList () {
                   2119:         
                   2120:         var stringToSearch = document.lonhomework.innerHTML;
                   2121: 
                   2122:         var ret = new Array();
                   2123:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2124:         var tag_list = stringToSearch.match(regex_findBlock);
                   2125: 
                   2126:         if(tag_list != null){
                   2127:             for(var i = 0; i < tag_list.length; i++){            
                   2128:                 ret.push(tag_list[i].replace(/"/, ''));
                   2129:             }
                   2130:         }
                   2131:         return ret;
                   2132:     }
                   2133: 
                   2134:     function saveScrollPosition (resource) {
                   2135:         var tag_list = getTagList();
                   2136: 
                   2137:         // we dont always want to jump to the first block
                   2138:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2139:         if(\$(window).scrollTop() > 170){
                   2140:             if(tag_list != null){
                   2141:                 var result;
                   2142:                 for(var i = 0; i < tag_list.length; i++){
                   2143:                     if(isElementInViewport(tag_list[i])){
                   2144:                         result += tag_list[i]+';';
                   2145:                     }
                   2146:                 }
                   2147:                 sessionStorage.setItem('anchor_'+resource, result);
                   2148:             }
                   2149:         } else {
                   2150:             // we dont need to save zero, just delete the item to leave everything tidy
                   2151:             sessionStorage.removeItem('anchor_'+resource);
                   2152:         }
                   2153:     }
                   2154: 
                   2155:     function restoreScrollPosition(resource){
                   2156: 
                   2157:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2158:         if(elem != null){
                   2159:             var tag_list = elem.split(';');
                   2160:             var elem_list;
                   2161: 
                   2162:             for(var i = 0; i < tag_list.length; i++){
                   2163:                 elem_list = document.getElementsByName(tag_list[i]);
                   2164:                 
                   2165:                 if(elem_list.length > 0){
                   2166:                     elem = elem_list[0];
                   2167:                     break;
                   2168:                 }
                   2169:             }
                   2170:             elem.scrollIntoView();
                   2171:         }
                   2172:     }
                   2173: 
                   2174:     function isElementInViewport(el) {
                   2175: 
                   2176:         // change to last element instead of first
                   2177:         var elem = document.getElementsByName(el);
                   2178:         var rect = elem[0].getBoundingClientRect();
                   2179: 
                   2180:         return (
                   2181:             rect.top >= 0 &&
                   2182:             rect.left >= 0 &&
                   2183:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2184:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2185:         );
                   2186:     }
                   2187:     
                   2188:     function autosize(depth){
                   2189:         var cmInst = window['cm'+depth];
                   2190:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2191: 
                   2192:         // is fixed size, switching to dynamic
                   2193:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2194:             cmInst.setSize("","auto");
                   2195:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2196:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2197: 
                   2198:         // is dynamic size, switching to fixed
                   2199:         } else {
                   2200:             cmInst.setSize("","300px");
                   2201:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2202:             sessionStorage.removeItem("autosized_"+depth);
                   2203:         }
                   2204:     }
                   2205: 
1.1248    raeburn  2206: $browse_or_search
1.1205    golterma 2207: 
                   2208: // ]]>
                   2209: </script>
                   2210: COLORFULEDIT
                   2211: }
                   2212: 
                   2213: sub xmleditor_js {
                   2214:     return <<XMLEDIT
                   2215: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2216: <script type="text/javascript">
                   2217: // <![CDATA[>
                   2218: 
                   2219:     function saveScrollPosition (resource) {
                   2220: 
                   2221:         var scrollPos = \$(window).scrollTop();
                   2222:         sessionStorage.setItem(resource,scrollPos);
                   2223:     }
                   2224: 
                   2225:     function restoreScrollPosition(resource){
                   2226: 
                   2227:         var scrollPos = sessionStorage.getItem(resource);
                   2228:         \$(window).scrollTop(scrollPos);
                   2229:     }
                   2230: 
                   2231:     // unless internet explorer
                   2232:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2233: 
                   2234:         \$(document).ready(function() {
                   2235:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2236:         });
                   2237:     }
                   2238: 
                   2239:     // inserts text at cursor position into codemirror (xml editor only)
                   2240:     function insertText(text){
                   2241:         cm.focus();
                   2242:         var curPos = cm.getCursor();
                   2243:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2244:     }
                   2245: // ]]>
                   2246: </script>
                   2247: XMLEDIT
                   2248: }
                   2249: 
                   2250: sub insert_folding_button {
                   2251:     my $curDepth = $Apache::lonxml::curdepth;
                   2252:     my $lastresource = $env{'request.ambiguous'};
                   2253: 
                   2254:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2255:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2256: }
                   2257: 
1.1248    raeburn  2258: sub crsauthor_url {
                   2259:     my ($url) = @_;
                   2260:     if ($url eq '') {
                   2261:         $url = $ENV{'REQUEST_URI'};
                   2262:     }
                   2263:     my ($cnum,$cdom);
                   2264:     if ($env{'request.course.id'}) {
                   2265:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2266:         if ($audom ne '' && $auname ne '') {
                   2267:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2268:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2269:                 $cnum = $auname;
                   2270:                 $cdom = $audom;
                   2271:             }
                   2272:         }
                   2273:     }
                   2274:     return ($cnum,$cdom);
                   2275: }
                   2276: 
                   2277: sub import_crsauthor_form {
1.1400    raeburn  2278:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2279:     return (0) unless ($env{'request.course.id'});
                   2280:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2281:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2282:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2283:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2284:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2285:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2286: 
1.1248    raeburn  2287:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2288:         $is_home = 1;
                   2289:     }
1.1400    raeburn  2290:     $toppath = "/priv/$cdom/$cnum";
                   2291:     my $nonemptydir = 1;
                   2292:     my $js_only;
                   2293:     if ($only) {
                   2294:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2295:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2296:     }
                   2297:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2298:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2299:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2300:     my %lt = &Apache::lonlocal::texthash (
                   2301:         fnam => 'Filename',
                   2302:         dire => 'Directory',
1.1400    raeburn  2303:         se   => 'Select',
1.1248    raeburn  2304:     );
1.1402    raeburn  2305:     $output = $lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2306:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2307:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2308:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2309:     if ($files{'/'}) {
                   2310:         $output .= '<option value="/">/</option>'."\n";
                   2311:     }
1.1400    raeburn  2312:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2313:         next if ($key eq '/');
1.1400    raeburn  2314:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2315:     }
                   2316:     $output .= '</select><br />'."\n".
1.1402    raeburn  2317:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2318:                '<option value="" selected="selected"></option>'."\n".
1.1402    raeburn  2319:                '</select>'."\n".
                   2320:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2321:     return ($numdirs,$output);
                   2322: }
                   2323: 
                   2324: sub show_crsfiles_js {
                   2325:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2326:     my $se = &js_escape(&mt('Select'));
                   2327:     my $exclude;
                   2328:     if (ref($excluderef) eq 'HASH') {
                   2329:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2330:     }
                   2331:     my $js = <<"END";
                   2332: 
                   2333: 
1.1402    raeburn  2334:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2335:         var relpath = '';
                   2336:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2337:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2338:             if (currdir == '') {
                   2339:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2340:                     selelem = form.elements[filesel];
                   2341:                     var j, numfiles = selelem.options.length -1;
                   2342:                     if (numfiles >=0) {
                   2343:                         for (j = numfiles; j >= 0; j--) {
                   2344:                             selelem.remove(j);
                   2345:                         }
                   2346:                     }
                   2347:                     if (selelem.options.length == 0) {
                   2348:                         selelem.options[selelem.options.length] = new Option('','');
                   2349:                         selelem.selectedIndex = 0;
1.1248    raeburn  2350:                     }
                   2351:                 }
1.1400    raeburn  2352:                 return;
                   2353:             } else {
                   2354:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2355:             }
                   2356:         }
1.1400    raeburn  2357:         var http = new XMLHttpRequest();
                   2358:         var url = "/adm/courseauthor";
                   2359:         var crsrole = "$env{'request.role'}";
                   2360:         var exclude = '';
                   2361:         if (exc) {
                   2362:             exclude = '$exclude';
                   2363:         }
1.1402    raeburn  2364:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2365:         http.open("POST", url, true);
                   2366:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2367:         http.onreadystatechange = function() {
                   2368:             if (http.readyState == 4 && http.status == 200) {
                   2369:                 var data = JSON.parse(http.responseText);
                   2370:                 var selelem;
                   2371:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2372:                     if (Array.isArray(data.dirs)) {
                   2373:                         selelem = form.elements[dirsel];
                   2374:                         var i, numdirs = selelem.options.length -1;
                   2375:                         if (numdirs >=0) {
                   2376:                             for (i = numdirs; i >= 0; i--) {
                   2377:                                 selelem.remove(i);
                   2378:                             }
                   2379:                         }
                   2380:                         var len = data.dirs.length;
                   2381:                         if (len) {
1.1402    raeburn  2382:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2383:                             var j;
                   2384:                             for (j = 0; j < len; j++) {
                   2385:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2386:                             }
                   2387:                             selelem.selectedIndex = 0;
                   2388:                         }
                   2389:                         if (!setfile) {
                   2390:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2391:                                 selelem = form.elements[filesel];
                   2392:                                 var j, numfiles = selelem.options.length -1;
                   2393:                                 if (numfiles >=0) {
                   2394:                                     for (j = numfiles; j >= 0; j--) {
                   2395:                                         selelem.remove(j);
                   2396:                                     }
                   2397:                                 }
                   2398:                                 if (selelem.options.length == 0) {
                   2399:                                     selelem.options[selelem.options.length] = new Option('','');
                   2400:                                     selelem.selectedIndex = 0;
                   2401:                                 }
                   2402:                             }
                   2403:                         }
                   2404:                     }
                   2405:                 }
                   2406:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2407:                     selelem = form.elements[filesel];
                   2408:                     var i, numfiles = selelem.options.length -1;
                   2409:                     if (numfiles >=0) {
                   2410:                         for (i = numfiles; i >= 0; i--) {
                   2411:                             selelem.remove(i);
                   2412:                         }
                   2413:                     }
                   2414:                     var x;
                   2415:                     for (x in data.files) {
                   2416:                         if (Array.isArray(data.files[x])) {
                   2417:                             if (data.files[x].length > 1) {
                   2418:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2419:                             }
                   2420:                             var len = data.files[x].length;
                   2421:                             if (len) {
                   2422:                                 var k;
                   2423:                                 for (k = 0; k < len; k++) {
                   2424:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2425:                                 }
                   2426:                                 selelem.selectedIndex = 0;
                   2427:                             }
                   2428:                         }
                   2429:                     }
                   2430:                     if (selelem.options.length == 0) {
                   2431:                         selelem.options[selelem.options.length] = new Option('','');
                   2432:                         selelem.selectedIndex = 0;
                   2433:                     }
1.1248    raeburn  2434:                 }
                   2435:             }
                   2436:         }
1.1400    raeburn  2437:         http.send(params);
1.1248    raeburn  2438:     }
1.1400    raeburn  2439: END
1.1248    raeburn  2440: }
                   2441: 
1.565     albertel 2442: =pod
                   2443: 
1.256     matthew  2444: =head1 Excel and CSV file utility routines
                   2445: 
                   2446: =cut
                   2447: 
                   2448: ###############################################################
                   2449: ###############################################################
                   2450: 
                   2451: =pod
                   2452: 
1.1162    raeburn  2453: =over 4
                   2454: 
1.648     raeburn  2455: =item * &csv_translate($text) 
1.37      matthew  2456: 
1.185     www      2457: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2458: format.
                   2459: 
                   2460: =cut
                   2461: 
1.180     matthew  2462: ###############################################################
                   2463: ###############################################################
1.37      matthew  2464: sub csv_translate {
                   2465:     my $text = shift;
                   2466:     $text =~ s/\"/\"\"/g;
1.209     albertel 2467:     $text =~ s/\n/ /g;
1.37      matthew  2468:     return $text;
                   2469: }
1.180     matthew  2470: 
                   2471: ###############################################################
                   2472: ###############################################################
                   2473: 
                   2474: =pod
                   2475: 
1.648     raeburn  2476: =item * &define_excel_formats()
1.180     matthew  2477: 
                   2478: Define some commonly used Excel cell formats.
                   2479: 
                   2480: Currently supported formats:
                   2481: 
                   2482: =over 4
                   2483: 
                   2484: =item header
                   2485: 
                   2486: =item bold
                   2487: 
                   2488: =item h1
                   2489: 
                   2490: =item h2
                   2491: 
                   2492: =item h3
                   2493: 
1.256     matthew  2494: =item h4
                   2495: 
                   2496: =item i
                   2497: 
1.180     matthew  2498: =item date
                   2499: 
                   2500: =back
                   2501: 
                   2502: Inputs: $workbook
                   2503: 
                   2504: Returns: $format, a hash reference.
                   2505: 
1.1057    foxr     2506: 
1.180     matthew  2507: =cut
                   2508: 
                   2509: ###############################################################
                   2510: ###############################################################
                   2511: sub define_excel_formats {
                   2512:     my ($workbook) = @_;
                   2513:     my $format;
                   2514:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2515:                                                 bottom    => 1,
                   2516:                                                 align     => 'center');
                   2517:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2518:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2519:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2520:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2521:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2522:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2523:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2524:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2525:     return $format;
                   2526: }
                   2527: 
                   2528: ###############################################################
                   2529: ###############################################################
1.113     bowersj2 2530: 
                   2531: =pod
                   2532: 
1.648     raeburn  2533: =item * &create_workbook()
1.255     matthew  2534: 
                   2535: Create an Excel worksheet.  If it fails, output message on the
                   2536: request object and return undefs.
                   2537: 
                   2538: Inputs: Apache request object
                   2539: 
                   2540: Returns (undef) on failure, 
                   2541:     Excel worksheet object, scalar with filename, and formats 
                   2542:     from &Apache::loncommon::define_excel_formats on success
                   2543: 
                   2544: =cut
                   2545: 
                   2546: ###############################################################
                   2547: ###############################################################
                   2548: sub create_workbook {
                   2549:     my ($r) = @_;
                   2550:         #
                   2551:     # Create the excel spreadsheet
                   2552:     my $filename = '/prtspool/'.
1.258     albertel 2553:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2554:         time.'_'.rand(1000000000).'.xls';
                   2555:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2556:     if (! defined($workbook)) {
                   2557:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2558:         $r->print(
                   2559:             '<p class="LC_error">'
                   2560:            .&mt('Problems occurred in creating the new Excel file.')
                   2561:            .' '.&mt('This error has been logged.')
                   2562:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2563:            .'</p>'
                   2564:         );
1.255     matthew  2565:         return (undef);
                   2566:     }
                   2567:     #
1.1014    foxr     2568:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2569:     #
                   2570:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2571:     return ($workbook,$filename,$format);
                   2572: }
                   2573: 
                   2574: ###############################################################
                   2575: ###############################################################
                   2576: 
                   2577: =pod
                   2578: 
1.648     raeburn  2579: =item * &create_text_file()
1.113     bowersj2 2580: 
1.542     raeburn  2581: Create a file to write to and eventually make available to the user.
1.256     matthew  2582: If file creation fails, outputs an error message on the request object and 
                   2583: return undefs.
1.113     bowersj2 2584: 
1.256     matthew  2585: Inputs: Apache request object, and file suffix
1.113     bowersj2 2586: 
1.256     matthew  2587: Returns (undef) on failure, 
                   2588:     Filehandle and filename on success.
1.113     bowersj2 2589: 
                   2590: =cut
                   2591: 
1.256     matthew  2592: ###############################################################
                   2593: ###############################################################
                   2594: sub create_text_file {
                   2595:     my ($r,$suffix) = @_;
                   2596:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2597:     my $fh;
                   2598:     my $filename = '/prtspool/'.
1.258     albertel 2599:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2600:         time.'_'.rand(1000000000).'.'.$suffix;
                   2601:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2602:     if (! defined($fh)) {
                   2603:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2604:         $r->print(
                   2605:             '<p class="LC_error">'
                   2606:            .&mt('Problems occurred in creating the output file.')
                   2607:            .' '.&mt('This error has been logged.')
                   2608:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2609:            .'</p>'
                   2610:         );
1.113     bowersj2 2611:     }
1.256     matthew  2612:     return ($fh,$filename)
1.113     bowersj2 2613: }
                   2614: 
                   2615: 
1.256     matthew  2616: =pod 
1.113     bowersj2 2617: 
                   2618: =back
                   2619: 
                   2620: =cut
1.37      matthew  2621: 
                   2622: ###############################################################
1.33      matthew  2623: ##        Home server <option> list generating code          ##
                   2624: ###############################################################
1.35      matthew  2625: 
1.169     www      2626: # ------------------------------------------
                   2627: 
                   2628: sub domain_select {
1.1289    raeburn  2629:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2630:     my @possdoms;
                   2631:     if (ref($incdoms) eq 'ARRAY') {
                   2632:         @possdoms = @{$incdoms};
                   2633:     } else {
                   2634:         @possdoms = &Apache::lonnet::all_domains();
                   2635:     }
                   2636: 
1.169     www      2637:     my %domains=map { 
1.514     albertel 2638: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2639:     } @possdoms;
                   2640: 
                   2641:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2642:         foreach my $dom (@{$excdoms}) {
                   2643:             delete($domains{$dom});
                   2644:         }
                   2645:     }
                   2646: 
1.169     www      2647:     if ($multiple) {
                   2648: 	$domains{''}=&mt('Any domain');
1.550     albertel 2649: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2650: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2651:     } else {
1.550     albertel 2652: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2653: 	return &select_form($name,$value,\%domains);
1.169     www      2654:     }
                   2655: }
                   2656: 
1.282     albertel 2657: #-------------------------------------------
                   2658: 
                   2659: =pod
                   2660: 
1.519     raeburn  2661: =head1 Routines for form select boxes
                   2662: 
                   2663: =over 4
                   2664: 
1.648     raeburn  2665: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2666: 
                   2667: Returns a string containing a <select> element int multiple mode
                   2668: 
                   2669: 
                   2670: Args:
                   2671:   $name - name of the <select> element
1.506     raeburn  2672:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2673:   $size - number of rows long the select element is
1.283     albertel 2674:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2675:           (shown text should already have been &mt())
1.506     raeburn  2676:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2677: 
1.282     albertel 2678: =cut
                   2679: 
                   2680: #-------------------------------------------
1.169     www      2681: sub multiple_select_form {
1.284     albertel 2682:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2683:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2684:     my $output='';
1.191     matthew  2685:     if (! defined($size)) {
                   2686:         $size = 4;
1.283     albertel 2687:         if (scalar(keys(%$hash))<4) {
                   2688:             $size = scalar(keys(%$hash));
1.191     matthew  2689:         }
                   2690:     }
1.734     bisitz   2691:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2692:     my @order;
1.506     raeburn  2693:     if (ref($order) eq 'ARRAY')  {
                   2694:         @order = @{$order};
                   2695:     } else {
                   2696:         @order = sort(keys(%$hash));
1.501     banghart 2697:     }
                   2698:     if (exists($$hash{'select_form_order'})) {
                   2699:         @order = @{$$hash{'select_form_order'}};
                   2700:     }
                   2701:         
1.284     albertel 2702:     foreach my $key (@order) {
1.356     albertel 2703:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2704:         $output.='selected="selected" ' if ($selected{$key});
                   2705:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2706:     }
                   2707:     $output.="</select>\n";
                   2708:     return $output;
                   2709: }
                   2710: 
1.88      www      2711: #-------------------------------------------
                   2712: 
                   2713: =pod
                   2714: 
1.1254    raeburn  2715: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2716: 
                   2717: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2718: allow a user to select options from a ref to a hash containing:
                   2719: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2720: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2721: An optional arg -- $readonly -- if true will cause the select form
                   2722: to be disabled, e.g., for the case where an instructor has a section-
                   2723: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2724: 
1.88      www      2725: See lonrights.pm for an example invocation and use.
                   2726: 
                   2727: =cut
                   2728: 
                   2729: #-------------------------------------------
                   2730: sub select_form {
1.1228    raeburn  2731:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2732:     return unless (ref($hashref) eq 'HASH');
                   2733:     if ($onchange) {
                   2734:         $onchange = ' onchange="'.$onchange.'"';
                   2735:     }
1.1228    raeburn  2736:     my $disabled;
                   2737:     if ($readonly) {
                   2738:         $disabled = ' disabled="disabled"';
                   2739:     }
                   2740:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2741:     my @keys;
1.970     raeburn  2742:     if (exists($hashref->{'select_form_order'})) {
                   2743: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2744:     } else {
1.970     raeburn  2745: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2746:     }
1.356     albertel 2747:     foreach my $key (@keys) {
                   2748:         $selectform.=
                   2749: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2750:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2751:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2752:     }
                   2753:     $selectform.="</select>";
                   2754:     return $selectform;
                   2755: }
                   2756: 
1.475     www      2757: # For display filters
                   2758: 
                   2759: sub display_filter {
1.1074    raeburn  2760:     my ($context) = @_;
1.475     www      2761:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2762:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2763:     my $phraseinput = 'hidden';
                   2764:     my $includeinput = 'hidden';
                   2765:     my ($checked,$includetypestext);
                   2766:     if ($env{'form.displayfilter'} eq 'containing') {
                   2767:         $phraseinput = 'text'; 
                   2768:         if ($context eq 'parmslog') {
                   2769:             $includeinput = 'checkbox';
                   2770:             if ($env{'form.includetypes'}) {
                   2771:                 $checked = ' checked="checked"';
                   2772:             }
                   2773:             $includetypestext = &mt('Include parameter types');
                   2774:         }
                   2775:     } else {
                   2776:         $includetypestext = '&nbsp;';
                   2777:     }
                   2778:     my ($additional,$secondid,$thirdid);
                   2779:     if ($context eq 'parmslog') {
                   2780:         $additional = 
                   2781:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2782:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2783:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2784:             '</label>';
                   2785:         $secondid = 'includetypes';
                   2786:         $thirdid = 'includetypestext';
                   2787:     }
                   2788:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2789:                                                     '$secondid','$thirdid')";
                   2790:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2791: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2792: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2793: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2794:            &mt('Filter: [_1]',
1.477     www      2795: 	   &select_form($env{'form.displayfilter'},
                   2796: 			'displayfilter',
1.970     raeburn  2797: 			{'currentfolder' => 'Current folder/page',
1.477     www      2798: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2799: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2800: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2801:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2802:                          '" />'.$additional;
                   2803: }
                   2804: 
                   2805: sub display_filter_js {
                   2806:     my $includetext = &mt('Include parameter types');
                   2807:     return <<"ENDJS";
                   2808:   
                   2809: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2810:     var firstType = 'hidden';
                   2811:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2812:         firstType = 'text';
                   2813:     }
                   2814:     firstObject = document.getElementById(firstid);
                   2815:     if (typeof(firstObject) == 'object') {
                   2816:         if (firstObject.type != firstType) {
                   2817:             changeInputType(firstObject,firstType);
                   2818:         }
                   2819:     }
                   2820:     if (context == 'parmslog') {
                   2821:         var secondType = 'hidden';
                   2822:         if (firstType == 'text') {
                   2823:             secondType = 'checkbox';
                   2824:         }
                   2825:         secondObject = document.getElementById(secondid);  
                   2826:         if (typeof(secondObject) == 'object') {
                   2827:             if (secondObject.type != secondType) {
                   2828:                 changeInputType(secondObject,secondType);
                   2829:             }
                   2830:         }
                   2831:         var textItem = document.getElementById(thirdid);
                   2832:         var currtext = textItem.innerHTML;
                   2833:         var newtext;
                   2834:         if (firstType == 'text') {
                   2835:             newtext = '$includetext';
                   2836:         } else {
                   2837:             newtext = '&nbsp;';
                   2838:         }
                   2839:         if (currtext != newtext) {
                   2840:             textItem.innerHTML = newtext;
                   2841:         }
                   2842:     }
                   2843:     return;
                   2844: }
                   2845: 
                   2846: function changeInputType(oldObject,newType) {
                   2847:     var newObject = document.createElement('input');
                   2848:     newObject.type = newType;
                   2849:     if (oldObject.size) {
                   2850:         newObject.size = oldObject.size;
                   2851:     }
                   2852:     if (oldObject.value) {
                   2853:         newObject.value = oldObject.value;
                   2854:     }
                   2855:     if (oldObject.name) {
                   2856:         newObject.name = oldObject.name;
                   2857:     }
                   2858:     if (oldObject.id) {
                   2859:         newObject.id = oldObject.id;
                   2860:     }
                   2861:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2862:     return;
                   2863: }
                   2864: 
                   2865: ENDJS
1.475     www      2866: }
                   2867: 
1.167     www      2868: sub gradeleveldescription {
                   2869:     my $gradelevel=shift;
                   2870:     my %gradelevels=(0 => 'Not specified',
                   2871: 		     1 => 'Grade 1',
                   2872: 		     2 => 'Grade 2',
                   2873: 		     3 => 'Grade 3',
                   2874: 		     4 => 'Grade 4',
                   2875: 		     5 => 'Grade 5',
                   2876: 		     6 => 'Grade 6',
                   2877: 		     7 => 'Grade 7',
                   2878: 		     8 => 'Grade 8',
                   2879: 		     9 => 'Grade 9',
                   2880: 		     10 => 'Grade 10',
                   2881: 		     11 => 'Grade 11',
                   2882: 		     12 => 'Grade 12',
                   2883: 		     13 => 'Grade 13',
                   2884: 		     14 => '100 Level',
                   2885: 		     15 => '200 Level',
                   2886: 		     16 => '300 Level',
                   2887: 		     17 => '400 Level',
                   2888: 		     18 => 'Graduate Level');
                   2889:     return &mt($gradelevels{$gradelevel});
                   2890: }
                   2891: 
1.163     www      2892: sub select_level_form {
                   2893:     my ($deflevel,$name)=@_;
                   2894:     unless ($deflevel) { $deflevel=0; }
1.167     www      2895:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2896:     for (my $i=0; $i<=18; $i++) {
                   2897:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2898:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2899:                 ">".&gradeleveldescription($i)."</option>\n";
                   2900:     }
                   2901:     $selectform.="</select>";
                   2902:     return $selectform;
1.163     www      2903: }
1.167     www      2904: 
1.35      matthew  2905: #-------------------------------------------
                   2906: 
1.45      matthew  2907: =pod
                   2908: 
1.1256    raeburn  2909: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2910: 
                   2911: Returns a string containing a <select name='$name' size='1'> form to 
                   2912: allow a user to select the domain to preform an operation in.  
                   2913: See loncreateuser.pm for an example invocation and use.
                   2914: 
1.90      www      2915: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2916: selected");
                   2917: 
1.743     raeburn  2918: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2919: 
1.910     raeburn  2920: 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.
                   2921: 
1.1121    raeburn  2922: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2923: 
                   2924: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2925: 
1.1256    raeburn  2926: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2927: 
1.35      matthew  2928: =cut
                   2929: 
                   2930: #-------------------------------------------
1.34      matthew  2931: sub select_dom_form {
1.1256    raeburn  2932:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2933:     if ($onchange) {
1.874     raeburn  2934:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2935:     }
1.1256    raeburn  2936:     if ($disabled) {
                   2937:         $disabled = ' disabled="disabled"';
                   2938:     }
1.1121    raeburn  2939:     my (@domains,%exclude);
1.910     raeburn  2940:     if (ref($incdoms) eq 'ARRAY') {
                   2941:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2942:     } else {
                   2943:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2944:     }
1.90      www      2945:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2946:     if (ref($excdoms) eq 'ARRAY') {
                   2947:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2948:     }
1.1256    raeburn  2949:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2950:     foreach my $dom (@domains) {
1.1121    raeburn  2951:         next if ($exclude{$dom});
1.356     albertel 2952:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2953:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2954:         if ($showdomdesc) {
                   2955:             if ($dom ne '') {
                   2956:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2957:                 if ($domdesc ne '') {
                   2958:                     $selectdomain .= ' ('.$domdesc.')';
                   2959:                 }
                   2960:             } 
                   2961:         }
                   2962:         $selectdomain .= "</option>\n";
1.34      matthew  2963:     }
                   2964:     $selectdomain.="</select>";
                   2965:     return $selectdomain;
                   2966: }
                   2967: 
1.35      matthew  2968: #-------------------------------------------
                   2969: 
1.45      matthew  2970: =pod
                   2971: 
1.648     raeburn  2972: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2973: 
1.586     raeburn  2974: input: 4 arguments (two required, two optional) - 
                   2975:     $domain - domain of new user
                   2976:     $name - name of form element
                   2977:     $default - Value of 'default' causes a default item to be first 
                   2978:                             option, and selected by default. 
                   2979:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2980:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2981: output: returns 2 items: 
1.586     raeburn  2982: (a) form element which contains either:
                   2983:    (i) <select name="$name">
                   2984:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2985:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2986:        </select>
                   2987:        form item if there are multiple library servers in $domain, or
                   2988:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2989:        if there is only one library server in $domain.
                   2990: 
                   2991: (b) number of library servers found.
                   2992: 
                   2993: See loncreateuser.pm for example of use.
1.35      matthew  2994: 
                   2995: =cut
                   2996: 
                   2997: #-------------------------------------------
1.586     raeburn  2998: sub home_server_form_item {
                   2999:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3000:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3001:     my $result;
                   3002:     my $numlib = keys(%servers);
                   3003:     if ($numlib > 1) {
                   3004:         $result .= '<select name="'.$name.'" />'."\n";
                   3005:         if ($default) {
1.804     bisitz   3006:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3007:                        '</option>'."\n";
                   3008:         }
                   3009:         foreach my $hostid (sort(keys(%servers))) {
                   3010:             $result.= '<option value="'.$hostid.'">'.
                   3011: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3012:         }
                   3013:         $result .= '</select>'."\n";
                   3014:     } elsif ($numlib == 1) {
                   3015:         my $hostid;
                   3016:         foreach my $item (keys(%servers)) {
                   3017:             $hostid = $item;
                   3018:         }
                   3019:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3020:                    $hostid.'" />';
                   3021:                    if (!$hide) {
                   3022:                        $result .= $hostid.' '.$servers{$hostid};
                   3023:                    }
                   3024:                    $result .= "\n";
                   3025:     } elsif ($default) {
                   3026:         $result .= '<input type="hidden" name="'.$name.
                   3027:                    '" value="default" />';
                   3028:                    if (!$hide) {
                   3029:                        $result .= &mt('default');
                   3030:                    }
                   3031:                    $result .= "\n";
1.33      matthew  3032:     }
1.586     raeburn  3033:     return ($result,$numlib);
1.33      matthew  3034: }
1.112     bowersj2 3035: 
                   3036: =pod
                   3037: 
1.534     albertel 3038: =back 
                   3039: 
1.112     bowersj2 3040: =cut
1.87      matthew  3041: 
                   3042: ###############################################################
1.112     bowersj2 3043: ##                  Decoding User Agent                      ##
1.87      matthew  3044: ###############################################################
                   3045: 
                   3046: =pod
                   3047: 
1.112     bowersj2 3048: =head1 Decoding the User Agent
                   3049: 
                   3050: =over 4
                   3051: 
                   3052: =item * &decode_user_agent()
1.87      matthew  3053: 
                   3054: Inputs: $r
                   3055: 
                   3056: Outputs:
                   3057: 
                   3058: =over 4
                   3059: 
1.112     bowersj2 3060: =item * $httpbrowser
1.87      matthew  3061: 
1.112     bowersj2 3062: =item * $clientbrowser
1.87      matthew  3063: 
1.112     bowersj2 3064: =item * $clientversion
1.87      matthew  3065: 
1.112     bowersj2 3066: =item * $clientmathml
1.87      matthew  3067: 
1.112     bowersj2 3068: =item * $clientunicode
1.87      matthew  3069: 
1.112     bowersj2 3070: =item * $clientos
1.87      matthew  3071: 
1.1137    raeburn  3072: =item * $clientmobile
                   3073: 
1.1141    raeburn  3074: =item * $clientinfo
                   3075: 
1.1194    raeburn  3076: =item * $clientosversion
                   3077: 
1.87      matthew  3078: =back
                   3079: 
1.157     matthew  3080: =back 
                   3081: 
1.87      matthew  3082: =cut
                   3083: 
                   3084: ###############################################################
                   3085: ###############################################################
                   3086: sub decode_user_agent {
1.247     albertel 3087:     my ($r)=@_;
1.87      matthew  3088:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3089:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3090:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3091:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3092:     my $clientbrowser='unknown';
                   3093:     my $clientversion='0';
                   3094:     my $clientmathml='';
                   3095:     my $clientunicode='0';
1.1137    raeburn  3096:     my $clientmobile=0;
1.1194    raeburn  3097:     my $clientosversion='';
1.87      matthew  3098:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3099:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3100: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3101: 	    $clientbrowser=$bname;
                   3102:             $httpbrowser=~/$vreg/i;
                   3103: 	    $clientversion=$1;
                   3104:             $clientmathml=($clientversion>=$minv);
                   3105:             $clientunicode=($clientversion>=$univ);
                   3106: 	}
                   3107:     }
                   3108:     my $clientos='unknown';
1.1141    raeburn  3109:     my $clientinfo;
1.87      matthew  3110:     if (($httpbrowser=~/linux/i) ||
                   3111:         ($httpbrowser=~/unix/i) ||
                   3112:         ($httpbrowser=~/ux/i) ||
                   3113:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3114:     if (($httpbrowser=~/vax/i) ||
                   3115:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3116:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3117:     if (($httpbrowser=~/mac/i) ||
                   3118:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3119:     if ($httpbrowser=~/win/i) {
                   3120:         $clientos='win';
                   3121:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3122:             $clientosversion = $1;
                   3123:         }
                   3124:     }
1.87      matthew  3125:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3126:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3127:         $clientmobile=lc($1);
                   3128:     }
1.1141    raeburn  3129:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3130:         $clientinfo = 'firefox-'.$1;
                   3131:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3132:         $clientinfo = 'chromeframe-'.$1;
                   3133:     }
1.87      matthew  3134:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3135:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3136:             $clientosversion);
1.87      matthew  3137: }
                   3138: 
1.32      matthew  3139: ###############################################################
                   3140: ##    Authentication changing form generation subroutines    ##
                   3141: ###############################################################
                   3142: ##
                   3143: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3144: ## hash, and have reasonable default values.
                   3145: ##
                   3146: ##    formname = the name given in the <form> tag.
1.35      matthew  3147: #-------------------------------------------
                   3148: 
1.45      matthew  3149: =pod
                   3150: 
1.112     bowersj2 3151: =head1 Authentication Routines
                   3152: 
                   3153: =over 4
                   3154: 
1.648     raeburn  3155: =item * &authform_xxxxxx()
1.35      matthew  3156: 
                   3157: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3158: handle some of the conveniences required for authentication forms.  
                   3159: This is not an optimal method, but it works.  
                   3160: 
                   3161: =over 4
                   3162: 
1.112     bowersj2 3163: =item * authform_header
1.35      matthew  3164: 
1.112     bowersj2 3165: =item * authform_authorwarning
1.35      matthew  3166: 
1.112     bowersj2 3167: =item * authform_nochange
1.35      matthew  3168: 
1.112     bowersj2 3169: =item * authform_kerberos
1.35      matthew  3170: 
1.112     bowersj2 3171: =item * authform_internal
1.35      matthew  3172: 
1.112     bowersj2 3173: =item * authform_filesystem
1.35      matthew  3174: 
1.1310    raeburn  3175: =item * authform_lti
                   3176: 
1.35      matthew  3177: =back
                   3178: 
1.648     raeburn  3179: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3180: 
1.35      matthew  3181: =cut
                   3182: 
                   3183: #-------------------------------------------
1.32      matthew  3184: sub authform_header{  
                   3185:     my %in = (
                   3186:         formname => 'cu',
1.80      albertel 3187:         kerb_def_dom => '',
1.32      matthew  3188:         @_,
                   3189:     );
                   3190:     $in{'formname'} = 'document.' . $in{'formname'};
                   3191:     my $result='';
1.80      albertel 3192: 
                   3193: #---------------------------------------------- Code for upper case translation
                   3194:     my $Javascript_toUpperCase;
                   3195:     unless ($in{kerb_def_dom}) {
                   3196:         $Javascript_toUpperCase =<<"END";
                   3197:         switch (choice) {
                   3198:            case 'krb': currentform.elements[choicearg].value =
                   3199:                currentform.elements[choicearg].value.toUpperCase();
                   3200:                break;
                   3201:            default:
                   3202:         }
                   3203: END
                   3204:     } else {
                   3205:         $Javascript_toUpperCase = "";
                   3206:     }
                   3207: 
1.165     raeburn  3208:     my $radioval = "'nochange'";
1.591     raeburn  3209:     if (defined($in{'curr_authtype'})) {
                   3210:         if ($in{'curr_authtype'} ne '') {
                   3211:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3212:         }
1.174     matthew  3213:     }
1.165     raeburn  3214:     my $argfield = 'null';
1.591     raeburn  3215:     if (defined($in{'mode'})) {
1.165     raeburn  3216:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3217:             if (defined($in{'curr_autharg'})) {
                   3218:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3219:                     $argfield = "'$in{'curr_autharg'}'";
                   3220:                 }
                   3221:             }
                   3222:         }
                   3223:     }
                   3224: 
1.32      matthew  3225:     $result.=<<"END";
                   3226: var current = new Object();
1.165     raeburn  3227: current.radiovalue = $radioval;
                   3228: current.argfield = $argfield;
1.32      matthew  3229: 
                   3230: function changed_radio(choice,currentform) {
                   3231:     var choicearg = choice + 'arg';
                   3232:     // If a radio button in changed, we need to change the argfield
                   3233:     if (current.radiovalue != choice) {
                   3234:         current.radiovalue = choice;
                   3235:         if (current.argfield != null) {
                   3236:             currentform.elements[current.argfield].value = '';
                   3237:         }
                   3238:         if (choice == 'nochange') {
                   3239:             current.argfield = null;
                   3240:         } else {
                   3241:             current.argfield = choicearg;
                   3242:             switch(choice) {
                   3243:                 case 'krb': 
                   3244:                     currentform.elements[current.argfield].value = 
                   3245:                         "$in{'kerb_def_dom'}";
                   3246:                 break;
                   3247:               default:
                   3248:                 break;
                   3249:             }
                   3250:         }
                   3251:     }
                   3252:     return;
                   3253: }
1.22      www      3254: 
1.32      matthew  3255: function changed_text(choice,currentform) {
                   3256:     var choicearg = choice + 'arg';
                   3257:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3258:         $Javascript_toUpperCase
1.32      matthew  3259:         // clear old field
                   3260:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3261:             currentform.elements[current.argfield].value = '';
                   3262:         }
                   3263:         current.argfield = choicearg;
                   3264:     }
                   3265:     set_auth_radio_buttons(choice,currentform);
                   3266:     return;
1.20      www      3267: }
1.32      matthew  3268: 
                   3269: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3270:     var numauthchoices = currentform.login.length;
                   3271:     if (typeof numauthchoices  == "undefined") {
                   3272:         return;
                   3273:     } 
1.32      matthew  3274:     var i=0;
1.986     raeburn  3275:     while (i < numauthchoices) {
1.32      matthew  3276:         if (currentform.login[i].value == newvalue) { break; }
                   3277:         i++;
                   3278:     }
1.986     raeburn  3279:     if (i == numauthchoices) {
1.32      matthew  3280:         return;
                   3281:     }
                   3282:     current.radiovalue = newvalue;
                   3283:     currentform.login[i].checked = true;
                   3284:     return;
                   3285: }
                   3286: END
                   3287:     return $result;
                   3288: }
                   3289: 
1.1106    raeburn  3290: sub authform_authorwarning {
1.32      matthew  3291:     my $result='';
1.144     matthew  3292:     $result='<i>'.
                   3293:         &mt('As a general rule, only authors or co-authors should be '.
                   3294:             'filesystem authenticated '.
                   3295:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3296:     return $result;
                   3297: }
                   3298: 
1.1106    raeburn  3299: sub authform_nochange {
1.32      matthew  3300:     my %in = (
                   3301:               formname => 'document.cu',
                   3302:               kerb_def_dom => 'MSU.EDU',
                   3303:               @_,
                   3304:           );
1.1106    raeburn  3305:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3306:     my $result;
1.1104    raeburn  3307:     if (!$authnum) {
1.1105    raeburn  3308:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3309:     } else {
                   3310:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3311:                   '<input type="radio" name="login" value="nochange" '.
                   3312:                   'checked="checked" onclick="'.
1.281     albertel 3313:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3314: 	    '</label>';
1.586     raeburn  3315:     }
1.32      matthew  3316:     return $result;
                   3317: }
                   3318: 
1.591     raeburn  3319: sub authform_kerberos {
1.32      matthew  3320:     my %in = (
                   3321:               formname => 'document.cu',
                   3322:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3323:               kerb_def_auth => 'krb4',
1.32      matthew  3324:               @_,
                   3325:               );
1.586     raeburn  3326:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3327:         $autharg,$jscall,$disabled);
1.1106    raeburn  3328:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3329:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3330:        $check5 = ' checked="checked"';
1.80      albertel 3331:     } else {
1.772     bisitz   3332:        $check4 = ' checked="checked"';
1.80      albertel 3333:     }
1.1259    raeburn  3334:     if ($in{'readonly'}) {
                   3335:         $disabled = ' disabled="disabled"';
                   3336:     }
1.165     raeburn  3337:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3338:     if (defined($in{'curr_authtype'})) {
                   3339:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3340:             $krbcheck = ' checked="checked"';
1.623     raeburn  3341:             if (defined($in{'mode'})) {
                   3342:                 if ($in{'mode'} eq 'modifyuser') {
                   3343:                     $krbcheck = '';
                   3344:                 }
                   3345:             }
1.591     raeburn  3346:             if (defined($in{'curr_kerb_ver'})) {
                   3347:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3348:                     $check5 = ' checked="checked"';
1.591     raeburn  3349:                     $check4 = '';
                   3350:                 } else {
1.772     bisitz   3351:                     $check4 = ' checked="checked"';
1.591     raeburn  3352:                     $check5 = '';
                   3353:                 }
1.586     raeburn  3354:             }
1.591     raeburn  3355:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3356:                 $krbarg = $in{'curr_autharg'};
                   3357:             }
1.586     raeburn  3358:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3359:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3360:                     $result = 
                   3361:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3362:         $in{'curr_autharg'},$krbver);
                   3363:                 } else {
                   3364:                     $result =
                   3365:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3366:                 }
                   3367:                 return $result; 
                   3368:             }
                   3369:         }
                   3370:     } else {
                   3371:         if ($authnum == 1) {
1.784     bisitz   3372:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3373:         }
                   3374:     }
1.586     raeburn  3375:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3376:         return;
1.587     raeburn  3377:     } elsif ($authtype eq '') {
1.591     raeburn  3378:         if (defined($in{'mode'})) {
1.587     raeburn  3379:             if ($in{'mode'} eq 'modifycourse') {
                   3380:                 if ($authnum == 1) {
1.1259    raeburn  3381:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3382:                 }
                   3383:             }
                   3384:         }
1.586     raeburn  3385:     }
                   3386:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3387:     if ($authtype eq '') {
                   3388:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3389:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3390:                     $krbcheck.$disabled.' />';
1.586     raeburn  3391:     }
                   3392:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3393:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3394:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3395:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3396:          $in{'curr_authtype'} eq 'krb4')) {
                   3397:         $result .= &mt
1.144     matthew  3398:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3399:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3400:          '<label>'.$authtype,
1.281     albertel 3401:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3402:              'value="'.$krbarg.'" '.
1.1259    raeburn  3403:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3404:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3405:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3406: 	 '</label>');
1.586     raeburn  3407:     } elsif ($can_assign{'krb4'}) {
                   3408:         $result .= &mt
                   3409:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3410:          '[_3] Version 4 [_4]',
                   3411:          '<label>'.$authtype,
                   3412:          '</label><input type="text" size="10" name="krbarg" '.
                   3413:              'value="'.$krbarg.'" '.
1.1259    raeburn  3414:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3415:          '<label><input type="hidden" name="krbver" value="4" />',
                   3416:          '</label>');
                   3417:     } elsif ($can_assign{'krb5'}) {
                   3418:         $result .= &mt
                   3419:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3420:          '[_3] Version 5 [_4]',
                   3421:          '<label>'.$authtype,
                   3422:          '</label><input type="text" size="10" name="krbarg" '.
                   3423:              'value="'.$krbarg.'" '.
1.1259    raeburn  3424:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3425:          '<label><input type="hidden" name="krbver" value="5" />',
                   3426:          '</label>');
                   3427:     }
1.32      matthew  3428:     return $result;
                   3429: }
                   3430: 
1.1106    raeburn  3431: sub authform_internal {
1.586     raeburn  3432:     my %in = (
1.32      matthew  3433:                 formname => 'document.cu',
                   3434:                 kerb_def_dom => 'MSU.EDU',
                   3435:                 @_,
                   3436:                 );
1.1259    raeburn  3437:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3438:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3439:     if ($in{'readonly'}) {
                   3440:         $disabled = ' disabled="disabled"';
                   3441:     }
1.591     raeburn  3442:     if (defined($in{'curr_authtype'})) {
                   3443:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3444:             if ($can_assign{'int'}) {
1.772     bisitz   3445:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3446:                 if (defined($in{'mode'})) {
                   3447:                     if ($in{'mode'} eq 'modifyuser') {
                   3448:                         $intcheck = '';
                   3449:                     }
                   3450:                 }
1.591     raeburn  3451:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3452:                     $intarg = $in{'curr_autharg'};
                   3453:                 }
                   3454:             } else {
                   3455:                 $result = &mt('Currently internally authenticated.');
                   3456:                 return $result;
1.165     raeburn  3457:             }
                   3458:         }
1.586     raeburn  3459:     } else {
                   3460:         if ($authnum == 1) {
1.784     bisitz   3461:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3462:         }
                   3463:     }
                   3464:     if (!$can_assign{'int'}) {
                   3465:         return;
1.587     raeburn  3466:     } elsif ($authtype eq '') {
1.591     raeburn  3467:         if (defined($in{'mode'})) {
1.587     raeburn  3468:             if ($in{'mode'} eq 'modifycourse') {
                   3469:                 if ($authnum == 1) {
1.1259    raeburn  3470:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3471:                 }
                   3472:             }
                   3473:         }
1.165     raeburn  3474:     }
1.586     raeburn  3475:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3476:     if ($authtype eq '') {
                   3477:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3478:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3479:     }
1.605     bisitz   3480:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3481:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3482:     $result = &mt
1.144     matthew  3483:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3484:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3485:     $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  3486:     return $result;
                   3487: }
                   3488: 
1.1104    raeburn  3489: sub authform_local {
1.32      matthew  3490:     my %in = (
                   3491:               formname => 'document.cu',
                   3492:               kerb_def_dom => 'MSU.EDU',
                   3493:               @_,
                   3494:               );
1.1259    raeburn  3495:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3496:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3497:     if ($in{'readonly'}) {
                   3498:         $disabled = ' disabled="disabled"';
                   3499:     } 
1.591     raeburn  3500:     if (defined($in{'curr_authtype'})) {
                   3501:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3502:             if ($can_assign{'loc'}) {
1.772     bisitz   3503:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3504:                 if (defined($in{'mode'})) {
                   3505:                     if ($in{'mode'} eq 'modifyuser') {
                   3506:                         $loccheck = '';
                   3507:                     }
                   3508:                 }
1.591     raeburn  3509:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3510:                     $locarg = $in{'curr_autharg'};
                   3511:                 }
                   3512:             } else {
                   3513:                 $result = &mt('Currently using local (institutional) authentication.');
                   3514:                 return $result;
1.165     raeburn  3515:             }
                   3516:         }
1.586     raeburn  3517:     } else {
                   3518:         if ($authnum == 1) {
1.784     bisitz   3519:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3520:         }
                   3521:     }
                   3522:     if (!$can_assign{'loc'}) {
                   3523:         return;
1.587     raeburn  3524:     } elsif ($authtype eq '') {
1.591     raeburn  3525:         if (defined($in{'mode'})) {
1.587     raeburn  3526:             if ($in{'mode'} eq 'modifycourse') {
                   3527:                 if ($authnum == 1) {
1.1259    raeburn  3528:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3529:                 }
                   3530:             }
                   3531:         }
1.165     raeburn  3532:     }
1.586     raeburn  3533:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3534:     if ($authtype eq '') {
                   3535:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3536:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3537:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3538:     }
                   3539:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3540:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3541:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3542:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3543:     return $result;
                   3544: }
                   3545: 
1.1106    raeburn  3546: sub authform_filesystem {
1.32      matthew  3547:     my %in = (
                   3548:               formname => 'document.cu',
                   3549:               kerb_def_dom => 'MSU.EDU',
                   3550:               @_,
                   3551:               );
1.1259    raeburn  3552:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3553:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3554:     if ($in{'readonly'}) {
                   3555:         $disabled = ' disabled="disabled"';
                   3556:     }
1.591     raeburn  3557:     if (defined($in{'curr_authtype'})) {
                   3558:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3559:             if ($can_assign{'fsys'}) {
1.772     bisitz   3560:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3561:                 if (defined($in{'mode'})) {
                   3562:                     if ($in{'mode'} eq 'modifyuser') {
                   3563:                         $fsyscheck = '';
                   3564:                     }
                   3565:                 }
1.586     raeburn  3566:             } else {
                   3567:                 $result = &mt('Currently Filesystem Authenticated.');
                   3568:                 return $result;
1.1259    raeburn  3569:             }
1.586     raeburn  3570:         }
                   3571:     } else {
                   3572:         if ($authnum == 1) {
1.784     bisitz   3573:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3574:         }
                   3575:     }
                   3576:     if (!$can_assign{'fsys'}) {
                   3577:         return;
1.587     raeburn  3578:     } elsif ($authtype eq '') {
1.591     raeburn  3579:         if (defined($in{'mode'})) {
1.587     raeburn  3580:             if ($in{'mode'} eq 'modifycourse') {
                   3581:                 if ($authnum == 1) {
1.1259    raeburn  3582:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3583:                 }
                   3584:             }
                   3585:         }
1.586     raeburn  3586:     }
                   3587:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3588:     if ($authtype eq '') {
                   3589:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3590:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3591:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3592:     }
1.1310    raeburn  3593:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3594:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3595:     $result = &mt
1.144     matthew  3596:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3597:          '<label>'.$authtype,'</label>'.$autharg);
                   3598:     return $result;
                   3599: }
                   3600: 
                   3601: sub authform_lti {
                   3602:     my %in = (
                   3603:               formname => 'document.cu',
                   3604:               kerb_def_dom => 'MSU.EDU',
                   3605:               @_,
                   3606:               );
                   3607:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3608:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3609:     if ($in{'readonly'}) {
                   3610:         $disabled = ' disabled="disabled"';
                   3611:     }
                   3612:     if (defined($in{'curr_authtype'})) {
                   3613:         if ($in{'curr_authtype'} eq 'lti') {
                   3614:             if ($can_assign{'lti'}) {
                   3615:                 $lticheck = 'checked="checked" ';
                   3616:                 if (defined($in{'mode'})) {
                   3617:                     if ($in{'mode'} eq 'modifyuser') {
                   3618:                         $lticheck = '';
                   3619:                     }
                   3620:                 }
                   3621:             } else {
                   3622:                 $result = &mt('Currently LTI Authenticated.');
                   3623:                 return $result;
                   3624:             }
                   3625:         }
                   3626:     } else {
                   3627:         if ($authnum == 1) {
                   3628:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3629:         }
                   3630:     }
                   3631:     if (!$can_assign{'lti'}) {
                   3632:         return;
                   3633:     } elsif ($authtype eq '') {
                   3634:         if (defined($in{'mode'})) {
                   3635:             if ($in{'mode'} eq 'modifycourse') {
                   3636:                 if ($authnum == 1) {
                   3637:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3638:                 }
                   3639:             }
                   3640:         }
                   3641:     }
                   3642:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3643:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3644:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3645:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3646:                     $jscall.'"'.$disabled.' />';
                   3647:     }
                   3648:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3649:     if ($authtype) {
                   3650:         $result = &mt('[_1] LTI Authenticated',
                   3651:                       '<label>'.$authtype.'</label>'.$autharg);
                   3652:     } else {
                   3653:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3654:                   $autharg;
                   3655:     }
1.32      matthew  3656:     return $result;
                   3657: }
                   3658: 
1.586     raeburn  3659: sub get_assignable_auth {
                   3660:     my ($dom) = @_;
                   3661:     if ($dom eq '') {
                   3662:         $dom = $env{'request.role.domain'};
                   3663:     }
                   3664:     my %can_assign = (
                   3665:                           krb4 => 1,
                   3666:                           krb5 => 1,
                   3667:                           int  => 1,
                   3668:                           loc  => 1,
1.1310    raeburn  3669:                           lti  => 1,
1.586     raeburn  3670:                      );
                   3671:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3672:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3673:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3674:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3675:             my $context;
                   3676:             if ($env{'request.role'} =~ /^au/) {
                   3677:                 $context = 'author';
1.1259    raeburn  3678:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3679:                 $context = 'domain';
                   3680:             } elsif ($env{'request.course.id'}) {
                   3681:                 $context = 'course';
                   3682:             }
                   3683:             if ($context) {
                   3684:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3685:                    %can_assign = %{$authhash->{$context}}; 
                   3686:                 }
                   3687:             }
                   3688:         }
                   3689:     }
                   3690:     my $authnum = 0;
                   3691:     foreach my $key (keys(%can_assign)) {
                   3692:         if ($can_assign{$key}) {
                   3693:             $authnum ++;
                   3694:         }
                   3695:     }
                   3696:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3697:         $authnum --;
                   3698:     }
                   3699:     return ($authnum,%can_assign);
                   3700: }
                   3701: 
1.1331    raeburn  3702: sub check_passwd_rules {
                   3703:     my ($domain,$plainpass) = @_;
                   3704:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3705:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3706:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3707:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3708:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3709:             if ($passwdconf{'min'} > $min) {
                   3710:                 $min = $passwdconf{'min'};
                   3711:             }
1.1331    raeburn  3712:         }
                   3713:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3714:             $max = $passwdconf{'max'};
                   3715:         }
                   3716:         @chars = @{$passwdconf{'chars'}};
                   3717:     }
                   3718:     if (($min) && (length($plainpass) < $min)) {
                   3719:         push(@brokerule,'min');
                   3720:     }
                   3721:     if (($max) && (length($plainpass) > $max)) {
                   3722:         push(@brokerule,'max');
                   3723:     }
                   3724:     if (@chars) {
                   3725:         my %rules;
                   3726:         map { $rules{$_} = 1; } @chars;
                   3727:         if ($rules{'uc'}) {
                   3728:             unless ($plainpass =~ /[A-Z]/) {
                   3729:                 push(@brokerule,'uc');
                   3730:             }
                   3731:         }
                   3732:         if ($rules{'lc'}) {
1.1332    raeburn  3733:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3734:                 push(@brokerule,'lc');
                   3735:             }
                   3736:         }
                   3737:         if ($rules{'num'}) {
                   3738:             unless ($plainpass =~ /\d/) {
                   3739:                 push(@brokerule,'num');
                   3740:             }
                   3741:         }
                   3742:         if ($rules{'spec'}) {
                   3743:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3744:                 push(@brokerule,'spec');
                   3745:             }
                   3746:         }
                   3747:     }
                   3748:     if (@brokerule) {
                   3749:         my %rulenames = &Apache::lonlocal::texthash(
                   3750:             uc   => 'At least one upper case letter',
                   3751:             lc   => 'At least one lower case letter',
                   3752:             num  => 'At least one number',
                   3753:             spec => 'At least one non-alphanumeric',
                   3754:         );
                   3755:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3756:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3757:         $rulenames{'num'} .= ': 0123456789';
                   3758:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3759:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3760:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3761:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3762:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3763:             if (grep(/^$rule$/,@brokerule)) {
                   3764:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3765:             }
                   3766:         }
                   3767:         $warning .= '</ul>';
                   3768:     }
1.1332    raeburn  3769:     if (wantarray) {
                   3770:         return @brokerule;
                   3771:     }
1.1331    raeburn  3772:     return $warning;
                   3773: }
                   3774: 
1.1376    raeburn  3775: sub passwd_validation_js {
1.1377    raeburn  3776:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3777:     my (%passwdconf,$alertmsg);
                   3778:     if ($context eq 'linkprot') {
                   3779:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3780:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3781:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3782:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3783:             }
                   3784:         }
                   3785:         if ($id eq 'add') {
                   3786:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3787:         } elsif ($id =~ /^\d+$/) {
                   3788:             my $pos = $id+1;
                   3789:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3790:         } else {
                   3791:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3792:         }
                   3793:     } else {
                   3794:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3795:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3796:     }
1.1376    raeburn  3797:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3798:     $numrules = 0;
                   3799:     $min = $Apache::lonnet::passwdmin;
                   3800:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3801:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3802:             if ($passwdconf{'min'} > $min) {
                   3803:                 $min = $passwdconf{'min'};
                   3804:             }
                   3805:         }
                   3806:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3807:             $max = $passwdconf{'max'};
                   3808:             $numrules ++;
                   3809:         }
                   3810:         @chars = @{$passwdconf{'chars'}};
                   3811:         if (@chars) {
                   3812:             $numrules ++;
                   3813:         }
                   3814:     }
                   3815:     if ($min > 0) {
                   3816:         $numrules ++;
                   3817:     }
                   3818:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3819:         if ($min) {
                   3820:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3821:         }
                   3822:         if ($max) {
                   3823:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3824:         }
                   3825:         my (@charalerts,@charrules);
                   3826:         if (@chars) {
                   3827:             if (grep(/^uc$/,@chars)) {
                   3828:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3829:                 push(@charrules,'uc');
                   3830:             }
                   3831:             if (grep(/^lc$/,@chars)) {
                   3832:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3833:                 push(@charrules,'lc');
                   3834:             }
                   3835:             if (grep(/^num$/,@chars)) {
                   3836:                 push(@charalerts,&mt('contain at least one number'));
                   3837:                 push(@charrules,'num');
                   3838:             }
                   3839:             if (grep(/^spec$/,@chars)) {
                   3840:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3841:                 push(@charrules,'spec');
                   3842:             }
                   3843:         }
                   3844:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3845:                     qq|            var currpwval = $currpasswdval;\n|;
                   3846:             if ($min) {
                   3847:                 $intargjs .= qq|
                   3848:             if (currpwval.length < $min) {
                   3849:                 rulesmsg += ' - $alert{min}';
                   3850:             }
                   3851: |;
                   3852:             }
                   3853:             if ($max) {
                   3854:                 $intargjs .= qq|
                   3855:             if (currpwval.length > $max) {
                   3856:                 rulesmsg += ' - $alert{max}';
                   3857:             }
                   3858: |;
                   3859:             }
                   3860:             if (@chars > 0) {
                   3861:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3862:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3863:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3864:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3865:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3866:                 my %rules;
                   3867:                 map { $rules{$_} = 1; } @chars;
                   3868:                 if ($rules{'uc'}) {
                   3869:                     $intargjs .= qq|
                   3870:             var ucRegExp = /[A-Z]/;
                   3871:             if (!ucRegExp.test(currpwval)) {
                   3872:                 brokerules.push('uc');
                   3873:             }
                   3874: |;
                   3875:                 }
                   3876:                 if ($rules{'lc'}) {
                   3877:                     $intargjs .= qq|
                   3878:             var lcRegExp = /[a-z]/;
                   3879:             if (!lcRegExp.test(currpwval)) {
                   3880:                 brokerules.push('lc');
                   3881:             }
                   3882: |;
                   3883:                 }
                   3884:                 if ($rules{'num'}) {
                   3885:                      $intargjs .= qq|
                   3886:             var numRegExp = /[0-9]/;
                   3887:             if (!numRegExp.test(currpwval)) {
                   3888:                 brokerules.push('num');
                   3889:             }
                   3890: |;
                   3891:                 }
                   3892:                 if ($rules{'spec'}) {
                   3893:                      $intargjs .= q|
                   3894:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3895:             if (!specRegExp.test(currpwval)) {
                   3896:                 brokerules.push('spec');
                   3897:             }
                   3898: |;
                   3899:                 }
                   3900:                 $intargjs .= qq|
                   3901:             if (brokerules.length > 0) {
                   3902:                 for (var i=0; i<brokerules.length; i++) {
                   3903:                     for (var j=0; j<charrules.length; j++) {
                   3904:                         if (brokerules[i] == charrules[j]) {
                   3905:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3906:                             break;
                   3907:                         }
                   3908:                     }
                   3909:                 }
                   3910:             }
                   3911: |;
                   3912:             }
                   3913:             $intargjs .= qq|
                   3914:             if (rulesmsg != '') {
                   3915:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3916:                 alert(rulesmsg);
                   3917:                 return false;
                   3918:             }
                   3919: |;
                   3920:     }
                   3921:     return ($numrules,$intargjs);
                   3922: }
                   3923: 
1.80      albertel 3924: ###############################################################
                   3925: ##    Get Kerberos Defaults for Domain                 ##
                   3926: ###############################################################
                   3927: ##
                   3928: ## Returns default kerberos version and an associated argument
                   3929: ## as listed in file domain.tab. If not listed, provides
                   3930: ## appropriate default domain and kerberos version.
                   3931: ##
                   3932: #-------------------------------------------
                   3933: 
                   3934: =pod
                   3935: 
1.648     raeburn  3936: =item * &get_kerberos_defaults()
1.80      albertel 3937: 
                   3938: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3939: version and domain. If not found, it defaults to version 4 and the 
                   3940: domain of the server.
1.80      albertel 3941: 
1.648     raeburn  3942: =over 4
                   3943: 
1.80      albertel 3944: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3945: 
1.648     raeburn  3946: =back
                   3947: 
                   3948: =back
                   3949: 
1.80      albertel 3950: =cut
                   3951: 
                   3952: #-------------------------------------------
                   3953: sub get_kerberos_defaults {
                   3954:     my $domain=shift;
1.641     raeburn  3955:     my ($krbdef,$krbdefdom);
                   3956:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3957:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3958:         $krbdef = $domdefaults{'auth_def'};
                   3959:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3960:     } else {
1.80      albertel 3961:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3962:         my $krbdefdom=$1;
                   3963:         $krbdefdom=~tr/a-z/A-Z/;
                   3964:         $krbdef = "krb4";
                   3965:     }
                   3966:     return ($krbdef,$krbdefdom);
                   3967: }
1.112     bowersj2 3968: 
1.32      matthew  3969: 
1.46      matthew  3970: ###############################################################
                   3971: ##                Thesaurus Functions                        ##
                   3972: ###############################################################
1.20      www      3973: 
1.46      matthew  3974: =pod
1.20      www      3975: 
1.112     bowersj2 3976: =head1 Thesaurus Functions
                   3977: 
                   3978: =over 4
                   3979: 
1.648     raeburn  3980: =item * &initialize_keywords()
1.46      matthew  3981: 
                   3982: Initializes the package variable %Keywords if it is empty.  Uses the
                   3983: package variable $thesaurus_db_file.
                   3984: 
                   3985: =cut
                   3986: 
                   3987: ###################################################
                   3988: 
                   3989: sub initialize_keywords {
                   3990:     return 1 if (scalar keys(%Keywords));
                   3991:     # If we are here, %Keywords is empty, so fill it up
                   3992:     #   Make sure the file we need exists...
                   3993:     if (! -e $thesaurus_db_file) {
                   3994:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3995:                                  " failed because it does not exist");
                   3996:         return 0;
                   3997:     }
                   3998:     #   Set up the hash as a database
                   3999:     my %thesaurus_db;
                   4000:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4001:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4002:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4003:                                  $thesaurus_db_file);
                   4004:         return 0;
                   4005:     } 
                   4006:     #  Get the average number of appearances of a word.
                   4007:     my $avecount = $thesaurus_db{'average.count'};
                   4008:     #  Put keywords (those that appear > average) into %Keywords
                   4009:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4010:         my ($count,undef) = split /:/,$data;
                   4011:         $Keywords{$word}++ if ($count > $avecount);
                   4012:     }
                   4013:     untie %thesaurus_db;
                   4014:     # Remove special values from %Keywords.
1.356     albertel 4015:     foreach my $value ('total.count','average.count') {
                   4016:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4017:   }
1.46      matthew  4018:     return 1;
                   4019: }
                   4020: 
                   4021: ###################################################
                   4022: 
                   4023: =pod
                   4024: 
1.648     raeburn  4025: =item * &keyword($word)
1.46      matthew  4026: 
                   4027: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4028: than the average number of times in the thesaurus database.  Calls 
                   4029: &initialize_keywords
                   4030: 
                   4031: =cut
                   4032: 
                   4033: ###################################################
1.20      www      4034: 
                   4035: sub keyword {
1.46      matthew  4036:     return if (!&initialize_keywords());
                   4037:     my $word=lc(shift());
                   4038:     $word=~s/\W//g;
                   4039:     return exists($Keywords{$word});
1.20      www      4040: }
1.46      matthew  4041: 
                   4042: ###############################################################
                   4043: 
                   4044: =pod 
1.20      www      4045: 
1.648     raeburn  4046: =item * &get_related_words()
1.46      matthew  4047: 
1.160     matthew  4048: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4049: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4050: will be returned.  The order of the words returned is determined by the
                   4051: database which holds them.
                   4052: 
                   4053: Uses global $thesaurus_db_file.
                   4054: 
1.1057    foxr     4055: 
1.46      matthew  4056: =cut
                   4057: 
                   4058: ###############################################################
                   4059: sub get_related_words {
                   4060:     my $keyword = shift;
                   4061:     my %thesaurus_db;
                   4062:     if (! -e $thesaurus_db_file) {
                   4063:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4064:                                  "failed because the file does not exist");
                   4065:         return ();
                   4066:     }
                   4067:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4068:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4069:         return ();
                   4070:     } 
                   4071:     my @Words=();
1.429     www      4072:     my $count=0;
1.46      matthew  4073:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4074: 	# The first element is the number of times
                   4075: 	# the word appears.  We do not need it now.
1.429     www      4076: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4077: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4078: 	my $threshold=$mostfrequentcount/10;
                   4079:         foreach my $possibleword (@RelatedWords) {
                   4080:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4081:             if ($wordcount>$threshold) {
                   4082: 		push(@Words,$word);
                   4083:                 $count++;
                   4084:                 if ($count>10) { last; }
                   4085: 	    }
1.20      www      4086:         }
                   4087:     }
1.46      matthew  4088:     untie %thesaurus_db;
                   4089:     return @Words;
1.14      harris41 4090: }
1.1090    foxr     4091: ###############################################################
                   4092: #
                   4093: #  Spell checking
                   4094: #
                   4095: 
                   4096: =pod
                   4097: 
1.1142    raeburn  4098: =back
                   4099: 
1.1090    foxr     4100: =head1 Spell checking
                   4101: 
                   4102: =over 4
                   4103: 
                   4104: =item * &check_spelling($wordlist $language)
                   4105: 
                   4106: Takes a string containing words and feeds it to an external
                   4107: spellcheck program via a pipeline. Returns a string containing
                   4108: them mis-spelled words.
                   4109: 
                   4110: Parameters:
                   4111: 
                   4112: =over 4
                   4113: 
                   4114: =item - $wordlist
                   4115: 
                   4116: String that will be fed into the spellcheck program.
                   4117: 
                   4118: =item - $language
                   4119: 
                   4120: Language string that specifies the language for which the spell
                   4121: check will be performed.
                   4122: 
                   4123: =back
                   4124: 
                   4125: =back
                   4126: 
                   4127: Note: This sub assumes that aspell is installed.
                   4128: 
                   4129: 
                   4130: =cut
                   4131: 
1.46      matthew  4132: 
1.1090    foxr     4133: sub check_spelling {
                   4134:     my ($wordlist, $language) = @_;
1.1091    foxr     4135:     my @misspellings;
                   4136:     
                   4137:     # Generate the speller and set the langauge.
                   4138:     # if explicitly selected:
1.1090    foxr     4139: 
1.1091    foxr     4140:     my $speller = Text::Aspell->new;
1.1090    foxr     4141:     if ($language) {
1.1091    foxr     4142: 	$speller->set_option('lang', $language);
1.1090    foxr     4143:     }
                   4144: 
1.1091    foxr     4145:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4146: 
1.1091    foxr     4147:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4148: 
1.1091    foxr     4149:     foreach my $word (@words) {
                   4150: 	if(! $speller->check($word)) {
                   4151: 	    push(@misspellings, $word);
1.1090    foxr     4152: 	}
                   4153:     }
1.1091    foxr     4154:     return join(' ', @misspellings);
                   4155:     
1.1090    foxr     4156: }
                   4157: 
1.61      www      4158: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4159: =pod
                   4160: 
1.112     bowersj2 4161: =head1 User Name Functions
                   4162: 
                   4163: =over 4
                   4164: 
1.648     raeburn  4165: =item * &plainname($uname,$udom,$first)
1.81      albertel 4166: 
1.112     bowersj2 4167: Takes a users logon name and returns it as a string in
1.226     albertel 4168: "first middle last generation" form 
                   4169: if $first is set to 'lastname' then it returns it as
                   4170: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4171: 
                   4172: =cut
1.61      www      4173: 
1.295     www      4174: 
1.81      albertel 4175: ###############################################################
1.61      www      4176: sub plainname {
1.226     albertel 4177:     my ($uname,$udom,$first)=@_;
1.537     albertel 4178:     return if (!defined($uname) || !defined($udom));
1.295     www      4179:     my %names=&getnames($uname,$udom);
1.226     albertel 4180:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4181: 					  $names{'middlename'},
                   4182: 					  $names{'lastname'},
                   4183: 					  $names{'generation'},$first);
                   4184:     $name=~s/^\s+//;
1.62      www      4185:     $name=~s/\s+$//;
                   4186:     $name=~s/\s+/ /g;
1.353     albertel 4187:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4188:     return $name;
1.61      www      4189: }
1.66      www      4190: 
                   4191: # -------------------------------------------------------------------- Nickname
1.81      albertel 4192: =pod
                   4193: 
1.648     raeburn  4194: =item * &nickname($uname,$udom)
1.81      albertel 4195: 
                   4196: Gets a users name and returns it as a string as
                   4197: 
                   4198: "&quot;nickname&quot;"
1.66      www      4199: 
1.81      albertel 4200: if the user has a nickname or
                   4201: 
                   4202: "first middle last generation"
                   4203: 
                   4204: if the user does not
                   4205: 
                   4206: =cut
1.66      www      4207: 
                   4208: sub nickname {
                   4209:     my ($uname,$udom)=@_;
1.537     albertel 4210:     return if (!defined($uname) || !defined($udom));
1.295     www      4211:     my %names=&getnames($uname,$udom);
1.68      albertel 4212:     my $name=$names{'nickname'};
1.66      www      4213:     if ($name) {
                   4214:        $name='&quot;'.$name.'&quot;'; 
                   4215:     } else {
                   4216:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4217: 	     $names{'lastname'}.' '.$names{'generation'};
                   4218:        $name=~s/\s+$//;
                   4219:        $name=~s/\s+/ /g;
                   4220:     }
                   4221:     return $name;
                   4222: }
                   4223: 
1.295     www      4224: sub getnames {
                   4225:     my ($uname,$udom)=@_;
1.537     albertel 4226:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4227:     if ($udom eq 'public' && $uname eq 'public') {
                   4228: 	return ('lastname' => &mt('Public'));
                   4229:     }
1.295     www      4230:     my $id=$uname.':'.$udom;
                   4231:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4232:     if ($cached) {
                   4233: 	return %{$names};
                   4234:     } else {
                   4235: 	my %loadnames=&Apache::lonnet::get('environment',
                   4236:                     ['firstname','middlename','lastname','generation','nickname'],
                   4237: 					 $udom,$uname);
                   4238: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4239: 	return %loadnames;
                   4240:     }
                   4241: }
1.61      www      4242: 
1.542     raeburn  4243: # -------------------------------------------------------------------- getemails
1.648     raeburn  4244: 
1.542     raeburn  4245: =pod
                   4246: 
1.648     raeburn  4247: =item * &getemails($uname,$udom)
1.542     raeburn  4248: 
                   4249: Gets a user's email information and returns it as a hash with keys:
                   4250: notification, critnotification, permanentemail
                   4251: 
                   4252: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4253: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4254:  
1.648     raeburn  4255: 
1.542     raeburn  4256: =cut
                   4257: 
1.648     raeburn  4258: 
1.466     albertel 4259: sub getemails {
                   4260:     my ($uname,$udom)=@_;
                   4261:     if ($udom eq 'public' && $uname eq 'public') {
                   4262: 	return;
                   4263:     }
1.467     www      4264:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4265:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4266:     my $id=$uname.':'.$udom;
                   4267:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4268:     if ($cached) {
                   4269: 	return %{$names};
                   4270:     } else {
                   4271: 	my %loadnames=&Apache::lonnet::get('environment',
                   4272:                     			   ['notification','critnotification',
                   4273: 					    'permanentemail'],
                   4274: 					   $udom,$uname);
                   4275: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4276: 	return %loadnames;
                   4277:     }
                   4278: }
                   4279: 
1.551     albertel 4280: sub flush_email_cache {
                   4281:     my ($uname,$udom)=@_;
                   4282:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4283:     if (!$uname) { $uname=$env{'user.name'};   }
                   4284:     return if ($udom eq 'public' && $uname eq 'public');
                   4285:     my $id=$uname.':'.$udom;
                   4286:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4287: }
                   4288: 
1.728     raeburn  4289: # -------------------------------------------------------------------- getlangs
                   4290: 
                   4291: =pod
                   4292: 
                   4293: =item * &getlangs($uname,$udom)
                   4294: 
                   4295: Gets a user's language preference and returns it as a hash with key:
                   4296: language.
                   4297: 
                   4298: =cut
                   4299: 
                   4300: 
                   4301: sub getlangs {
                   4302:     my ($uname,$udom) = @_;
                   4303:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4304:     if (!$uname) { $uname=$env{'user.name'};   }
                   4305:     my $id=$uname.':'.$udom;
                   4306:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4307:     if ($cached) {
                   4308:         return %{$langs};
                   4309:     } else {
                   4310:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4311:                                            $udom,$uname);
                   4312:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4313:         return %loadlangs;
                   4314:     }
                   4315: }
                   4316: 
                   4317: sub flush_langs_cache {
                   4318:     my ($uname,$udom)=@_;
                   4319:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4320:     if (!$uname) { $uname=$env{'user.name'};   }
                   4321:     return if ($udom eq 'public' && $uname eq 'public');
                   4322:     my $id=$uname.':'.$udom;
                   4323:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4324: }
                   4325: 
1.61      www      4326: # ------------------------------------------------------------------ Screenname
1.81      albertel 4327: 
                   4328: =pod
                   4329: 
1.648     raeburn  4330: =item * &screenname($uname,$udom)
1.81      albertel 4331: 
                   4332: Gets a users screenname and returns it as a string
                   4333: 
                   4334: =cut
1.61      www      4335: 
                   4336: sub screenname {
                   4337:     my ($uname,$udom)=@_;
1.258     albertel 4338:     if ($uname eq $env{'user.name'} &&
                   4339: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4340:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4341:     return $names{'screenname'};
1.62      www      4342: }
                   4343: 
1.212     albertel 4344: 
1.802     bisitz   4345: # ------------------------------------------------------------- Confirm Wrapper
                   4346: =pod
                   4347: 
1.1142    raeburn  4348: =item * &confirmwrapper($message)
1.802     bisitz   4349: 
                   4350: Wrap messages about completion of operation in box
                   4351: 
                   4352: =cut
                   4353: 
                   4354: sub confirmwrapper {
                   4355:     my ($message)=@_;
                   4356:     if ($message) {
                   4357:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4358:                .$message."\n"
                   4359:                .'</div>'."\n";
                   4360:     } else {
                   4361:         return $message;
                   4362:     }
                   4363: }
                   4364: 
1.62      www      4365: # ------------------------------------------------------------- Message Wrapper
                   4366: 
                   4367: sub messagewrapper {
1.369     www      4368:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4369:     return 
1.441     albertel 4370:         '<a href="/adm/email?compose=individual&amp;'.
                   4371:         'recname='.$username.'&amp;recdom='.$domain.
                   4372: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4373:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4374: }
1.802     bisitz   4375: 
1.74      www      4376: # --------------------------------------------------------------- Notes Wrapper
                   4377: 
                   4378: sub noteswrapper {
                   4379:     my ($link,$un,$do)=@_;
                   4380:     return 
1.896     amueller 4381: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4382: }
1.802     bisitz   4383: 
1.62      www      4384: # ------------------------------------------------------------- Aboutme Wrapper
                   4385: 
                   4386: sub aboutmewrapper {
1.1070    raeburn  4387:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4388:     if (!defined($username)  && !defined($domain)) {
                   4389:         return;
                   4390:     }
1.1096    raeburn  4391:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4392: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4393: }
                   4394: 
                   4395: # ------------------------------------------------------------ Syllabus Wrapper
                   4396: 
                   4397: sub syllabuswrapper {
1.707     bisitz   4398:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4399:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4400: }
1.14      harris41 4401: 
1.1397    raeburn  4402: # -----------------------------------------------------------------------------
                   4403: 
1.1396    raeburn  4404: sub aboutme_on {
                   4405:     my ($uname,$udom)=@_;
                   4406:     unless ($uname) { $uname=$env{'user.name'}; }
                   4407:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4408:     return if ($udom eq 'public' && $uname eq 'public');
                   4409:     my $hashkey=$uname.':'.$udom;
                   4410:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4411:     if ($cached) {
                   4412:         return $aboutme;
                   4413:     }
                   4414:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4415:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4416:     return $aboutme;
                   4417: }
                   4418: 
                   4419: sub devalidate_aboutme_cache {
                   4420:     my ($uname,$udom)=@_;
                   4421:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4422:     if (!$uname) { $uname=$env{'user.name'};   }
                   4423:     return if ($udom eq 'public' && $uname eq 'public');
                   4424:     my $id=$uname.':'.$udom;
                   4425:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4426: }
                   4427: 
1.208     matthew  4428: sub track_student_link {
1.887     raeburn  4429:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4430:     my $link ="/adm/trackstudent?";
1.208     matthew  4431:     my $title = 'View recent activity';
                   4432:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4433:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4434:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4435:         $title .= ' of this student';
1.268     albertel 4436:     } 
1.208     matthew  4437:     if (defined($target) && $target !~ /^\s*$/) {
                   4438:         $target = qq{target="$target"};
                   4439:     } else {
                   4440:         $target = '';
                   4441:     }
1.268     albertel 4442:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4443:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4444:     $title = &mt($title);
                   4445:     $linktext = &mt($linktext);
1.448     albertel 4446:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4447: 	&help_open_topic('View_recent_activity');
1.208     matthew  4448: }
                   4449: 
1.781     raeburn  4450: sub slot_reservations_link {
                   4451:     my ($linktext,$sname,$sdom,$target) = @_;
                   4452:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4453:     my $title = 'View slot reservation history';
                   4454:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4455:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4456:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4457:         $title .= ' of this student';
                   4458:     }
                   4459:     if (defined($target) && $target !~ /^\s*$/) {
                   4460:         $target = qq{target="$target"};
                   4461:     } else {
                   4462:         $target = '';
                   4463:     }
                   4464:     $title = &mt($title);
                   4465:     $linktext = &mt($linktext);
                   4466:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4467: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4468: 
                   4469: }
                   4470: 
1.508     www      4471: # ===================================================== Display a student photo
                   4472: 
                   4473: 
1.509     albertel 4474: sub student_image_tag {
1.508     www      4475:     my ($domain,$user)=@_;
                   4476:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4477:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4478: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4479:     } else {
                   4480: 	return '';
                   4481:     }
                   4482: }
                   4483: 
1.112     bowersj2 4484: =pod
                   4485: 
                   4486: =back
                   4487: 
                   4488: =head1 Access .tab File Data
                   4489: 
                   4490: =over 4
                   4491: 
1.648     raeburn  4492: =item * &languageids() 
1.112     bowersj2 4493: 
                   4494: returns list of all language ids
                   4495: 
                   4496: =cut
                   4497: 
1.14      harris41 4498: sub languageids {
1.16      harris41 4499:     return sort(keys(%language));
1.14      harris41 4500: }
                   4501: 
1.112     bowersj2 4502: =pod
                   4503: 
1.648     raeburn  4504: =item * &languagedescription() 
1.112     bowersj2 4505: 
                   4506: returns description of a specified language id
                   4507: 
                   4508: =cut
                   4509: 
1.14      harris41 4510: sub languagedescription {
1.125     www      4511:     my $code=shift;
                   4512:     return  ($supported_language{$code}?'* ':'').
                   4513:             $language{$code}.
1.126     www      4514: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4515: }
                   4516: 
1.1048    foxr     4517: =pod
                   4518: 
                   4519: =item * &plainlanguagedescription
                   4520: 
                   4521: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4522: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4523: 
                   4524: =cut
                   4525: 
1.145     www      4526: sub plainlanguagedescription {
                   4527:     my $code=shift;
                   4528:     return $language{$code};
                   4529: }
                   4530: 
1.1048    foxr     4531: =pod
                   4532: 
                   4533: =item * &supportedlanguagecode
                   4534: 
                   4535: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4536: code.
                   4537: 
                   4538: =cut
                   4539: 
1.145     www      4540: sub supportedlanguagecode {
                   4541:     my $code=shift;
                   4542:     return $supported_language{$code};
1.97      www      4543: }
                   4544: 
1.112     bowersj2 4545: =pod
                   4546: 
1.1048    foxr     4547: =item * &latexlanguage()
                   4548: 
                   4549: Given a language key code returns the correspondnig language to use
                   4550: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4551: is no supported hyphenation for the language code.
                   4552: 
                   4553: =cut
                   4554: 
                   4555: sub latexlanguage {
                   4556:     my $code = shift;
                   4557:     return $latex_language{$code};
                   4558: }
                   4559: 
                   4560: =pod
                   4561: 
                   4562: =item * &latexhyphenation()
                   4563: 
                   4564: Same as above but what's supplied is the language as it might be stored
                   4565: in the metadata.
                   4566: 
                   4567: =cut
                   4568: 
                   4569: sub latexhyphenation {
                   4570:     my $key = shift;
                   4571:     return $latex_language_bykey{$key};
                   4572: }
                   4573: 
                   4574: =pod
                   4575: 
1.648     raeburn  4576: =item * &copyrightids() 
1.112     bowersj2 4577: 
                   4578: returns list of all copyrights
                   4579: 
                   4580: =cut
                   4581: 
                   4582: sub copyrightids {
                   4583:     return sort(keys(%cprtag));
                   4584: }
                   4585: 
                   4586: =pod
                   4587: 
1.648     raeburn  4588: =item * &copyrightdescription() 
1.112     bowersj2 4589: 
                   4590: returns description of a specified copyright id
                   4591: 
                   4592: =cut
                   4593: 
                   4594: sub copyrightdescription {
1.166     www      4595:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4596: }
1.197     matthew  4597: 
                   4598: =pod
                   4599: 
1.648     raeburn  4600: =item * &source_copyrightids() 
1.192     taceyjo1 4601: 
                   4602: returns list of all source copyrights
                   4603: 
                   4604: =cut
                   4605: 
                   4606: sub source_copyrightids {
                   4607:     return sort(keys(%scprtag));
                   4608: }
                   4609: 
                   4610: =pod
                   4611: 
1.648     raeburn  4612: =item * &source_copyrightdescription() 
1.192     taceyjo1 4613: 
                   4614: returns description of a specified source copyright id
                   4615: 
                   4616: =cut
                   4617: 
                   4618: sub source_copyrightdescription {
                   4619:     return &mt($scprtag{shift(@_)});
                   4620: }
1.112     bowersj2 4621: 
                   4622: =pod
                   4623: 
1.648     raeburn  4624: =item * &filecategories() 
1.112     bowersj2 4625: 
                   4626: returns list of all file categories
                   4627: 
                   4628: =cut
                   4629: 
                   4630: sub filecategories {
                   4631:     return sort(keys(%category_extensions));
                   4632: }
                   4633: 
                   4634: =pod
                   4635: 
1.648     raeburn  4636: =item * &filecategorytypes() 
1.112     bowersj2 4637: 
                   4638: returns list of file types belonging to a given file
                   4639: category
                   4640: 
                   4641: =cut
                   4642: 
                   4643: sub filecategorytypes {
1.356     albertel 4644:     my ($cat) = @_;
1.1248    raeburn  4645:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4646:         return @{$category_extensions{lc($cat)}};
                   4647:     } else {
                   4648:         return ();
                   4649:     }
1.112     bowersj2 4650: }
                   4651: 
                   4652: =pod
                   4653: 
1.648     raeburn  4654: =item * &fileembstyle() 
1.112     bowersj2 4655: 
                   4656: returns embedding style for a specified file type
                   4657: 
                   4658: =cut
                   4659: 
                   4660: sub fileembstyle {
                   4661:     return $fe{lc(shift(@_))};
1.169     www      4662: }
                   4663: 
1.351     www      4664: sub filemimetype {
                   4665:     return $fm{lc(shift(@_))};
                   4666: }
                   4667: 
1.169     www      4668: 
                   4669: sub filecategoryselect {
                   4670:     my ($name,$value)=@_;
1.189     matthew  4671:     return &select_form($value,$name,
1.970     raeburn  4672:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4673: }
                   4674: 
                   4675: =pod
                   4676: 
1.648     raeburn  4677: =item * &filedescription() 
1.112     bowersj2 4678: 
                   4679: returns description for a specified file type
                   4680: 
                   4681: =cut
                   4682: 
                   4683: sub filedescription {
1.188     matthew  4684:     my $file_description = $fd{lc(shift())};
                   4685:     $file_description =~ s:([\[\]]):~$1:g;
                   4686:     return &mt($file_description);
1.112     bowersj2 4687: }
                   4688: 
                   4689: =pod
                   4690: 
1.648     raeburn  4691: =item * &filedescriptionex() 
1.112     bowersj2 4692: 
                   4693: returns description for a specified file type with
                   4694: extra formatting
                   4695: 
                   4696: =cut
                   4697: 
                   4698: sub filedescriptionex {
                   4699:     my $ex=shift;
1.188     matthew  4700:     my $file_description = $fd{lc($ex)};
                   4701:     $file_description =~ s:([\[\]]):~$1:g;
                   4702:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4703: }
                   4704: 
                   4705: # End of .tab access
                   4706: =pod
                   4707: 
                   4708: =back
                   4709: 
                   4710: =cut
                   4711: 
                   4712: # ------------------------------------------------------------------ File Types
                   4713: sub fileextensions {
                   4714:     return sort(keys(%fe));
                   4715: }
                   4716: 
1.97      www      4717: # ----------------------------------------------------------- Display Languages
                   4718: # returns a hash with all desired display languages
                   4719: #
                   4720: 
                   4721: sub display_languages {
                   4722:     my %languages=();
1.695     raeburn  4723:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4724: 	$languages{$lang}=1;
1.97      www      4725:     }
                   4726:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4727:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4728: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4729: 	    $languages{$lang}=1;
1.97      www      4730:         }
                   4731:     }
                   4732:     return %languages;
1.14      harris41 4733: }
                   4734: 
1.582     albertel 4735: sub languages {
                   4736:     my ($possible_langs) = @_;
1.695     raeburn  4737:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4738:     if (!ref($possible_langs)) {
                   4739: 	if( wantarray ) {
                   4740: 	    return @preferred_langs;
                   4741: 	} else {
                   4742: 	    return $preferred_langs[0];
                   4743: 	}
                   4744:     }
                   4745:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4746:     my @preferred_possibilities;
                   4747:     foreach my $preferred_lang (@preferred_langs) {
                   4748: 	if (exists($possibilities{$preferred_lang})) {
                   4749: 	    push(@preferred_possibilities, $preferred_lang);
                   4750: 	}
                   4751:     }
                   4752:     if( wantarray ) {
                   4753: 	return @preferred_possibilities;
                   4754:     }
                   4755:     return $preferred_possibilities[0];
                   4756: }
                   4757: 
1.742     raeburn  4758: sub user_lang {
                   4759:     my ($touname,$toudom,$fromcid) = @_;
                   4760:     my @userlangs;
                   4761:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4762:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4763:                     $env{'course.'.$fromcid.'.languages'}));
                   4764:     } else {
                   4765:         my %langhash = &getlangs($touname,$toudom);
                   4766:         if ($langhash{'languages'} ne '') {
                   4767:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4768:         } else {
                   4769:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4770:             if ($domdefs{'lang_def'} ne '') {
                   4771:                 @userlangs = ($domdefs{'lang_def'});
                   4772:             }
                   4773:         }
                   4774:     }
                   4775:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4776:     my $user_lh = Apache::localize->get_handle(@languages);
                   4777:     return $user_lh;
                   4778: }
                   4779: 
                   4780: 
1.112     bowersj2 4781: ###############################################################
                   4782: ##               Student Answer Attempts                     ##
                   4783: ###############################################################
                   4784: 
                   4785: =pod
                   4786: 
                   4787: =head1 Alternate Problem Views
                   4788: 
                   4789: =over 4
                   4790: 
1.648     raeburn  4791: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4792:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4793: 
                   4794: Return string with previous attempt on problem. Arguments:
                   4795: 
                   4796: =over 4
                   4797: 
                   4798: =item * $symb: Problem, including path
                   4799: 
                   4800: =item * $username: username of the desired student
                   4801: 
                   4802: =item * $domain: domain of the desired student
1.14      harris41 4803: 
1.112     bowersj2 4804: =item * $course: Course ID
1.14      harris41 4805: 
1.112     bowersj2 4806: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4807:     something
1.14      harris41 4808: 
1.112     bowersj2 4809: =item * $regexp: if string matches this regexp, the string will be
                   4810:     sent to $gradesub
1.14      harris41 4811: 
1.112     bowersj2 4812: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4813: 
1.1199    raeburn  4814: =item * $usec: section of the desired student
                   4815: 
                   4816: =item * $identifier: counter for student (multiple students one problem) or 
                   4817:     problem (one student; whole sequence).
                   4818: 
1.112     bowersj2 4819: =back
1.14      harris41 4820: 
1.112     bowersj2 4821: The output string is a table containing all desired attempts, if any.
1.16      harris41 4822: 
1.112     bowersj2 4823: =cut
1.1       albertel 4824: 
                   4825: sub get_previous_attempt {
1.1199    raeburn  4826:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4827:   my $prevattempts='';
1.43      ng       4828:   no strict 'refs';
1.1       albertel 4829:   if ($symb) {
1.3       albertel 4830:     my (%returnhash)=
                   4831:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4832:     if ($returnhash{'version'}) {
                   4833:       my %lasthash=();
                   4834:       my $version;
                   4835:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4836:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4837:             if ($key =~ /\.rawrndseed$/) {
                   4838:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4839:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4840:             } else {
                   4841:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4842:             }
1.19      harris41 4843:         }
1.1       albertel 4844:       }
1.596     albertel 4845:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4846:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4847:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4848:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4849:       foreach my $key (sort(keys(%lasthash))) {
                   4850: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4851: 	if ($#parts > 0) {
1.31      albertel 4852: 	  my $data=$parts[-1];
1.989     raeburn  4853:           next if ($data eq 'foilorder');
1.31      albertel 4854: 	  pop(@parts);
1.1010    www      4855:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4856:           if ($data eq 'type') {
                   4857:               unless ($showsurv) {
                   4858:                   my $id = join(',',@parts);
                   4859:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4860:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4861:                       $lasthidden{$ign.'.'.$id} = 1;
                   4862:                   }
1.945     raeburn  4863:               }
1.1199    raeburn  4864:               if ($identifier ne '') {
                   4865:                   my $id = join(',',@parts);
                   4866:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4867:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4868:                       $hidestatus{$ign.'.'.$id} = 1;
                   4869:                   }
                   4870:               }
                   4871:           } elsif ($data eq 'regrader') {
                   4872:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4873:                   my $id = join(',',@parts);
                   4874:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4875:               }
1.1010    www      4876:           } 
1.31      albertel 4877: 	} else {
1.41      ng       4878: 	  if ($#parts == 0) {
                   4879: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4880: 	  } else {
                   4881: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4882: 	  }
1.31      albertel 4883: 	}
1.16      harris41 4884:       }
1.596     albertel 4885:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4886:       if ($getattempt eq '') {
1.1199    raeburn  4887:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4888:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4889:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4890:                 foreach my $id (keys(%regraded)) {
                   4891:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4892:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4893:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4894:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4895:                     }
                   4896:                 }
                   4897:             }
1.1200    raeburn  4898:         }
                   4899: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4900:             my (@hidden,@unsolved);
1.945     raeburn  4901:             if (%typeparts) {
                   4902:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4903:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4904:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4905:                         push(@hidden,$id);
1.1199    raeburn  4906:                     } elsif ($identifier ne '') {
                   4907:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4908:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4909:                                 ($hidestatus{$id})) {
1.1200    raeburn  4910:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4911:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4912:                                 push(@{$solved{$id}},$version);
                   4913:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4914:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4915:                                 my $skip;
                   4916:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4917:                                     foreach my $reset (@{$resets{$id}}) {
                   4918:                                         if ($reset > $solved{$id}[-1]) {
                   4919:                                             $skip=1;
                   4920:                                             last;
                   4921:                                         }
                   4922:                                     }
                   4923:                                 }
                   4924:                                 unless ($skip) {
                   4925:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4926:                                     push(@unsolved,$partslist);
                   4927:                                 }
                   4928:                             }
                   4929:                         }
1.945     raeburn  4930:                     }
                   4931:                 }
                   4932:             }
                   4933:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4934:                            '<td>'.&mt('Transaction [_1]',$version);
                   4935:             if (@unsolved) {
                   4936:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4937:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4938:                                  &mt('Hide').'</label></span>';
                   4939:             }
                   4940:             $prevattempts .= '</td>';
1.945     raeburn  4941:             if (@hidden) {
                   4942:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4943:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4944:                     my $hide;
                   4945:                     foreach my $id (@hidden) {
                   4946:                         if ($key =~ /^\Q$id\E/) {
                   4947:                             $hide = 1;
                   4948:                             last;
                   4949:                         }
                   4950:                     }
                   4951:                     if ($hide) {
                   4952:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4953:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4954:                             my $value = &format_previous_attempt_value($key,
                   4955:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4956:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4957:                         } else {
                   4958:                             $prevattempts.='<td>&nbsp;</td>';
                   4959:                         }
                   4960:                     } else {
                   4961:                         if ($key =~ /\./) {
1.1212    raeburn  4962:                             my $value = $returnhash{$version.':'.$key};
                   4963:                             if ($key =~ /\.rndseed$/) {
                   4964:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4965:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4966:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4967:                                 }
                   4968:                             }
                   4969:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4970:                                            '&nbsp;</td>';
1.945     raeburn  4971:                         } else {
                   4972:                             $prevattempts.='<td>&nbsp;</td>';
                   4973:                         }
                   4974:                     }
                   4975:                 }
                   4976:             } else {
                   4977: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4978:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4979:                     my $value = $returnhash{$version.':'.$key};
                   4980:                     if ($key =~ /\.rndseed$/) {
                   4981:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4982:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4983:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4984:                         }
                   4985:                     }
                   4986:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4987:                                    '&nbsp;</td>';
1.945     raeburn  4988: 	        }
                   4989:             }
                   4990: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4991: 	 }
1.1       albertel 4992:       }
1.945     raeburn  4993:       my @currhidden = keys(%lasthidden);
1.596     albertel 4994:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4995:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4996:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4997:           if (%typeparts) {
                   4998:               my $hidden;
                   4999:               foreach my $id (@currhidden) {
                   5000:                   if ($key =~ /^\Q$id\E/) {
                   5001:                       $hidden = 1;
                   5002:                       last;
                   5003:                   }
                   5004:               }
                   5005:               if ($hidden) {
                   5006:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5007:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5008:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5009:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5010:                           $value = &$gradesub($value);
                   5011:                       }
1.1173    kruse    5012:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5013:                   } else {
                   5014:                       $prevattempts.='<td>&nbsp;</td>';
                   5015:                   }
                   5016:               } else {
                   5017:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5018:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5019:                       $value = &$gradesub($value);
                   5020:                   }
1.1173    kruse    5021:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5022:               }
                   5023:           } else {
                   5024: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5025: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5026:                   $value = &$gradesub($value);
                   5027:               }
1.1173    kruse    5028: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5029:           }
1.16      harris41 5030:       }
1.596     albertel 5031:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5032:     } else {
1.1305    raeburn  5033:       my $msg;
                   5034:       if ($symb =~ /ext\.tool$/) {
                   5035:           $msg = &mt('No grade passed back.');
                   5036:       } else {
                   5037:           $msg = &mt('Nothing submitted - no attempts.');
                   5038:       }
1.596     albertel 5039:       $prevattempts=
                   5040: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5041: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5042: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5043:     }
                   5044:   } else {
1.596     albertel 5045:     $prevattempts=
                   5046: 	  &start_data_table().&start_data_table_row().
                   5047: 	  '<td>'.&mt('No data.').'</td>'.
                   5048: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5049:   }
1.10      albertel 5050: }
                   5051: 
1.581     albertel 5052: sub format_previous_attempt_value {
                   5053:     my ($key,$value) = @_;
1.1011    www      5054:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5055:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5056:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5057:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5058:     } elsif ($key =~ /answerstring$/) {
                   5059:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5060:         my @answer = %answers;
                   5061:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5062:         my @anskeys = sort(keys(%answers));
                   5063:         if (@anskeys == 1) {
                   5064:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5065:             if ($answer =~ m{\0}) {
                   5066:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5067:             }
                   5068:             my $tag_internal_answer_name = 'INTERNAL';
                   5069:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5070:                 $value = $answer; 
                   5071:             } else {
                   5072:                 $value = $anskeys[0].'='.$answer;
                   5073:             }
                   5074:         } else {
                   5075:             foreach my $ans (@anskeys) {
                   5076:                 my $answer = $answers{$ans};
1.1001    raeburn  5077:                 if ($answer =~ m{\0}) {
                   5078:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5079:                 }
                   5080:                 $value .=  $ans.'='.$answer.'<br />';;
                   5081:             } 
                   5082:         }
1.581     albertel 5083:     } else {
1.1173    kruse    5084:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5085:     }
                   5086:     return $value;
                   5087: }
                   5088: 
                   5089: 
1.107     albertel 5090: sub relative_to_absolute {
                   5091:     my ($url,$output)=@_;
                   5092:     my $parser=HTML::TokeParser->new(\$output);
                   5093:     my $token;
                   5094:     my $thisdir=$url;
                   5095:     my @rlinks=();
                   5096:     while ($token=$parser->get_token) {
                   5097: 	if ($token->[0] eq 'S') {
                   5098: 	    if ($token->[1] eq 'a') {
                   5099: 		if ($token->[2]->{'href'}) {
                   5100: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5101: 		}
                   5102: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5103: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5104: 	    } elsif ($token->[1] eq 'base') {
                   5105: 		$thisdir=$token->[2]->{'href'};
                   5106: 	    }
                   5107: 	}
                   5108:     }
                   5109:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5110:     foreach my $link (@rlinks) {
1.726     raeburn  5111: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5112: 		($link=~/^\//) ||
                   5113: 		($link=~/^javascript:/i) ||
                   5114: 		($link=~/^mailto:/i) ||
                   5115: 		($link=~/^\#/)) {
                   5116: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5117: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5118: 	}
                   5119:     }
                   5120: # -------------------------------------------------- Deal with Applet codebases
                   5121:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5122:     return $output;
                   5123: }
                   5124: 
1.112     bowersj2 5125: =pod
                   5126: 
1.648     raeburn  5127: =item * &get_student_view()
1.112     bowersj2 5128: 
                   5129: show a snapshot of what student was looking at
                   5130: 
                   5131: =cut
                   5132: 
1.10      albertel 5133: sub get_student_view {
1.186     albertel 5134:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5135:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5136:   my (%form);
1.10      albertel 5137:   my @elements=('symb','courseid','domain','username');
                   5138:   foreach my $element (@elements) {
1.186     albertel 5139:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5140:   }
1.186     albertel 5141:   if (defined($moreenv)) {
                   5142:       %form=(%form,%{$moreenv});
                   5143:   }
1.236     albertel 5144:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5145:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5146:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5147:       $feedurl =~ s{^/adm/wrapper}{};
                   5148:   }
1.650     www      5149:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5150:   $userview=~s/\<body[^\>]*\>//gi;
                   5151:   $userview=~s/\<\/body\>//gi;
                   5152:   $userview=~s/\<html\>//gi;
                   5153:   $userview=~s/\<\/html\>//gi;
                   5154:   $userview=~s/\<head\>//gi;
                   5155:   $userview=~s/\<\/head\>//gi;
                   5156:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5157:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5158:   if (wantarray) {
                   5159:      return ($userview,$response);
                   5160:   } else {
                   5161:      return $userview;
                   5162:   }
                   5163: }
                   5164: 
                   5165: sub get_student_view_with_retries {
                   5166:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5167: 
                   5168:     my $ok = 0;                 # True if we got a good response.
                   5169:     my $content;
                   5170:     my $response;
                   5171: 
                   5172:     # Try to get the student_view done. within the retries count:
                   5173:     
                   5174:     do {
                   5175:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5176:          $ok      = $response->is_success;
                   5177:          if (!$ok) {
                   5178:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5179:          }
                   5180:          $retries--;
                   5181:     } while (!$ok && ($retries > 0));
                   5182:     
                   5183:     if (!$ok) {
                   5184:        $content = '';          # On error return an empty content.
                   5185:     }
1.651     www      5186:     if (wantarray) {
                   5187:        return ($content, $response);
                   5188:     } else {
                   5189:        return $content;
                   5190:     }
1.11      albertel 5191: }
                   5192: 
1.1349    raeburn  5193: sub css_links {
                   5194:     my ($currsymb,$level) = @_;
                   5195:     my ($links,@symbs,%cssrefs,%httpref);
                   5196:     if ($level eq 'map') {
                   5197:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5198:         if (ref($navmap)) {
                   5199:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5200:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5201:             foreach my $res (@resources) {
                   5202:                 if (ref($res) && $res->symb()) {
                   5203:                     push(@symbs,$res->symb());
                   5204:                 }
                   5205:             }
                   5206:         }
                   5207:     } else {
                   5208:         @symbs = ($currsymb);
                   5209:     }
                   5210:     foreach my $symb (@symbs) {
                   5211:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5212:         if ($css_href =~ /\S/) {
                   5213:             unless ($css_href =~ m{https?://}) {
                   5214:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5215:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5216:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5217:                 unless ($css_href =~ m{^/}) {
                   5218:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5219:                 }
                   5220:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5221:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5222:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5223:                         my $thisurl = $proburl;
                   5224:                         if ($env{'httpref.'.$proburl}) {
                   5225:                             $thisurl = $env{'httpref.'.$proburl};
                   5226:                         }
                   5227:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5228:                     }
                   5229:                 }
                   5230:             }
                   5231:             $cssrefs{$css_href} = 1;
                   5232:         }
                   5233:     }
                   5234:     if (keys(%httpref)) {
                   5235:         &Apache::lonnet::appenv(\%httpref);
                   5236:     }
                   5237:     if (keys(%cssrefs)) {
                   5238:         foreach my $css_href (keys(%cssrefs)) {
                   5239:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5240:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5241:         }
                   5242:     }
                   5243:     return $links;
                   5244: }
                   5245: 
1.112     bowersj2 5246: =pod
                   5247: 
1.648     raeburn  5248: =item * &get_student_answers() 
1.112     bowersj2 5249: 
                   5250: show a snapshot of how student was answering problem
                   5251: 
                   5252: =cut
                   5253: 
1.11      albertel 5254: sub get_student_answers {
1.100     sakharuk 5255:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5256:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5257:   my (%moreenv);
1.11      albertel 5258:   my @elements=('symb','courseid','domain','username');
                   5259:   foreach my $element (@elements) {
1.186     albertel 5260:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5261:   }
1.186     albertel 5262:   $moreenv{'grade_target'}='answer';
                   5263:   %moreenv=(%form,%moreenv);
1.497     raeburn  5264:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5265:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5266:   return $userview;
1.1       albertel 5267: }
1.116     albertel 5268: 
                   5269: =pod
                   5270: 
                   5271: =item * &submlink()
                   5272: 
1.242     albertel 5273: Inputs: $text $uname $udom $symb $target
1.116     albertel 5274: 
                   5275: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5276: 
                   5277: =cut
                   5278: 
                   5279: ###############################################
                   5280: sub submlink {
1.242     albertel 5281:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5282:     if (!($uname && $udom)) {
                   5283: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5284: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5285: 	if (!$symb) { $symb=$cursymb; }
                   5286:     }
1.254     matthew  5287:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5288:     $symb=&escape($symb);
1.960     bisitz   5289:     if ($target) { $target=" target=\"$target\""; }
                   5290:     return
                   5291:         '<a href="/adm/grades?command=submission'.
                   5292:         '&amp;symb='.$symb.
                   5293:         '&amp;student='.$uname.
                   5294:         '&amp;userdom='.$udom.'"'.
                   5295:         $target.'>'.$text.'</a>';
1.242     albertel 5296: }
                   5297: ##############################################
                   5298: 
                   5299: =pod
                   5300: 
                   5301: =item * &pgrdlink()
                   5302: 
                   5303: Inputs: $text $uname $udom $symb $target
                   5304: 
                   5305: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5306: 
                   5307: =cut
                   5308: 
                   5309: ###############################################
                   5310: sub pgrdlink {
                   5311:     my $link=&submlink(@_);
                   5312:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5313:     return $link;
                   5314: }
                   5315: ##############################################
                   5316: 
                   5317: =pod
                   5318: 
                   5319: =item * &pprmlink()
                   5320: 
                   5321: Inputs: $text $uname $udom $symb $target
                   5322: 
                   5323: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5324: student and a specific resource
1.242     albertel 5325: 
                   5326: =cut
                   5327: 
                   5328: ###############################################
                   5329: sub pprmlink {
                   5330:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5331:     if (!($uname && $udom)) {
                   5332: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5333: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5334: 	if (!$symb) { $symb=$cursymb; }
                   5335:     }
1.254     matthew  5336:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5337:     $symb=&escape($symb);
1.242     albertel 5338:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5339:     return '<a href="/adm/parmset?command=set&amp;'.
                   5340: 	'symb='.$symb.'&amp;uname='.$uname.
                   5341: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5342: }
                   5343: ##############################################
1.37      matthew  5344: 
1.112     bowersj2 5345: =pod
                   5346: 
                   5347: =back
                   5348: 
                   5349: =cut
                   5350: 
1.37      matthew  5351: ###############################################
1.51      www      5352: 
                   5353: 
                   5354: sub timehash {
1.687     raeburn  5355:     my ($thistime) = @_;
                   5356:     my $timezone = &Apache::lonlocal::gettimezone();
                   5357:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5358:                      ->set_time_zone($timezone);
                   5359:     my $wday = $dt->day_of_week();
                   5360:     if ($wday == 7) { $wday = 0; }
                   5361:     return ( 'second' => $dt->second(),
                   5362:              'minute' => $dt->minute(),
                   5363:              'hour'   => $dt->hour(),
                   5364:              'day'     => $dt->day_of_month(),
                   5365:              'month'   => $dt->month(),
                   5366:              'year'    => $dt->year(),
                   5367:              'weekday' => $wday,
                   5368:              'dayyear' => $dt->day_of_year(),
                   5369:              'dlsav'   => $dt->is_dst() );
1.51      www      5370: }
                   5371: 
1.370     www      5372: sub utc_string {
                   5373:     my ($date)=@_;
1.371     www      5374:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5375: }
                   5376: 
1.51      www      5377: sub maketime {
                   5378:     my %th=@_;
1.687     raeburn  5379:     my ($epoch_time,$timezone,$dt);
                   5380:     $timezone = &Apache::lonlocal::gettimezone();
                   5381:     eval {
                   5382:         $dt = DateTime->new( year   => $th{'year'},
                   5383:                              month  => $th{'month'},
                   5384:                              day    => $th{'day'},
                   5385:                              hour   => $th{'hour'},
                   5386:                              minute => $th{'minute'},
                   5387:                              second => $th{'second'},
                   5388:                              time_zone => $timezone,
                   5389:                          );
                   5390:     };
                   5391:     if (!$@) {
                   5392:         $epoch_time = $dt->epoch;
                   5393:         if ($epoch_time) {
                   5394:             return $epoch_time;
                   5395:         }
                   5396:     }
1.51      www      5397:     return POSIX::mktime(
                   5398:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5399:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5400: }
                   5401: 
                   5402: #########################################
1.51      www      5403: 
                   5404: sub findallcourses {
1.482     raeburn  5405:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5406:     my %roles;
                   5407:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5408:     my %courses;
1.51      www      5409:     my $now=time;
1.482     raeburn  5410:     if (!defined($uname)) {
                   5411:         $uname = $env{'user.name'};
                   5412:     }
                   5413:     if (!defined($udom)) {
                   5414:         $udom = $env{'user.domain'};
                   5415:     }
                   5416:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5417:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5418:         if (!%roles) {
                   5419:             %roles = (
                   5420:                        cc => 1,
1.907     raeburn  5421:                        co => 1,
1.482     raeburn  5422:                        in => 1,
                   5423:                        ep => 1,
                   5424:                        ta => 1,
                   5425:                        cr => 1,
                   5426:                        st => 1,
                   5427:              );
                   5428:         }
                   5429:         foreach my $entry (keys(%roleshash)) {
                   5430:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5431:             if ($trole =~ /^cr/) { 
                   5432:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5433:             } else {
                   5434:                 next if (!exists($roles{$trole}));
                   5435:             }
                   5436:             if ($tend) {
                   5437:                 next if ($tend < $now);
                   5438:             }
                   5439:             if ($tstart) {
                   5440:                 next if ($tstart > $now);
                   5441:             }
1.1058    raeburn  5442:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5443:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5444:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5445:             if ($secpart eq '') {
                   5446:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5447:                 $sec = 'none';
1.1058    raeburn  5448:                 $value .= $cnum.'/';
1.482     raeburn  5449:             } else {
                   5450:                 $cnum = $cnumpart;
                   5451:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5452:                 $value .= $cnum.'/'.$sec;
                   5453:             }
                   5454:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5455:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5456:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5457:                 }
                   5458:             } else {
                   5459:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5460:             }
1.482     raeburn  5461:         }
                   5462:     } else {
                   5463:         foreach my $key (keys(%env)) {
1.483     albertel 5464: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5465:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5466: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5467: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5468: 	        next if (%roles && !exists($roles{$role}));
                   5469: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5470:                 my $active=1;
                   5471:                 if ($starttime) {
                   5472: 		    if ($now<$starttime) { $active=0; }
                   5473:                 }
                   5474:                 if ($endtime) {
                   5475:                     if ($now>$endtime) { $active=0; }
                   5476:                 }
                   5477:                 if ($active) {
1.1058    raeburn  5478:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5479:                     if ($sec eq '') {
                   5480:                         $sec = 'none';
1.1058    raeburn  5481:                     } else {
                   5482:                         $value .= $sec;
                   5483:                     }
                   5484:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5485:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5486:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5487:                         }
                   5488:                     } else {
                   5489:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5490:                     }
1.474     raeburn  5491:                 }
                   5492:             }
1.51      www      5493:         }
                   5494:     }
1.474     raeburn  5495:     return %courses;
1.51      www      5496: }
1.37      matthew  5497: 
1.54      www      5498: ###############################################
1.474     raeburn  5499: 
                   5500: sub blockcheck {
1.1372    raeburn  5501:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5502:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5503:         my ($has_evb,$check_ipaccess);
                   5504:         my $dom = $env{'user.domain'};
                   5505:         if ($env{'request.course.id'}) {
                   5506:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5507:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5508:             my $checkrole = "cm./$cdom/$cnum";
                   5509:             my $sec = $env{'request.course.sec'};
                   5510:             if ($sec ne '') {
                   5511:                 $checkrole .= "/$sec";
                   5512:             }
                   5513:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5514:                 ($env{'request.role'} !~ /^st/)) {
                   5515:                 $has_evb = 1;
                   5516:             }
                   5517:             unless ($has_evb) {
                   5518:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5519:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5520:                     if ($udom eq $cdom) {
                   5521:                         $check_ipaccess = 1;
                   5522:                     }
                   5523:                 }
                   5524:             }
1.1375    raeburn  5525:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5526:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5527:             my $checkrole;
                   5528:             if ($env{'request.role.domain'} eq '') {
                   5529:                 $checkrole = "cm./$env{'user.domain'}/";
                   5530:             } else {
                   5531:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5532:             }
                   5533:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5534:                 $has_evb = 1;
                   5535:             }
1.1372    raeburn  5536:         }
                   5537:         unless ($has_evb || $check_ipaccess) {
                   5538:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5539:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5540:                 $dom = $udom;
                   5541:             }
                   5542:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5543:                 $check_ipaccess = 1;
                   5544:             } else {
                   5545:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5546:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5547:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5548:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5549:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5550:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5551:                         $check_ipaccess = 1;
                   5552:                     }
                   5553:                 }
                   5554:             }
                   5555:         }
                   5556:         if ($check_ipaccess) {
                   5557:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5558:             unless (defined($cached)) {
                   5559:                 my %domconfig =
                   5560:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5561:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5562:             }
                   5563:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5564:                 foreach my $id (keys(%{$ipaccessref})) {
                   5565:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5566:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5567:                         if ($range) {
                   5568:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5569:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5570:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5571:                                         return ('','','',$id,$dom);
                   5572:                                         last;
                   5573:                                     }
                   5574:                                 }
                   5575:                             }
                   5576:                         }
                   5577:                     }
                   5578:                 }
                   5579:             }
                   5580:         }
1.1373    raeburn  5581:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5582:             return ();
                   5583:         }
1.1372    raeburn  5584:     }
1.1189    raeburn  5585:     if (defined($udom) && defined($uname)) {
                   5586:         # If uname and udom are for a course, check for blocks in the course.
                   5587:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5588:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5589:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5590:             return ($startblock,$endblock,$triggerblock);
                   5591:         }
                   5592:     } else {
1.490     raeburn  5593:         $udom = $env{'user.domain'};
                   5594:         $uname = $env{'user.name'};
                   5595:     }
                   5596: 
1.502     raeburn  5597:     my $startblock = 0;
                   5598:     my $endblock = 0;
1.1062    raeburn  5599:     my $triggerblock = '';
1.1373    raeburn  5600:     my %live_courses;
                   5601:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5602:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5603:     }
1.474     raeburn  5604: 
1.490     raeburn  5605:     # If uname is for a user, and activity is course-specific, i.e.,
                   5606:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5607: 
1.490     raeburn  5608:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5609:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5610:          $activity eq 'search' || $activity eq 'reinit' ||
                   5611:          $activity eq 'alert') &&
1.1189    raeburn  5612:         ($env{'request.course.id'})) {
1.490     raeburn  5613:         foreach my $key (keys(%live_courses)) {
                   5614:             if ($key ne $env{'request.course.id'}) {
                   5615:                 delete($live_courses{$key});
                   5616:             }
                   5617:         }
                   5618:     }
                   5619: 
                   5620:     my $otheruser = 0;
                   5621:     my %own_courses;
                   5622:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5623:         # Resource belongs to user other than current user.
                   5624:         $otheruser = 1;
                   5625:         # Gather courses for current user
                   5626:         %own_courses = 
                   5627:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5628:     }
                   5629: 
                   5630:     # Gather active course roles - course coordinator, instructor, 
                   5631:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5632: 
                   5633:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5634:         my ($cdom,$cnum);
                   5635:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5636:             $cdom = $env{'course.'.$course.'.domain'};
                   5637:             $cnum = $env{'course.'.$course.'.num'};
                   5638:         } else {
1.490     raeburn  5639:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5640:         }
                   5641:         my $no_ownblock = 0;
                   5642:         my $no_userblock = 0;
1.533     raeburn  5643:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5644:             # Check if current user has 'evb' priv for this
                   5645:             if (defined($own_courses{$course})) {
                   5646:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5647:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5648:                     if ($sec ne 'none') {
                   5649:                         $checkrole .= '/'.$sec;
                   5650:                     }
                   5651:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5652:                         $no_ownblock = 1;
                   5653:                         last;
                   5654:                     }
                   5655:                 }
                   5656:             }
                   5657:             # if they have 'evb' priv and are currently not playing student
                   5658:             next if (($no_ownblock) &&
                   5659:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5660:         }
1.474     raeburn  5661:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5662:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5663:             if ($sec ne 'none') {
1.482     raeburn  5664:                 $checkrole .= '/'.$sec;
1.474     raeburn  5665:             }
1.490     raeburn  5666:             if ($otheruser) {
                   5667:                 # Resource belongs to user other than current user.
                   5668:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5669:                 my (%allroles,%userroles);
                   5670:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5671:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5672:                         my ($trole,$tdom,$tnum,$tsec);
                   5673:                         if ($entry =~ /^cr/) {
                   5674:                             ($trole,$tdom,$tnum,$tsec) = 
                   5675:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5676:                         } else {
                   5677:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5678:                         }
                   5679:                         my ($spec,$area,$trest);
                   5680:                         $area = '/'.$tdom.'/'.$tnum;
                   5681:                         $trest = $tnum;
                   5682:                         if ($tsec ne '') {
                   5683:                             $area .= '/'.$tsec;
                   5684:                             $trest .= '/'.$tsec;
                   5685:                         }
                   5686:                         $spec = $trole.'.'.$area;
                   5687:                         if ($trole =~ /^cr/) {
                   5688:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5689:                                                               $tdom,$spec,$trest,$area);
                   5690:                         } else {
                   5691:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5692:                                                                 $tdom,$spec,$trest,$area);
                   5693:                         }
                   5694:                     }
1.1276    raeburn  5695:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5696:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5697:                         if ($1) {
                   5698:                             $no_userblock = 1;
                   5699:                             last;
                   5700:                         }
1.486     raeburn  5701:                     }
                   5702:                 }
1.490     raeburn  5703:             } else {
                   5704:                 # Resource belongs to current user
                   5705:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5706:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5707:                     $no_ownblock = 1;
                   5708:                     last;
                   5709:                 }
1.474     raeburn  5710:             }
                   5711:         }
                   5712:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5713:         next if (($no_ownblock) &&
1.491     albertel 5714:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5715:         next if ($no_userblock);
1.474     raeburn  5716: 
1.1303    raeburn  5717:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5718:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5719: 
1.1062    raeburn  5720:         my ($start,$end,$trigger) = 
1.1347    raeburn  5721:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5722:         if (($start != 0) && 
                   5723:             (($startblock == 0) || ($startblock > $start))) {
                   5724:             $startblock = $start;
1.1062    raeburn  5725:             if ($trigger ne '') {
                   5726:                 $triggerblock = $trigger;
                   5727:             }
1.502     raeburn  5728:         }
                   5729:         if (($end != 0)  &&
                   5730:             (($endblock == 0) || ($endblock < $end))) {
                   5731:             $endblock = $end;
1.1062    raeburn  5732:             if ($trigger ne '') {
                   5733:                 $triggerblock = $trigger;
                   5734:             }
1.502     raeburn  5735:         }
1.490     raeburn  5736:     }
1.1062    raeburn  5737:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5738: }
                   5739: 
                   5740: sub get_blocks {
1.1347    raeburn  5741:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5742:     my $startblock = 0;
                   5743:     my $endblock = 0;
1.1062    raeburn  5744:     my $triggerblock = '';
1.490     raeburn  5745:     my $course = $cdom.'_'.$cnum;
                   5746:     $setters->{$course} = {};
                   5747:     $setters->{$course}{'staff'} = [];
                   5748:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5749:     $setters->{$course}{'triggers'} = [];
                   5750:     my (@blockers,%triggered);
                   5751:     my $now = time;
                   5752:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5753:     if ($activity eq 'docs') {
1.1348    raeburn  5754:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5755:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5756:             $blocked = 1;
                   5757:             $nosymbcache = 1;
1.1348    raeburn  5758:             $noenccheck = 1;
1.1347    raeburn  5759:         }
1.1348    raeburn  5760:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5761:         foreach my $block (@blockers) {
                   5762:             if ($block =~ /^firstaccess____(.+)$/) {
                   5763:                 my $item = $1;
                   5764:                 my $type = 'map';
                   5765:                 my $timersymb = $item;
                   5766:                 if ($item eq 'course') {
                   5767:                     $type = 'course';
                   5768:                 } elsif ($item =~ /___\d+___/) {
                   5769:                     $type = 'resource';
                   5770:                 } else {
                   5771:                     $timersymb = &Apache::lonnet::symbread($item);
                   5772:                 }
                   5773:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5774:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5775:                 $triggered{$block} = {
                   5776:                                        start => $start,
                   5777:                                        end   => $end,
                   5778:                                        type  => $type,
                   5779:                                      };
                   5780:             }
                   5781:         }
                   5782:     } else {
                   5783:         foreach my $block (keys(%commblocks)) {
                   5784:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5785:                 my ($start,$end) = ($1,$2);
                   5786:                 if ($start <= time && $end >= time) {
                   5787:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5788:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5789:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5790:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5791:                                     push(@blockers,$block);
                   5792:                                 }
                   5793:                             }
                   5794:                         }
                   5795:                     }
                   5796:                 }
                   5797:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5798:                 my $item = $1;
                   5799:                 my $timersymb = $item; 
                   5800:                 my $type = 'map';
                   5801:                 if ($item eq 'course') {
                   5802:                     $type = 'course';
                   5803:                 } elsif ($item =~ /___\d+___/) {
                   5804:                     $type = 'resource';
                   5805:                 } else {
                   5806:                     $timersymb = &Apache::lonnet::symbread($item);
                   5807:                 }
                   5808:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5809:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5810:                 if ($start && $end) {
                   5811:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5812:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5813:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5814:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5815:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5816:                                         push(@blockers,$block);
                   5817:                                         $triggered{$block} = {
                   5818:                                                                start => $start,
                   5819:                                                                end   => $end,
                   5820:                                                                type  => $type,
                   5821:                                                              };
                   5822:                                     }
                   5823:                                 }
                   5824:                             }
1.1062    raeburn  5825:                         }
                   5826:                     }
1.490     raeburn  5827:                 }
1.1062    raeburn  5828:             }
                   5829:         }
                   5830:     }
                   5831:     foreach my $blocker (@blockers) {
                   5832:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5833:             &parse_block_record($commblocks{$blocker});
                   5834:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5835:         my ($start,$end,$triggertype);
                   5836:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5837:             ($start,$end) = ($1,$2);
                   5838:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5839:             $start = $triggered{$blocker}{'start'};
                   5840:             $end = $triggered{$blocker}{'end'};
                   5841:             $triggertype = $triggered{$blocker}{'type'};
                   5842:         }
                   5843:         if ($start) {
                   5844:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5845:             if ($triggertype) {
                   5846:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5847:             } else {
                   5848:                 push(@{$$setters{$course}{'triggers'}},0);
                   5849:             }
                   5850:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5851:                 $startblock = $start;
                   5852:                 if ($triggertype) {
                   5853:                     $triggerblock = $blocker;
1.474     raeburn  5854:                 }
                   5855:             }
1.1062    raeburn  5856:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5857:                $endblock = $end;
                   5858:                if ($triggertype) {
                   5859:                    $triggerblock = $blocker;
                   5860:                }
                   5861:             }
1.474     raeburn  5862:         }
                   5863:     }
1.1062    raeburn  5864:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5865: }
                   5866: 
                   5867: sub parse_block_record {
                   5868:     my ($record) = @_;
                   5869:     my ($setuname,$setudom,$title,$blocks);
                   5870:     if (ref($record) eq 'HASH') {
                   5871:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5872:         $title = &unescape($record->{'event'});
                   5873:         $blocks = $record->{'blocks'};
                   5874:     } else {
                   5875:         my @data = split(/:/,$record,3);
                   5876:         if (scalar(@data) eq 2) {
                   5877:             $title = $data[1];
                   5878:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5879:         } else {
                   5880:             ($setuname,$setudom,$title) = @data;
                   5881:         }
                   5882:         $blocks = { 'com' => 'on' };
                   5883:     }
                   5884:     return ($setuname,$setudom,$title,$blocks);
                   5885: }
                   5886: 
1.854     kalberla 5887: sub blocking_status {
1.1372    raeburn  5888:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5889:     my %setters;
1.890     droeschl 5890: 
1.1061    raeburn  5891: # check for active blocking
1.1372    raeburn  5892:     if ($clientip eq '') {
                   5893:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5894:     }
                   5895:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5896:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5897:     my $blocked = 0;
1.1372    raeburn  5898:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5899:         $blocked = 1;
                   5900:     }
1.890     droeschl 5901: 
1.1061    raeburn  5902: # caller just wants to know whether a block is active
                   5903:     if (!wantarray) { return $blocked; }
                   5904: 
                   5905: # build a link to a popup window containing the details
                   5906:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5907: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5908:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5909:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5910:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5911:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5912:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5913:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5914:         if ($symb) {
                   5915:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5916:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5917:         }
1.1062    raeburn  5918:     }
1.1061    raeburn  5919: 
                   5920:     my $output .= <<'END_MYBLOCK';
                   5921: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5922:     var options = "width=" + w + ",height=" + h + ",";
                   5923:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5924:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5925:     var newWin = window.open(url, wdwName, options);
                   5926:     newWin.focus();
                   5927: }
1.890     droeschl 5928: END_MYBLOCK
1.854     kalberla 5929: 
1.1061    raeburn  5930:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5931:   
1.1061    raeburn  5932:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5933:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5934:     my $class = 'LC_comblock';
1.1062    raeburn  5935:     if ($activity eq 'docs') {
                   5936:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5937:         $class = '';
1.1063    raeburn  5938:     } elsif ($activity eq 'printout') {
                   5939:         $text = &mt('Printing Blocked');
1.1232    raeburn  5940:     } elsif ($activity eq 'passwd') {
                   5941:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5942:     } elsif ($activity eq 'grades') {
                   5943:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5944:     } elsif ($activity eq 'search') {
                   5945:         $text = &mt('Search Blocked');
1.1282    raeburn  5946:     } elsif ($activity eq 'alert') {
                   5947:         $text = &mt('Checking Critical Messages Blocked');
                   5948:     } elsif ($activity eq 'reinit') {
                   5949:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5950:     } elsif ($activity eq 'about') {
                   5951:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5952:     } elsif ($activity eq 'wishlist') {
                   5953:         $text = &mt('Access to Stored Links Blocked');
                   5954:     } elsif ($activity eq 'annotate') {
                   5955:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5956:     }
1.1061    raeburn  5957:     $output .= <<"END_BLOCK";
1.1217    raeburn  5958: <div class='$class'>
1.869     kalberla 5959:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5960:   title='$text'>
                   5961:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5962:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5963:   title='$text'>$text</a>
1.867     kalberla 5964: </div>
                   5965: 
                   5966: END_BLOCK
1.474     raeburn  5967: 
1.1061    raeburn  5968:     return ($blocked, $output);
1.854     kalberla 5969: }
1.490     raeburn  5970: 
1.60      matthew  5971: ###############################################
                   5972: 
1.682     raeburn  5973: sub check_ip_acc {
1.1201    raeburn  5974:     my ($acc,$clientip)=@_;
1.682     raeburn  5975:     &Apache::lonxml::debug("acc is $acc");
                   5976:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5977:         return 1;
                   5978:     }
1.1339    raeburn  5979:     my ($ip,$allowed);
                   5980:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5981:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5982:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5983:     } else {
1.1350    raeburn  5984:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5985:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5986:     }
1.682     raeburn  5987: 
                   5988:     my $name;
1.1219    raeburn  5989:     my %access = (
                   5990:                      allowfrom => 1,
                   5991:                      denyfrom  => 0,
                   5992:                  );
                   5993:     my @allows;
                   5994:     my @denies;
                   5995:     foreach my $item (split(',',$acc)) {
                   5996:         $item =~ s/^\s*//;
                   5997:         $item =~ s/\s*$//;
                   5998:         my $pattern;
                   5999:         if ($item =~ /^\!(.+)$/) {
                   6000:             push(@denies,$1);
                   6001:         } else {
                   6002:             push(@allows,$item);
                   6003:         }
                   6004:    }
                   6005:    my $numdenies = scalar(@denies);
                   6006:    my $numallows = scalar(@allows);
                   6007:    my $count = 0;
                   6008:    foreach my $pattern (@denies,@allows) {
                   6009:         $count ++; 
                   6010:         my $acctype = 'allowfrom';
                   6011:         if ($count <= $numdenies) {
                   6012:             $acctype = 'denyfrom';
                   6013:         }
1.682     raeburn  6014:         if ($pattern =~ /\*$/) {
                   6015:             #35.8.*
                   6016:             $pattern=~s/\*//;
1.1219    raeburn  6017:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6018:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6019:             #35.8.3.[34-56]
                   6020:             my $low=$2;
                   6021:             my $high=$3;
                   6022:             $pattern=$1;
                   6023:             if ($ip =~ /^\Q$pattern\E/) {
                   6024:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6025:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6026:             }
                   6027:         } elsif ($pattern =~ /^\*/) {
                   6028:             #*.msu.edu
                   6029:             $pattern=~s/\*//;
                   6030:             if (!defined($name)) {
                   6031:                 use Socket;
                   6032:                 my $netaddr=inet_aton($ip);
                   6033:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6034:             }
1.1219    raeburn  6035:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6036:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6037:             #127.0.0.1
1.1219    raeburn  6038:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6039:         } else {
                   6040:             #some.name.com
                   6041:             if (!defined($name)) {
                   6042:                 use Socket;
                   6043:                 my $netaddr=inet_aton($ip);
                   6044:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6045:             }
1.1219    raeburn  6046:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6047:         }
                   6048:         if ($allowed =~ /^(0|1)$/) { last; }
                   6049:     }
                   6050:     if ($allowed eq '') {
                   6051:         if ($numdenies && !$numallows) {
                   6052:             $allowed = 1;
                   6053:         } else {
                   6054:             $allowed = 0;
1.682     raeburn  6055:         }
                   6056:     }
                   6057:     return $allowed;
                   6058: }
                   6059: 
                   6060: ###############################################
                   6061: 
1.60      matthew  6062: =pod
                   6063: 
1.112     bowersj2 6064: =head1 Domain Template Functions
                   6065: 
                   6066: =over 4
                   6067: 
                   6068: =item * &determinedomain()
1.60      matthew  6069: 
                   6070: Inputs: $domain (usually will be undef)
                   6071: 
1.63      www      6072: Returns: Determines which domain should be used for designs
1.60      matthew  6073: 
                   6074: =cut
1.54      www      6075: 
1.60      matthew  6076: ###############################################
1.63      www      6077: sub determinedomain {
                   6078:     my $domain=shift;
1.531     albertel 6079:     if (! $domain) {
1.60      matthew  6080:         # Determine domain if we have not been given one
1.893     raeburn  6081:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6082:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6083:         if ($env{'request.role.domain'}) { 
                   6084:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6085:         }
                   6086:     }
1.63      www      6087:     return $domain;
                   6088: }
                   6089: ###############################################
1.517     raeburn  6090: 
1.518     albertel 6091: sub devalidate_domconfig_cache {
                   6092:     my ($udom)=@_;
                   6093:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6094: }
                   6095: 
                   6096: # ---------------------- Get domain configuration for a domain
                   6097: sub get_domainconf {
                   6098:     my ($udom) = @_;
                   6099:     my $cachetime=1800;
                   6100:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6101:     if (defined($cached)) { return %{$result}; }
                   6102: 
                   6103:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6104: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6105:     my (%designhash,%legacy);
1.518     albertel 6106:     if (keys(%domconfig) > 0) {
                   6107:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6108:             if (keys(%{$domconfig{'login'}})) {
                   6109:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6110:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6111:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6112:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6113:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6114:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6115:                                         if ($key eq 'loginvia') {
                   6116:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6117:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6118:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6119:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6120: 
                   6121:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6122:                                                 } else {
                   6123:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6124:                                                 }
1.948     raeburn  6125:                                             }
1.1208    raeburn  6126:                                         } elsif ($key eq 'headtag') {
                   6127:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6128:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6129:                                             }
1.946     raeburn  6130:                                         }
1.1208    raeburn  6131:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6132:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6133:                                         }
1.946     raeburn  6134:                                     }
                   6135:                                 }
                   6136:                             }
1.1366    raeburn  6137:                         } elsif ($key eq 'saml') {
                   6138:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6139:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6140:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6141:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6142:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6143:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6144:                                         }
                   6145:                                     }
                   6146:                                 }
                   6147:                             }
1.946     raeburn  6148:                         } else {
                   6149:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6150:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6151:                                     $domconfig{'login'}{$key}{$img};
                   6152:                             }
1.699     raeburn  6153:                         }
                   6154:                     } else {
                   6155:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6156:                     }
1.632     raeburn  6157:                 }
                   6158:             } else {
                   6159:                 $legacy{'login'} = 1;
1.518     albertel 6160:             }
1.632     raeburn  6161:         } else {
                   6162:             $legacy{'login'} = 1;
1.518     albertel 6163:         }
                   6164:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6165:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6166:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6167:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6168:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6169:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6170:                         }
1.518     albertel 6171:                     }
                   6172:                 }
1.632     raeburn  6173:             } else {
                   6174:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6175:             }
1.632     raeburn  6176:         } else {
                   6177:             $legacy{'rolecolors'} = 1;
1.518     albertel 6178:         }
1.948     raeburn  6179:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6180:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6181:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6182:             }
                   6183:         }
1.632     raeburn  6184:         if (keys(%legacy) > 0) {
                   6185:             my %legacyhash = &get_legacy_domconf($udom);
                   6186:             foreach my $item (keys(%legacyhash)) {
                   6187:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6188:                     if ($legacy{'login'}) { 
                   6189:                         $designhash{$item} = $legacyhash{$item};
                   6190:                     }
                   6191:                 } else {
                   6192:                     if ($legacy{'rolecolors'}) {
                   6193:                         $designhash{$item} = $legacyhash{$item};
                   6194:                     }
1.518     albertel 6195:                 }
                   6196:             }
                   6197:         }
1.632     raeburn  6198:     } else {
                   6199:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6200:     }
                   6201:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6202: 				  $cachetime);
                   6203:     return %designhash;
                   6204: }
                   6205: 
1.632     raeburn  6206: sub get_legacy_domconf {
                   6207:     my ($udom) = @_;
                   6208:     my %legacyhash;
                   6209:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6210:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6211:     if (-e $designfile) {
1.1317    raeburn  6212:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6213:             while (my $line = <$fh>) {
                   6214:                 next if ($line =~ /^\#/);
                   6215:                 chomp($line);
                   6216:                 my ($key,$val)=(split(/\=/,$line));
                   6217:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6218:             }
                   6219:             close($fh);
                   6220:         }
                   6221:     }
1.1026    raeburn  6222:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6223:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6224:     }
                   6225:     return %legacyhash;
                   6226: }
                   6227: 
1.63      www      6228: =pod
                   6229: 
1.112     bowersj2 6230: =item * &domainlogo()
1.63      www      6231: 
                   6232: Inputs: $domain (usually will be undef)
                   6233: 
                   6234: Returns: A link to a domain logo, if the domain logo exists.
                   6235: If the domain logo does not exist, a description of the domain.
                   6236: 
                   6237: =cut
1.112     bowersj2 6238: 
1.63      www      6239: ###############################################
                   6240: sub domainlogo {
1.517     raeburn  6241:     my $domain = &determinedomain(shift);
1.518     albertel 6242:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6243:     # See if there is a logo
                   6244:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6245:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6246:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6247: 	    if ($imgsrc =~ m{^/res/}) {
                   6248: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6249: 		&Apache::lonnet::repcopy($local_name);
                   6250: 	    }
                   6251: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6252:         }
                   6253:         my $alttext = $domain;
                   6254:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6255:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6256:         }
                   6257:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6258:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6259:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6260:     } else {
1.60      matthew  6261:         return '';
1.59      www      6262:     }
                   6263: }
1.63      www      6264: ##############################################
                   6265: 
                   6266: =pod
                   6267: 
1.112     bowersj2 6268: =item * &designparm()
1.63      www      6269: 
                   6270: Inputs: $which parameter; $domain (usually will be undef)
                   6271: 
                   6272: Returns: value of designparamter $which
                   6273: 
                   6274: =cut
1.112     bowersj2 6275: 
1.397     albertel 6276: 
1.400     albertel 6277: ##############################################
1.397     albertel 6278: sub designparm {
                   6279:     my ($which,$domain)=@_;
                   6280:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6281:         return $env{'environment.color.'.$which};
1.96      www      6282:     }
1.63      www      6283:     $domain=&determinedomain($domain);
1.1016    raeburn  6284:     my %domdesign;
                   6285:     unless ($domain eq 'public') {
                   6286:         %domdesign = &get_domainconf($domain);
                   6287:     }
1.520     raeburn  6288:     my $output;
1.517     raeburn  6289:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6290:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6291:     } else {
1.520     raeburn  6292:         $output = $defaultdesign{$which};
                   6293:     }
                   6294:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6295:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6296:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6297:             if ($output =~ m{^/res/}) {
                   6298:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6299:                 &Apache::lonnet::repcopy($local_name);
                   6300:             }
1.520     raeburn  6301:             $output = &lonhttpdurl($output);
                   6302:         }
1.63      www      6303:     }
1.520     raeburn  6304:     return $output;
1.63      www      6305: }
1.59      www      6306: 
1.822     bisitz   6307: ##############################################
                   6308: =pod
                   6309: 
1.832     bisitz   6310: =item * &authorspace()
                   6311: 
1.1028    raeburn  6312: Inputs: $url (usually will be undef).
1.832     bisitz   6313: 
1.1132    raeburn  6314: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6315:          directory being viewed (or for which action is being taken). 
                   6316:          If $url is provided, and begins /priv/<domain>/<uname>
                   6317:          the path will be that portion of the $context argument.
                   6318:          Otherwise the path will be for the author space of the current
                   6319:          user when the current role is author, or for that of the 
                   6320:          co-author/assistant co-author space when the current role 
                   6321:          is co-author or assistant co-author.
1.832     bisitz   6322: 
                   6323: =cut
                   6324: 
                   6325: sub authorspace {
1.1028    raeburn  6326:     my ($url) = @_;
                   6327:     if ($url ne '') {
                   6328:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6329:            return $1;
                   6330:         }
                   6331:     }
1.832     bisitz   6332:     my $caname = '';
1.1024    www      6333:     my $cadom = '';
1.1028    raeburn  6334:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6335:         ($cadom,$caname) =
1.832     bisitz   6336:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6337:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6338:         $caname = $env{'user.name'};
1.1024    www      6339:         $cadom = $env{'user.domain'};
1.832     bisitz   6340:     }
1.1028    raeburn  6341:     if (($caname ne '') && ($cadom ne '')) {
                   6342:         return "/priv/$cadom/$caname/";
                   6343:     }
                   6344:     return;
1.832     bisitz   6345: }
                   6346: 
                   6347: ##############################################
                   6348: =pod
                   6349: 
1.822     bisitz   6350: =item * &head_subbox()
                   6351: 
                   6352: Inputs: $content (contains HTML code with page functions, etc.)
                   6353: 
                   6354: Returns: HTML div with $content
                   6355:          To be included in page header
                   6356: 
                   6357: =cut
                   6358: 
                   6359: sub head_subbox {
                   6360:     my ($content)=@_;
                   6361:     my $output =
1.993     raeburn  6362:         '<div class="LC_head_subbox">'
1.822     bisitz   6363:        .$content
                   6364:        .'</div>'
                   6365: }
                   6366: 
                   6367: ##############################################
                   6368: =pod
                   6369: 
                   6370: =item * &CSTR_pageheader()
                   6371: 
1.1026    raeburn  6372: Input: (optional) filename from which breadcrumb trail is built.
                   6373:        In most cases no input as needed, as $env{'request.filename'}
                   6374:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6375:        frameset flag
                   6376:        If page header is being requested for use in a frameset, then
                   6377:        the second (option) argument -- frameset will be true, and
                   6378:        the target attribute set for links should be target="_parent".
1.1407    raeburn  6379:        If $title is supplied as the thitd arg, that will be used to 
                   6380:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6381: 
                   6382: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6383:          To be included on Authoring Space pages
1.822     bisitz   6384: 
                   6385: =cut
                   6386: 
                   6387: sub CSTR_pageheader {
1.1407    raeburn  6388:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6389:     if ($trailfile eq '') {
                   6390:         $trailfile = $env{'request.filename'};
                   6391:     }
                   6392: 
                   6393: # this is for resources; directories have customtitle, and crumbs
                   6394: # and select recent are created in lonpubdir.pm
                   6395: 
                   6396:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6397:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6398:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6399:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6400:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6401: 
                   6402:     my $parentpath = '';
                   6403:     my $lastitem = '';
                   6404:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6405:         $parentpath = $1;
                   6406:         $lastitem = $2;
                   6407:     } else {
                   6408:         $lastitem = $thisdisfn;
                   6409:     }
1.921     bisitz   6410: 
1.1406    raeburn  6411:     my $crsauthor;
1.1246    raeburn  6412:     if (($env{'request.course.id'}) &&
                   6413:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6414:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6415:         $crsauthor = 1;
1.1406    raeburn  6416:         if ($title eq '') {
                   6417:             $title = &mt('Course Authoring Space');
                   6418:         }
                   6419:     } elsif ($title eq '') {
1.1246    raeburn  6420:         $title = &mt('Authoring Space');
                   6421:     }
                   6422: 
1.1379    raeburn  6423:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6424:     if ($frameset) {
                   6425:         $target = ' target="_parent"';
                   6426:         $crumbtarget = '_parent';
                   6427:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6428:         $target = '';
                   6429:         $crumbtarget = '';
1.1379    raeburn  6430:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6431:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6432:         $crumbtarget = $env{'request.deeplink.target'};
                   6433:     }
1.1313    raeburn  6434: 
1.921     bisitz   6435:     my $output =
1.1407    raeburn  6436:          '<div>'
1.822     bisitz   6437:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6438:         .'<b>'.$title.'</b> '
1.1314    raeburn  6439:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6440:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6441: 
                   6442:     if ($lastitem) {
                   6443:         $output .=
                   6444:              '<span class="LC_filename">'
                   6445:             .$lastitem
                   6446:             .'</span>';
                   6447:     }
1.1245    raeburn  6448: 
1.1246    raeburn  6449:     if ($crsauthor) {
1.1379    raeburn  6450:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6451:     } else {
                   6452:         $output .=
                   6453:              '<br />'
1.1314    raeburn  6454:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6455:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6456:             .'</form>'
1.1379    raeburn  6457:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6458:     }
1.1407    raeburn  6459:     $output .= '</div>';
1.921     bisitz   6460: 
                   6461:     return $output;
1.822     bisitz   6462: }
                   6463: 
1.60      matthew  6464: ###############################################
                   6465: ###############################################
                   6466: 
                   6467: =pod
                   6468: 
1.112     bowersj2 6469: =back
                   6470: 
1.549     albertel 6471: =head1 HTML Helpers
1.112     bowersj2 6472: 
                   6473: =over 4
                   6474: 
                   6475: =item * &bodytag()
1.60      matthew  6476: 
                   6477: Returns a uniform header for LON-CAPA web pages.
                   6478: 
                   6479: Inputs: 
                   6480: 
1.112     bowersj2 6481: =over 4
                   6482: 
                   6483: =item * $title, A title to be displayed on the page.
                   6484: 
                   6485: =item * $function, the current role (can be undef).
                   6486: 
                   6487: =item * $addentries, extra parameters for the <body> tag.
                   6488: 
                   6489: =item * $bodyonly, if defined, only return the <body> tag.
                   6490: 
                   6491: =item * $domain, if defined, force a given domain.
                   6492: 
                   6493: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6494:             text interface only)
1.60      matthew  6495: 
1.814     bisitz   6496: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6497:                      navigational links
1.317     albertel 6498: 
1.338     albertel 6499: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6500: 
1.460     albertel 6501: =item * $args, optional argument valid values are
                   6502:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6503:             use_absolute     -> for external resource or syllabus, this will
                   6504:                                 contain https://<hostname> if server uses
                   6505:                                 https (as per hosts.tab), but request is for http
                   6506:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6507: 
1.1096    raeburn  6508: =item * $advtoolsref, optional argument, ref to an array containing
                   6509:             inlineremote items to be added in "Functions" menu below
                   6510:             breadcrumbs.
                   6511: 
1.1316    raeburn  6512: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6513:             course, if LON-CAPA is in LTI Provider context. Value is
                   6514:             the scope of use, i.e., launch was for access to a single, a map
                   6515:             or the entire course.
                   6516: 
                   6517: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6518:             context, this will contain the URL for the landing item in
                   6519:             the course, after launch from an LTI Consumer
                   6520: 
1.1318    raeburn  6521: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6522:             context, this will contain a reference to hash of items
                   6523:             to be included in the page header and/or inline menu.
                   6524: 
1.1385    raeburn  6525: =item * $menucoll, optional argument, if specific menu collection is in
                   6526:             effect, either set as the default for the course, or set for
                   6527:             the deeplink paramater for $env{'request.deeplink.login'}
                   6528:             then $menucoll will be the number of that collection. 
                   6529: 
                   6530: =item * $menuref, optional argument, reference to a hash, containing the
                   6531:             menu options included for the menu in effect, based on the
                   6532:             configuration for the numbered menu collection in use.  
                   6533: 
                   6534: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6535:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6536:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6537:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6538:             being called a second time.
                   6539: 
1.112     bowersj2 6540: =back
                   6541: 
1.60      matthew  6542: Returns: A uniform header for LON-CAPA web pages.  
                   6543: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6544: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6545: other decorations will be returned.
                   6546: 
                   6547: =cut
                   6548: 
1.54      www      6549: sub bodytag {
1.831     bisitz   6550:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6551:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6552:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6553: 
1.954     raeburn  6554:     my $public;
                   6555:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6556:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6557:         $public = 1;
                   6558:     }
1.460     albertel 6559:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6560:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6561:     my $hostname = $args->{'hostname'};
1.339     albertel 6562: 
1.183     matthew  6563:     $function = &get_users_function() if (!$function);
1.339     albertel 6564:     my $img =    &designparm($function.'.img',$domain);
                   6565:     my $font =   &designparm($function.'.font',$domain);
                   6566:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6567: 
1.803     bisitz   6568:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6569: 		   'bgcolor' => $pgbg,
1.339     albertel 6570: 		   'text'    => $font,
                   6571:                    'alink'   => &designparm($function.'.alink',$domain),
                   6572: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6573: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6574:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6575: 
1.63      www      6576:  # role and realm
1.1178    raeburn  6577:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6578:     if ($realm) {
                   6579:         $realm = '/'.$realm;
                   6580:     }
1.1357    raeburn  6581:     if ($role eq 'ca') {
1.479     albertel 6582:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6583:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6584:     } 
1.55      www      6585: # realm
1.1357    raeburn  6586:     my ($cid,$sec);
1.258     albertel 6587:     if ($env{'request.course.id'}) {
1.1357    raeburn  6588:         $cid = $env{'request.course.id'};
                   6589:         if ($env{'request.course.sec'}) {
                   6590:             $sec = $env{'request.course.sec'};
                   6591:         }
                   6592:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6593:         if (&Apache::lonnet::is_course($1,$2)) {
                   6594:             $cid = $1.'_'.$2;
                   6595:             $sec = $3;
                   6596:         }
                   6597:     }
                   6598:     if ($cid) {
1.378     raeburn  6599:         if ($env{'request.role'} !~ /^cr/) {
                   6600:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6601:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6602:             if ($env{'request.role.desc'}) {
                   6603:                 $role = $env{'request.role.desc'};
                   6604:             } else {
                   6605:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6606:             }
1.1257    raeburn  6607:         } else {
                   6608:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6609:         }
1.1357    raeburn  6610:         if ($sec) {
                   6611:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6612:         }   
1.1357    raeburn  6613: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6614:     } else {
                   6615:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6616:     }
1.433     albertel 6617: 
1.359     albertel 6618:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6619: 
1.438     albertel 6620:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6621: 
1.101     www      6622: # construct main body tag
1.359     albertel 6623:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6624: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6625: 
1.1131    raeburn  6626:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6627: 
1.1130    raeburn  6628:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6629:         return $bodytag;
1.1130    raeburn  6630:     }
1.359     albertel 6631: 
1.954     raeburn  6632:     if ($public) {
1.433     albertel 6633: 	undef($role);
                   6634:     }
1.1318    raeburn  6635: 
1.1359    raeburn  6636:     my $showcrstitle = 1;
1.1357    raeburn  6637:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6638:         if (ref($ltimenu) eq 'HASH') {
                   6639:             unless ($ltimenu->{'role'}) {
                   6640:                 undef($role);
                   6641:             }
                   6642:             unless ($ltimenu->{'coursetitle'}) {
                   6643:                 $realm='&nbsp;';
1.1359    raeburn  6644:                 $showcrstitle = 0;
                   6645:             }
                   6646:         }
                   6647:     } elsif (($cid) && ($menucoll)) {
                   6648:         if (ref($menuref) eq 'HASH') {
                   6649:             unless ($menuref->{'role'}) {
                   6650:                 undef($role);
                   6651:             }
                   6652:             unless ($menuref->{'crs'}) {
                   6653:                 $realm='&nbsp;';
                   6654:                 $showcrstitle = 0;
1.1318    raeburn  6655:             }
                   6656:         }
                   6657:     }
                   6658: 
1.762     bisitz   6659:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6660:     #
                   6661:     # Extra info if you are the DC
                   6662:     my $dc_info = '';
1.1359    raeburn  6663:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6664:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6665:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6666:         $dc_info =~ s/\s+$//;
1.359     albertel 6667:     }
                   6668: 
1.1237    raeburn  6669:     my $crstype;
1.1357    raeburn  6670:     if ($cid) {
                   6671:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6672:     } elsif ($args->{'crstype'}) {
                   6673:         $crstype = $args->{'crstype'};
                   6674:     }
                   6675:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6676:         undef($role);
                   6677:     } else {
1.1242    raeburn  6678:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6679:     }
1.853     droeschl 6680: 
1.903     droeschl 6681:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6682: 
                   6683:         #    if ($env{'request.state'} eq 'construct') {
                   6684:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6685:         #    }
                   6686: 
1.1130    raeburn  6687:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6688:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6689: 
1.1318    raeburn  6690:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6691:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6692:                                                               $args->{'links_disabled'},
                   6693:                                                               $args->{'links_target'});
1.359     albertel 6694: 
1.1318    raeburn  6695:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6696:                 if ($dc_info) {
                   6697:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6698:                 }
                   6699:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6700:                                <em>$realm</em> $dc_info</div>|;
                   6701:                 return $bodytag;
                   6702:             }
1.894     droeschl 6703: 
1.1318    raeburn  6704:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6705:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6706:             }
1.916     droeschl 6707: 
1.1318    raeburn  6708:             $bodytag .= $right;
1.852     droeschl 6709: 
1.1318    raeburn  6710:             if ($dc_info) {
                   6711:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6712:             }
                   6713:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6714:         }
1.916     droeschl 6715: 
1.1169    raeburn  6716:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6717:         if ($args->{'no_secondary_menu'}) {
                   6718:             return $bodytag;
                   6719:         }
1.1169    raeburn  6720:         #don't show menus for public users
1.954     raeburn  6721:         if (!$public){
1.1318    raeburn  6722:             unless ($args->{'no_inline_menu'}) {
                   6723:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6724:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6725:                                                             $menucoll,$menuref,
1.1380    raeburn  6726:                                                             $args->{'links_disabled'},
                   6727:                                                             $args->{'links_target'});
1.1318    raeburn  6728:             }
1.903     droeschl 6729:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6730:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6731:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6732:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  6733:                                 $args->{'bread_crumbs'},'','',$hostname,
                   6734:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6735:             } elsif ($forcereg) {
                   6736:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  6737:                                 $args->{'group'},$args->{'hide_buttons'},
                   6738:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6739:             } else {
                   6740:                 $bodytag .= 
                   6741:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6742:                                                         $forcereg,$args->{'group'},
                   6743:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6744:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6745:             }
1.903     droeschl 6746:         }else{
                   6747:             # this is to seperate menu from content when there's no secondary
                   6748:             # menu. Especially needed for public accessible ressources.
                   6749:             $bodytag .= '<hr style="clear:both" />';
                   6750:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6751:         }
1.903     droeschl 6752: 
1.235     raeburn  6753:         return $bodytag;
1.182     matthew  6754: }
                   6755: 
1.917     raeburn  6756: sub dc_courseid_toggle {
                   6757:     my ($dc_info) = @_;
1.980     raeburn  6758:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6759:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6760:            &mt('(More ...)').'</a></span>'.
                   6761:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6762: }
                   6763: 
1.330     albertel 6764: sub make_attr_string {
                   6765:     my ($register,$attr_ref) = @_;
                   6766: 
                   6767:     if ($attr_ref && !ref($attr_ref)) {
                   6768: 	die("addentries Must be a hash ref ".
                   6769: 	    join(':',caller(1))." ".
                   6770: 	    join(':',caller(0))." ");
                   6771:     }
                   6772: 
                   6773:     if ($register) {
1.339     albertel 6774: 	my ($on_load,$on_unload);
                   6775: 	foreach my $key (keys(%{$attr_ref})) {
                   6776: 	    if      (lc($key) eq 'onload') {
                   6777: 		$on_load.=$attr_ref->{$key}.';';
                   6778: 		delete($attr_ref->{$key});
                   6779: 
                   6780: 	    } elsif (lc($key) eq 'onunload') {
                   6781: 		$on_unload.=$attr_ref->{$key}.';';
                   6782: 		delete($attr_ref->{$key});
                   6783: 	    }
                   6784: 	}
1.953     droeschl 6785: 	$attr_ref->{'onload'}  = $on_load;
                   6786: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6787:     }
1.339     albertel 6788: 
1.330     albertel 6789:     my $attr_string;
1.1159    raeburn  6790:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6791: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6792:     }
                   6793:     return $attr_string;
                   6794: }
                   6795: 
                   6796: 
1.182     matthew  6797: ###############################################
1.251     albertel 6798: ###############################################
                   6799: 
                   6800: =pod
                   6801: 
                   6802: =item * &endbodytag()
                   6803: 
                   6804: Returns a uniform footer for LON-CAPA web pages.
                   6805: 
1.635     raeburn  6806: Inputs: 1 - optional reference to an args hash
                   6807: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6808: a 'Continue' link is not displayed if the page contains an
                   6809: internal redirect in the <head></head> section,
                   6810: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6811: 
                   6812: =cut
                   6813: 
                   6814: sub endbodytag {
1.635     raeburn  6815:     my ($args) = @_;
1.1080    raeburn  6816:     my $endbodytag;
                   6817:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6818:         $endbodytag='</body>';
                   6819:     }
1.315     albertel 6820:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6821:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  6822:             my ($endbodyjs,$idattr);
                   6823:             if ($env{'internal.head.to_opener'}) {
                   6824:                 my $linkid = 'LC_continue_link';
                   6825:                 $idattr = ' id="'.$linkid.'"';
                   6826:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6827:                 $endbodyjs=<<ENDJS;
                   6828: <script type="text/javascript">
                   6829: // <![CDATA[
                   6830: function ebFunction(evt) {
                   6831:     evt.preventDefault();
                   6832:     var dest = '$redirect_for_js';
                   6833:     if (window.opener != null && !window.opener.closed) {
                   6834:         window.opener.location.href=dest;
                   6835:         window.close();
                   6836:     } else {
                   6837:         window.location.href=dest;
                   6838:     }
                   6839:     return false;
                   6840: }
                   6841: 
                   6842: \$(document).ready(function () {
                   6843:   if (document.getElementById('$linkid')) {
                   6844:     var clickelem = document.getElementById('$linkid');
                   6845:     clickelem.addEventListener('click',ebFunction,false);
                   6846:   }
                   6847: });
                   6848: // ]]>
                   6849: </script>
                   6850: ENDJS
                   6851:             }
1.635     raeburn  6852: 	    $endbodytag=
1.1386    raeburn  6853: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6854: 	        &mt('Continue').'</a>'.
                   6855: 	        $endbodytag;
                   6856:         }
1.315     albertel 6857:     }
1.1411    raeburn  6858:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   6859:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   6860:     }
1.251     albertel 6861:     return $endbodytag;
                   6862: }
                   6863: 
1.352     albertel 6864: =pod
                   6865: 
                   6866: =item * &standard_css()
                   6867: 
                   6868: Returns a style sheet
                   6869: 
                   6870: Inputs: (all optional)
                   6871:             domain         -> force to color decorate a page for a specific
                   6872:                                domain
                   6873:             function       -> force usage of a specific rolish color scheme
                   6874:             bgcolor        -> override the default page bgcolor
                   6875: 
                   6876: =cut
                   6877: 
1.343     albertel 6878: sub standard_css {
1.345     albertel 6879:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6880:     $function  = &get_users_function() if (!$function);
                   6881:     my $img    = &designparm($function.'.img',   $domain);
                   6882:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6883:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6884:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6885: #second colour for later usage
1.345     albertel 6886:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6887:     my $pgbg_or_bgcolor =
                   6888: 	         $bgcolor ||
1.352     albertel 6889: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6890:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6891:     my $alink  = &designparm($function.'.alink', $domain);
                   6892:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6893:     my $link   = &designparm($function.'.link',  $domain);
                   6894: 
1.602     albertel 6895:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6896:     my $mono                 = 'monospace';
1.850     bisitz   6897:     my $data_table_head      = $sidebg;
                   6898:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6899:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6900:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6901:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6902:     my $mail_new             = '#FFBB77';
                   6903:     my $mail_new_hover       = '#DD9955';
                   6904:     my $mail_read            = '#BBBB77';
                   6905:     my $mail_read_hover      = '#999944';
                   6906:     my $mail_replied         = '#AAAA88';
                   6907:     my $mail_replied_hover   = '#888855';
                   6908:     my $mail_other           = '#99BBBB';
                   6909:     my $mail_other_hover     = '#669999';
1.391     albertel 6910:     my $table_header         = '#DDDDDD';
1.489     raeburn  6911:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6912:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6913:     my $button_hover         = '#BF2317';
1.392     albertel 6914: 
1.608     albertel 6915:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6916:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6917:                                              : '0 3px 0 4px';
1.448     albertel 6918: 
1.523     albertel 6919: 
1.343     albertel 6920:     return <<END;
1.947     droeschl 6921: 
                   6922: /* needed for iframe to allow 100% height in FF */
                   6923: body, html { 
                   6924:     margin: 0;
                   6925:     padding: 0 0.5%;
                   6926:     height: 99%; /* to avoid scrollbars */
                   6927: }
                   6928: 
1.795     www      6929: body {
1.911     bisitz   6930:   font-family: $sans;
                   6931:   line-height:130%;
                   6932:   font-size:0.83em;
                   6933:   color:$font;
1.795     www      6934: }
                   6935: 
1.959     onken    6936: a:focus,
                   6937: a:focus img {
1.795     www      6938:   color: red;
                   6939: }
1.698     harmsja  6940: 
1.911     bisitz   6941: form, .inline {
                   6942:   display: inline;
1.795     www      6943: }
1.721     harmsja  6944: 
1.795     www      6945: .LC_right {
1.911     bisitz   6946:   text-align:right;
1.795     www      6947: }
                   6948: 
                   6949: .LC_middle {
1.911     bisitz   6950:   vertical-align:middle;
1.795     www      6951: }
1.721     harmsja  6952: 
1.1130    raeburn  6953: .LC_floatleft {
                   6954:   float: left;
                   6955: }
                   6956: 
                   6957: .LC_floatright {
                   6958:   float: right;
                   6959: }
                   6960: 
1.911     bisitz   6961: .LC_400Box {
                   6962:   width:400px;
                   6963: }
1.721     harmsja  6964: 
1.947     droeschl 6965: .LC_iframecontainer {
                   6966:     width: 98%;
                   6967:     margin: 0;
                   6968:     position: fixed;
                   6969:     top: 8.5em;
                   6970:     bottom: 0;
                   6971: }
                   6972: 
                   6973: .LC_iframecontainer iframe{
                   6974:     border: none;
                   6975:     width: 100%;
                   6976:     height: 100%;
                   6977: }
                   6978: 
1.778     bisitz   6979: .LC_filename {
                   6980:   font-family: $mono;
                   6981:   white-space:pre;
1.921     bisitz   6982:   font-size: 120%;
1.778     bisitz   6983: }
                   6984: 
                   6985: .LC_fileicon {
                   6986:   border: none;
                   6987:   height: 1.3em;
                   6988:   vertical-align: text-bottom;
                   6989:   margin-right: 0.3em;
                   6990:   text-decoration:none;
                   6991: }
                   6992: 
1.1008    www      6993: .LC_setting {
                   6994:   text-decoration:underline;
                   6995: }
                   6996: 
1.350     albertel 6997: .LC_error {
                   6998:   color: red;
                   6999: }
1.795     www      7000: 
1.1097    bisitz   7001: .LC_warning {
                   7002:   color: darkorange;
                   7003: }
                   7004: 
1.457     albertel 7005: .LC_diff_removed {
1.733     bisitz   7006:   color: red;
1.394     albertel 7007: }
1.532     albertel 7008: 
                   7009: .LC_info,
1.457     albertel 7010: .LC_success,
                   7011: .LC_diff_added {
1.350     albertel 7012:   color: green;
                   7013: }
1.795     www      7014: 
1.802     bisitz   7015: div.LC_confirm_box {
                   7016:   background-color: #FAFAFA;
                   7017:   border: 1px solid $lg_border_color;
                   7018:   margin-right: 0;
                   7019:   padding: 5px;
                   7020: }
                   7021: 
                   7022: div.LC_confirm_box .LC_error img,
                   7023: div.LC_confirm_box .LC_success img {
                   7024:   vertical-align: middle;
                   7025: }
                   7026: 
1.1242    raeburn  7027: .LC_maxwidth {
                   7028:   max-width: 100%;
                   7029:   height: auto;
                   7030: }
                   7031: 
1.1243    raeburn  7032: .LC_textsize_mobile {
                   7033:   \@media only screen and (max-device-width: 480px) {
                   7034:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7035:   }
                   7036: }
                   7037: 
1.440     albertel 7038: .LC_icon {
1.771     droeschl 7039:   border: none;
1.790     droeschl 7040:   vertical-align: middle;
1.771     droeschl 7041: }
                   7042: 
1.543     albertel 7043: .LC_docs_spacer {
                   7044:   width: 25px;
                   7045:   height: 1px;
1.771     droeschl 7046:   border: none;
1.543     albertel 7047: }
1.346     albertel 7048: 
1.532     albertel 7049: .LC_internal_info {
1.735     bisitz   7050:   color: #999999;
1.532     albertel 7051: }
                   7052: 
1.794     www      7053: .LC_discussion {
1.1050    www      7054:   background: $data_table_dark;
1.911     bisitz   7055:   border: 1px solid black;
                   7056:   margin: 2px;
1.794     www      7057: }
                   7058: 
                   7059: .LC_disc_action_left {
1.1050    www      7060:   background: $sidebg;
1.911     bisitz   7061:   text-align: left;
1.1050    www      7062:   padding: 4px;
                   7063:   margin: 2px;
1.794     www      7064: }
                   7065: 
                   7066: .LC_disc_action_right {
1.1050    www      7067:   background: $sidebg;
1.911     bisitz   7068:   text-align: right;
1.1050    www      7069:   padding: 4px;
                   7070:   margin: 2px;
1.794     www      7071: }
                   7072: 
                   7073: .LC_disc_new_item {
1.911     bisitz   7074:   background: white;
                   7075:   border: 2px solid red;
1.1050    www      7076:   margin: 4px;
                   7077:   padding: 4px;
1.794     www      7078: }
                   7079: 
                   7080: .LC_disc_old_item {
1.911     bisitz   7081:   background: white;
1.1050    www      7082:   margin: 4px;
                   7083:   padding: 4px;
1.794     www      7084: }
                   7085: 
1.458     albertel 7086: table.LC_pastsubmission {
                   7087:   border: 1px solid black;
                   7088:   margin: 2px;
                   7089: }
                   7090: 
1.924     bisitz   7091: table#LC_menubuttons {
1.345     albertel 7092:   width: 100%;
                   7093:   background: $pgbg;
1.392     albertel 7094:   border: 2px;
1.402     albertel 7095:   border-collapse: separate;
1.803     bisitz   7096:   padding: 0;
1.345     albertel 7097: }
1.392     albertel 7098: 
1.801     tempelho 7099: table#LC_title_bar a {
                   7100:   color: $fontmenu;
                   7101: }
1.836     bisitz   7102: 
1.807     droeschl 7103: table#LC_title_bar {
1.819     tempelho 7104:   clear: both;
1.836     bisitz   7105:   display: none;
1.807     droeschl 7106: }
                   7107: 
1.795     www      7108: table#LC_title_bar,
1.933     droeschl 7109: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7110: table#LC_title_bar.LC_with_remote {
1.359     albertel 7111:   width: 100%;
1.392     albertel 7112:   border-color: $pgbg;
                   7113:   border-style: solid;
                   7114:   border-width: $border;
1.379     albertel 7115:   background: $pgbg;
1.801     tempelho 7116:   color: $fontmenu;
1.392     albertel 7117:   border-collapse: collapse;
1.803     bisitz   7118:   padding: 0;
1.819     tempelho 7119:   margin: 0;
1.359     albertel 7120: }
1.795     www      7121: 
1.933     droeschl 7122: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7123:     margin: 0;
                   7124:     padding: 0;
1.933     droeschl 7125:     position: relative;
                   7126:     list-style: none;
1.913     droeschl 7127: }
1.933     droeschl 7128: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7129:     display: inline;
                   7130: }
1.933     droeschl 7131: 
                   7132: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7133:     padding: 0;
1.933     droeschl 7134:     margin: 0;
                   7135:     float: left;
1.913     droeschl 7136: }
1.933     droeschl 7137: .LC_breadcrumb_tools_tools {
                   7138:     padding: 0;
                   7139:     margin: 0;
1.913     droeschl 7140:     float: right;
                   7141: }
                   7142: 
1.1240    raeburn  7143: .LC_placement_prog {
                   7144:     padding-right: 20px;
                   7145:     font-weight: bold;
                   7146:     font-size: 90%;
                   7147: }
                   7148: 
1.359     albertel 7149: table#LC_title_bar td {
                   7150:   background: $tabbg;
                   7151: }
1.795     www      7152: 
1.911     bisitz   7153: table#LC_menubuttons img {
1.803     bisitz   7154:   border: none;
1.346     albertel 7155: }
1.795     www      7156: 
1.842     droeschl 7157: .LC_breadcrumbs_component {
1.911     bisitz   7158:   float: right;
                   7159:   margin: 0 1em;
1.357     albertel 7160: }
1.842     droeschl 7161: .LC_breadcrumbs_component img {
1.911     bisitz   7162:   vertical-align: middle;
1.777     tempelho 7163: }
1.795     www      7164: 
1.1243    raeburn  7165: .LC_breadcrumbs_hoverable {
                   7166:   background: $sidebg;
                   7167: }
                   7168: 
1.383     albertel 7169: td.LC_table_cell_checkbox {
                   7170:   text-align: center;
                   7171: }
1.795     www      7172: 
                   7173: .LC_fontsize_small {
1.911     bisitz   7174:   font-size: 70%;
1.705     tempelho 7175: }
                   7176: 
1.844     bisitz   7177: #LC_breadcrumbs {
1.911     bisitz   7178:   clear:both;
                   7179:   background: $sidebg;
                   7180:   border-bottom: 1px solid $lg_border_color;
                   7181:   line-height: 2.5em;
1.933     droeschl 7182:   overflow: hidden;
1.911     bisitz   7183:   margin: 0;
                   7184:   padding: 0;
1.995     raeburn  7185:   text-align: left;
1.819     tempelho 7186: }
1.862     bisitz   7187: 
1.1098    bisitz   7188: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7189:   clear:both;
                   7190:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7191:   border: 1px solid $sidebg;
1.1098    bisitz   7192:   margin: 0 0 10px 0;
1.966     bisitz   7193:   padding: 3px;
1.995     raeburn  7194:   text-align: left;
1.822     bisitz   7195: }
                   7196: 
1.795     www      7197: .LC_fontsize_medium {
1.911     bisitz   7198:   font-size: 85%;
1.705     tempelho 7199: }
                   7200: 
1.795     www      7201: .LC_fontsize_large {
1.911     bisitz   7202:   font-size: 120%;
1.705     tempelho 7203: }
                   7204: 
1.346     albertel 7205: .LC_menubuttons_inline_text {
                   7206:   color: $font;
1.698     harmsja  7207:   font-size: 90%;
1.701     harmsja  7208:   padding-left:3px;
1.346     albertel 7209: }
                   7210: 
1.934     droeschl 7211: .LC_menubuttons_inline_text img{
                   7212:   vertical-align: middle;
                   7213: }
                   7214: 
1.1051    www      7215: li.LC_menubuttons_inline_text img {
1.951     onken    7216:   cursor:pointer;
1.1002    droeschl 7217:   text-decoration: none;
1.951     onken    7218: }
                   7219: 
1.526     www      7220: .LC_menubuttons_link {
                   7221:   text-decoration: none;
                   7222: }
1.795     www      7223: 
1.522     albertel 7224: .LC_menubuttons_category {
1.521     www      7225:   color: $font;
1.526     www      7226:   background: $pgbg;
1.521     www      7227:   font-size: larger;
                   7228:   font-weight: bold;
                   7229: }
                   7230: 
1.346     albertel 7231: td.LC_menubuttons_text {
1.911     bisitz   7232:   color: $font;
1.346     albertel 7233: }
1.706     harmsja  7234: 
1.346     albertel 7235: .LC_current_location {
                   7236:   background: $tabbg;
                   7237: }
1.795     www      7238: 
1.1286    raeburn  7239: td.LC_zero_height {
                   7240:   line-height: 0; 
                   7241:   cellpadding: 0;
                   7242: }
                   7243: 
1.938     bisitz   7244: table.LC_data_table {
1.347     albertel 7245:   border: 1px solid #000000;
1.402     albertel 7246:   border-collapse: separate;
1.426     albertel 7247:   border-spacing: 1px;
1.610     albertel 7248:   background: $pgbg;
1.347     albertel 7249: }
1.795     www      7250: 
1.422     albertel 7251: .LC_data_table_dense {
                   7252:   font-size: small;
                   7253: }
1.795     www      7254: 
1.507     raeburn  7255: table.LC_nested_outer {
                   7256:   border: 1px solid #000000;
1.589     raeburn  7257:   border-collapse: collapse;
1.803     bisitz   7258:   border-spacing: 0;
1.507     raeburn  7259:   width: 100%;
                   7260: }
1.795     www      7261: 
1.879     raeburn  7262: table.LC_innerpickbox,
1.507     raeburn  7263: table.LC_nested {
1.803     bisitz   7264:   border: none;
1.589     raeburn  7265:   border-collapse: collapse;
1.803     bisitz   7266:   border-spacing: 0;
1.507     raeburn  7267:   width: 100%;
                   7268: }
1.795     www      7269: 
1.911     bisitz   7270: table.LC_data_table tr th,
                   7271: table.LC_calendar tr th,
1.879     raeburn  7272: table.LC_prior_tries tr th,
                   7273: table.LC_innerpickbox tr th {
1.349     albertel 7274:   font-weight: bold;
                   7275:   background-color: $data_table_head;
1.801     tempelho 7276:   color:$fontmenu;
1.701     harmsja  7277:   font-size:90%;
1.347     albertel 7278: }
1.795     www      7279: 
1.879     raeburn  7280: table.LC_innerpickbox tr th,
                   7281: table.LC_innerpickbox tr td {
                   7282:   vertical-align: top;
                   7283: }
                   7284: 
1.711     raeburn  7285: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7286:   background-color: #CCCCCC;
1.711     raeburn  7287:   font-weight: bold;
                   7288:   text-align: left;
                   7289: }
1.795     www      7290: 
1.912     bisitz   7291: table.LC_data_table tr.LC_odd_row > td {
                   7292:   background-color: $data_table_light;
                   7293:   padding: 2px;
                   7294:   vertical-align: top;
                   7295: }
                   7296: 
1.809     bisitz   7297: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7298:   background-color: $data_table_light;
1.912     bisitz   7299:   vertical-align: top;
                   7300: }
                   7301: 
                   7302: table.LC_data_table tr.LC_even_row > td {
                   7303:   background-color: $data_table_dark;
1.425     albertel 7304:   padding: 2px;
1.900     bisitz   7305:   vertical-align: top;
1.347     albertel 7306: }
1.795     www      7307: 
1.809     bisitz   7308: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7309:   background-color: $data_table_dark;
1.900     bisitz   7310:   vertical-align: top;
1.347     albertel 7311: }
1.795     www      7312: 
1.425     albertel 7313: table.LC_data_table tr.LC_data_table_highlight td {
                   7314:   background-color: $data_table_darker;
                   7315: }
1.795     www      7316: 
1.639     raeburn  7317: table.LC_data_table tr td.LC_leftcol_header {
                   7318:   background-color: $data_table_head;
                   7319:   font-weight: bold;
                   7320: }
1.795     www      7321: 
1.451     albertel 7322: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7323: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7324:   font-weight: bold;
                   7325:   font-style: italic;
                   7326:   text-align: center;
                   7327:   padding: 8px;
1.347     albertel 7328: }
1.795     www      7329: 
1.1114    raeburn  7330: table.LC_data_table tr.LC_empty_row td,
                   7331: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7332:   background-color: $sidebg;
                   7333: }
                   7334: 
                   7335: table.LC_nested tr.LC_empty_row td {
                   7336:   background-color: #FFFFFF;
                   7337: }
                   7338: 
1.890     droeschl 7339: table.LC_caption {
                   7340: }
                   7341: 
1.507     raeburn  7342: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7343:   padding: 4ex
                   7344: }
1.795     www      7345: 
1.507     raeburn  7346: table.LC_nested_outer tr th {
                   7347:   font-weight: bold;
1.801     tempelho 7348:   color:$fontmenu;
1.507     raeburn  7349:   background-color: $data_table_head;
1.701     harmsja  7350:   font-size: small;
1.507     raeburn  7351:   border-bottom: 1px solid #000000;
                   7352: }
1.795     www      7353: 
1.507     raeburn  7354: table.LC_nested_outer tr td.LC_subheader {
                   7355:   background-color: $data_table_head;
                   7356:   font-weight: bold;
                   7357:   font-size: small;
                   7358:   border-bottom: 1px solid #000000;
                   7359:   text-align: right;
1.451     albertel 7360: }
1.795     www      7361: 
1.507     raeburn  7362: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7363:   background-color: #CCCCCC;
1.451     albertel 7364:   font-weight: bold;
                   7365:   font-size: small;
1.507     raeburn  7366:   text-align: center;
                   7367: }
1.795     www      7368: 
1.589     raeburn  7369: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7370: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7371:   text-align: left;
1.451     albertel 7372: }
1.795     www      7373: 
1.507     raeburn  7374: table.LC_nested td {
1.735     bisitz   7375:   background-color: #FFFFFF;
1.451     albertel 7376:   font-size: small;
1.507     raeburn  7377: }
1.795     www      7378: 
1.507     raeburn  7379: table.LC_nested_outer tr th.LC_right_item,
                   7380: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7381: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7382: table.LC_nested tr td.LC_right_item {
1.451     albertel 7383:   text-align: right;
                   7384: }
                   7385: 
1.507     raeburn  7386: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7387:   background-color: #EEEEEE;
1.451     albertel 7388: }
                   7389: 
1.473     raeburn  7390: table.LC_createuser {
                   7391: }
                   7392: 
                   7393: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7394:   font-size: small;
1.473     raeburn  7395: }
                   7396: 
                   7397: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7398:   background-color: #CCCCCC;
1.473     raeburn  7399:   font-weight: bold;
                   7400:   text-align: center;
                   7401: }
                   7402: 
1.349     albertel 7403: table.LC_calendar {
                   7404:   border: 1px solid #000000;
                   7405:   border-collapse: collapse;
1.917     raeburn  7406:   width: 98%;
1.349     albertel 7407: }
1.795     www      7408: 
1.349     albertel 7409: table.LC_calendar_pickdate {
                   7410:   font-size: xx-small;
                   7411: }
1.795     www      7412: 
1.349     albertel 7413: table.LC_calendar tr td {
                   7414:   border: 1px solid #000000;
                   7415:   vertical-align: top;
1.917     raeburn  7416:   width: 14%;
1.349     albertel 7417: }
1.795     www      7418: 
1.349     albertel 7419: table.LC_calendar tr td.LC_calendar_day_empty {
                   7420:   background-color: $data_table_dark;
                   7421: }
1.795     www      7422: 
1.779     bisitz   7423: table.LC_calendar tr td.LC_calendar_day_current {
                   7424:   background-color: $data_table_highlight;
1.777     tempelho 7425: }
1.795     www      7426: 
1.938     bisitz   7427: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7428:   background-color: $mail_new;
                   7429: }
1.795     www      7430: 
1.938     bisitz   7431: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7432:   background-color: $mail_new_hover;
                   7433: }
1.795     www      7434: 
1.938     bisitz   7435: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7436:   background-color: $mail_read;
                   7437: }
1.795     www      7438: 
1.938     bisitz   7439: /*
                   7440: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7441:   background-color: $mail_read_hover;
                   7442: }
1.938     bisitz   7443: */
1.795     www      7444: 
1.938     bisitz   7445: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7446:   background-color: $mail_replied;
                   7447: }
1.795     www      7448: 
1.938     bisitz   7449: /*
                   7450: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7451:   background-color: $mail_replied_hover;
                   7452: }
1.938     bisitz   7453: */
1.795     www      7454: 
1.938     bisitz   7455: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7456:   background-color: $mail_other;
                   7457: }
1.795     www      7458: 
1.938     bisitz   7459: /*
                   7460: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7461:   background-color: $mail_other_hover;
                   7462: }
1.938     bisitz   7463: */
1.494     raeburn  7464: 
1.777     tempelho 7465: table.LC_data_table tr > td.LC_browser_file,
                   7466: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7467:   background: #AAEE77;
1.389     albertel 7468: }
1.795     www      7469: 
1.777     tempelho 7470: table.LC_data_table tr > td.LC_browser_file_locked,
                   7471: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7472:   background: #FFAA99;
1.387     albertel 7473: }
1.795     www      7474: 
1.777     tempelho 7475: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7476:   background: #888888;
1.779     bisitz   7477: }
1.795     www      7478: 
1.777     tempelho 7479: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7480: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7481:   background: #F8F866;
1.777     tempelho 7482: }
1.795     www      7483: 
1.696     bisitz   7484: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7485:   background: #E0E8FF;
1.387     albertel 7486: }
1.696     bisitz   7487: 
1.707     bisitz   7488: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7489:   /* background: #77FF77; */
1.707     bisitz   7490: }
1.795     www      7491: 
1.707     bisitz   7492: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7493:   border-right: 8px solid #FFFF77;
1.707     bisitz   7494: }
1.795     www      7495: 
1.707     bisitz   7496: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7497:   border-right: 8px solid #FFAA77;
1.707     bisitz   7498: }
1.795     www      7499: 
1.707     bisitz   7500: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7501:   border-right: 8px solid #FF7777;
1.707     bisitz   7502: }
1.795     www      7503: 
1.707     bisitz   7504: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7505:   border-right: 8px solid #AAFF77;
1.707     bisitz   7506: }
1.795     www      7507: 
1.707     bisitz   7508: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7509:   border-right: 8px solid #11CC55;
1.707     bisitz   7510: }
                   7511: 
1.388     albertel 7512: span.LC_current_location {
1.701     harmsja  7513:   font-size:larger;
1.388     albertel 7514:   background: $pgbg;
                   7515: }
1.387     albertel 7516: 
1.1029    www      7517: span.LC_current_nav_location {
                   7518:   font-weight:bold;
                   7519:   background: $sidebg;
                   7520: }
                   7521: 
1.395     albertel 7522: span.LC_parm_menu_item {
                   7523:   font-size: larger;
                   7524: }
1.795     www      7525: 
1.395     albertel 7526: span.LC_parm_scope_all {
                   7527:   color: red;
                   7528: }
1.795     www      7529: 
1.395     albertel 7530: span.LC_parm_scope_folder {
                   7531:   color: green;
                   7532: }
1.795     www      7533: 
1.395     albertel 7534: span.LC_parm_scope_resource {
                   7535:   color: orange;
                   7536: }
1.795     www      7537: 
1.395     albertel 7538: span.LC_parm_part {
                   7539:   color: blue;
                   7540: }
1.795     www      7541: 
1.911     bisitz   7542: span.LC_parm_folder,
                   7543: span.LC_parm_symb {
1.395     albertel 7544:   font-size: x-small;
                   7545:   font-family: $mono;
                   7546:   color: #AAAAAA;
                   7547: }
                   7548: 
1.977     bisitz   7549: ul.LC_parm_parmlist li {
                   7550:   display: inline-block;
                   7551:   padding: 0.3em 0.8em;
                   7552:   vertical-align: top;
                   7553:   width: 150px;
                   7554:   border-top:1px solid $lg_border_color;
                   7555: }
                   7556: 
1.795     www      7557: td.LC_parm_overview_level_menu,
                   7558: td.LC_parm_overview_map_menu,
                   7559: td.LC_parm_overview_parm_selectors,
                   7560: td.LC_parm_overview_restrictions  {
1.396     albertel 7561:   border: 1px solid black;
                   7562:   border-collapse: collapse;
                   7563: }
1.795     www      7564: 
1.1285    raeburn  7565: span.LC_parm_recursive,
                   7566: td.LC_parm_recursive {
                   7567:   font-weight: bold;
                   7568:   font-size: smaller;
                   7569: }
                   7570: 
1.396     albertel 7571: table.LC_parm_overview_restrictions td {
                   7572:   border-width: 1px 4px 1px 4px;
                   7573:   border-style: solid;
                   7574:   border-color: $pgbg;
                   7575:   text-align: center;
                   7576: }
1.795     www      7577: 
1.396     albertel 7578: table.LC_parm_overview_restrictions th {
                   7579:   background: $tabbg;
                   7580:   border-width: 1px 4px 1px 4px;
                   7581:   border-style: solid;
                   7582:   border-color: $pgbg;
                   7583: }
1.795     www      7584: 
1.398     albertel 7585: table#LC_helpmenu {
1.803     bisitz   7586:   border: none;
1.398     albertel 7587:   height: 55px;
1.803     bisitz   7588:   border-spacing: 0;
1.398     albertel 7589: }
                   7590: 
                   7591: table#LC_helpmenu fieldset legend {
                   7592:   font-size: larger;
                   7593: }
1.795     www      7594: 
1.397     albertel 7595: table#LC_helpmenu_links {
                   7596:   width: 100%;
                   7597:   border: 1px solid black;
                   7598:   background: $pgbg;
1.803     bisitz   7599:   padding: 0;
1.397     albertel 7600:   border-spacing: 1px;
                   7601: }
1.795     www      7602: 
1.397     albertel 7603: table#LC_helpmenu_links tr td {
                   7604:   padding: 1px;
                   7605:   background: $tabbg;
1.399     albertel 7606:   text-align: center;
                   7607:   font-weight: bold;
1.397     albertel 7608: }
1.396     albertel 7609: 
1.795     www      7610: table#LC_helpmenu_links a:link,
                   7611: table#LC_helpmenu_links a:visited,
1.397     albertel 7612: table#LC_helpmenu_links a:active {
                   7613:   text-decoration: none;
                   7614:   color: $font;
                   7615: }
1.795     www      7616: 
1.397     albertel 7617: table#LC_helpmenu_links a:hover {
                   7618:   text-decoration: underline;
                   7619:   color: $vlink;
                   7620: }
1.396     albertel 7621: 
1.417     albertel 7622: .LC_chrt_popup_exists {
                   7623:   border: 1px solid #339933;
                   7624:   margin: -1px;
                   7625: }
1.795     www      7626: 
1.417     albertel 7627: .LC_chrt_popup_up {
                   7628:   border: 1px solid yellow;
                   7629:   margin: -1px;
                   7630: }
1.795     www      7631: 
1.417     albertel 7632: .LC_chrt_popup {
                   7633:   border: 1px solid #8888FF;
                   7634:   background: #CCCCFF;
                   7635: }
1.795     www      7636: 
1.421     albertel 7637: table.LC_pick_box {
                   7638:   border-collapse: separate;
                   7639:   background: white;
                   7640:   border: 1px solid black;
                   7641:   border-spacing: 1px;
                   7642: }
1.795     www      7643: 
1.421     albertel 7644: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7645:   background: $sidebg;
1.421     albertel 7646:   font-weight: bold;
1.900     bisitz   7647:   text-align: left;
1.740     bisitz   7648:   vertical-align: top;
1.421     albertel 7649:   width: 184px;
                   7650:   padding: 8px;
                   7651: }
1.795     www      7652: 
1.579     raeburn  7653: table.LC_pick_box td.LC_pick_box_value {
                   7654:   text-align: left;
                   7655:   padding: 8px;
                   7656: }
1.795     www      7657: 
1.579     raeburn  7658: table.LC_pick_box td.LC_pick_box_select {
                   7659:   text-align: left;
                   7660:   padding: 8px;
                   7661: }
1.795     www      7662: 
1.424     albertel 7663: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7664:   padding: 0;
1.421     albertel 7665:   height: 1px;
                   7666:   background: black;
                   7667: }
1.795     www      7668: 
1.421     albertel 7669: table.LC_pick_box td.LC_pick_box_submit {
                   7670:   text-align: right;
                   7671: }
1.795     www      7672: 
1.579     raeburn  7673: table.LC_pick_box td.LC_evenrow_value {
                   7674:   text-align: left;
                   7675:   padding: 8px;
                   7676:   background-color: $data_table_light;
                   7677: }
1.795     www      7678: 
1.579     raeburn  7679: table.LC_pick_box td.LC_oddrow_value {
                   7680:   text-align: left;
                   7681:   padding: 8px;
                   7682:   background-color: $data_table_light;
                   7683: }
1.795     www      7684: 
1.579     raeburn  7685: span.LC_helpform_receipt_cat {
                   7686:   font-weight: bold;
                   7687: }
1.795     www      7688: 
1.424     albertel 7689: table.LC_group_priv_box {
                   7690:   background: white;
                   7691:   border: 1px solid black;
                   7692:   border-spacing: 1px;
                   7693: }
1.795     www      7694: 
1.424     albertel 7695: table.LC_group_priv_box td.LC_pick_box_title {
                   7696:   background: $tabbg;
                   7697:   font-weight: bold;
                   7698:   text-align: right;
                   7699:   width: 184px;
                   7700: }
1.795     www      7701: 
1.424     albertel 7702: table.LC_group_priv_box td.LC_groups_fixed {
                   7703:   background: $data_table_light;
                   7704:   text-align: center;
                   7705: }
1.795     www      7706: 
1.424     albertel 7707: table.LC_group_priv_box td.LC_groups_optional {
                   7708:   background: $data_table_dark;
                   7709:   text-align: center;
                   7710: }
1.795     www      7711: 
1.424     albertel 7712: table.LC_group_priv_box td.LC_groups_functionality {
                   7713:   background: $data_table_darker;
                   7714:   text-align: center;
                   7715:   font-weight: bold;
                   7716: }
1.795     www      7717: 
1.424     albertel 7718: table.LC_group_priv td {
                   7719:   text-align: left;
1.803     bisitz   7720:   padding: 0;
1.424     albertel 7721: }
                   7722: 
                   7723: .LC_navbuttons {
                   7724:   margin: 2ex 0ex 2ex 0ex;
                   7725: }
1.795     www      7726: 
1.423     albertel 7727: .LC_topic_bar {
                   7728:   font-weight: bold;
                   7729:   background: $tabbg;
1.918     wenzelju 7730:   margin: 1em 0em 1em 2em;
1.805     bisitz   7731:   padding: 3px;
1.918     wenzelju 7732:   font-size: 1.2em;
1.423     albertel 7733: }
1.795     www      7734: 
1.423     albertel 7735: .LC_topic_bar span {
1.918     wenzelju 7736:   left: 0.5em;
                   7737:   position: absolute;
1.423     albertel 7738:   vertical-align: middle;
1.918     wenzelju 7739:   font-size: 1.2em;
1.423     albertel 7740: }
1.795     www      7741: 
1.423     albertel 7742: table.LC_course_group_status {
                   7743:   margin: 20px;
                   7744: }
1.795     www      7745: 
1.423     albertel 7746: table.LC_status_selector td {
                   7747:   vertical-align: top;
                   7748:   text-align: center;
1.424     albertel 7749:   padding: 4px;
                   7750: }
1.795     www      7751: 
1.599     albertel 7752: div.LC_feedback_link {
1.616     albertel 7753:   clear: both;
1.829     kalberla 7754:   background: $sidebg;
1.779     bisitz   7755:   width: 100%;
1.829     kalberla 7756:   padding-bottom: 10px;
                   7757:   border: 1px $tabbg solid;
1.833     kalberla 7758:   height: 22px;
                   7759:   line-height: 22px;
                   7760:   padding-top: 5px;
                   7761: }
                   7762: 
                   7763: div.LC_feedback_link img {
                   7764:   height: 22px;
1.867     kalberla 7765:   vertical-align:middle;
1.829     kalberla 7766: }
                   7767: 
1.911     bisitz   7768: div.LC_feedback_link a {
1.829     kalberla 7769:   text-decoration: none;
1.489     raeburn  7770: }
1.795     www      7771: 
1.867     kalberla 7772: div.LC_comblock {
1.911     bisitz   7773:   display:inline;
1.867     kalberla 7774:   color:$font;
                   7775:   font-size:90%;
                   7776: }
                   7777: 
                   7778: div.LC_feedback_link div.LC_comblock {
                   7779:   padding-left:5px;
                   7780: }
                   7781: 
                   7782: div.LC_feedback_link div.LC_comblock a {
                   7783:   color:$font;
                   7784: }
                   7785: 
1.489     raeburn  7786: span.LC_feedback_link {
1.858     bisitz   7787:   /* background: $feedback_link_bg; */
1.599     albertel 7788:   font-size: larger;
                   7789: }
1.795     www      7790: 
1.599     albertel 7791: span.LC_message_link {
1.858     bisitz   7792:   /* background: $feedback_link_bg; */
1.599     albertel 7793:   font-size: larger;
                   7794:   position: absolute;
                   7795:   right: 1em;
1.489     raeburn  7796: }
1.421     albertel 7797: 
1.515     albertel 7798: table.LC_prior_tries {
1.524     albertel 7799:   border: 1px solid #000000;
                   7800:   border-collapse: separate;
                   7801:   border-spacing: 1px;
1.515     albertel 7802: }
1.523     albertel 7803: 
1.515     albertel 7804: table.LC_prior_tries td {
1.524     albertel 7805:   padding: 2px;
1.515     albertel 7806: }
1.523     albertel 7807: 
                   7808: .LC_answer_correct {
1.795     www      7809:   background: lightgreen;
                   7810:   color: darkgreen;
                   7811:   padding: 6px;
1.523     albertel 7812: }
1.795     www      7813: 
1.523     albertel 7814: .LC_answer_charged_try {
1.797     www      7815:   background: #FFAAAA;
1.795     www      7816:   color: darkred;
                   7817:   padding: 6px;
1.523     albertel 7818: }
1.795     www      7819: 
1.779     bisitz   7820: .LC_answer_not_charged_try,
1.523     albertel 7821: .LC_answer_no_grade,
                   7822: .LC_answer_late {
1.795     www      7823:   background: lightyellow;
1.523     albertel 7824:   color: black;
1.795     www      7825:   padding: 6px;
1.523     albertel 7826: }
1.795     www      7827: 
1.523     albertel 7828: .LC_answer_previous {
1.795     www      7829:   background: lightblue;
                   7830:   color: darkblue;
                   7831:   padding: 6px;
1.523     albertel 7832: }
1.795     www      7833: 
1.779     bisitz   7834: .LC_answer_no_message {
1.777     tempelho 7835:   background: #FFFFFF;
                   7836:   color: black;
1.795     www      7837:   padding: 6px;
1.779     bisitz   7838: }
1.795     www      7839: 
1.1334    raeburn  7840: .LC_answer_unknown,
                   7841: .LC_answer_warning {
1.779     bisitz   7842:   background: orange;
                   7843:   color: black;
1.795     www      7844:   padding: 6px;
1.777     tempelho 7845: }
1.795     www      7846: 
1.529     albertel 7847: span.LC_prior_numerical,
                   7848: span.LC_prior_string,
                   7849: span.LC_prior_custom,
                   7850: span.LC_prior_reaction,
                   7851: span.LC_prior_math {
1.925     bisitz   7852:   font-family: $mono;
1.523     albertel 7853:   white-space: pre;
                   7854: }
                   7855: 
1.525     albertel 7856: span.LC_prior_string {
1.925     bisitz   7857:   font-family: $mono;
1.525     albertel 7858:   white-space: pre;
                   7859: }
                   7860: 
1.523     albertel 7861: table.LC_prior_option {
                   7862:   width: 100%;
                   7863:   border-collapse: collapse;
                   7864: }
1.795     www      7865: 
1.911     bisitz   7866: table.LC_prior_rank,
1.795     www      7867: table.LC_prior_match {
1.528     albertel 7868:   border-collapse: collapse;
                   7869: }
1.795     www      7870: 
1.528     albertel 7871: table.LC_prior_option tr td,
                   7872: table.LC_prior_rank tr td,
                   7873: table.LC_prior_match tr td {
1.524     albertel 7874:   border: 1px solid #000000;
1.515     albertel 7875: }
                   7876: 
1.855     bisitz   7877: .LC_nobreak {
1.544     albertel 7878:   white-space: nowrap;
1.519     raeburn  7879: }
                   7880: 
1.576     raeburn  7881: span.LC_cusr_emph {
                   7882:   font-style: italic;
                   7883: }
                   7884: 
1.633     raeburn  7885: span.LC_cusr_subheading {
                   7886:   font-weight: normal;
                   7887:   font-size: 85%;
                   7888: }
                   7889: 
1.861     bisitz   7890: div.LC_docs_entry_move {
1.859     bisitz   7891:   border: 1px solid #BBBBBB;
1.545     albertel 7892:   background: #DDDDDD;
1.861     bisitz   7893:   width: 22px;
1.859     bisitz   7894:   padding: 1px;
                   7895:   margin: 0;
1.545     albertel 7896: }
                   7897: 
1.861     bisitz   7898: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7899: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7900:   font-size: x-small;
                   7901: }
1.795     www      7902: 
1.861     bisitz   7903: .LC_docs_entry_parameter {
                   7904:   white-space: nowrap;
                   7905: }
                   7906: 
1.544     albertel 7907: .LC_docs_copy {
1.545     albertel 7908:   color: #000099;
1.544     albertel 7909: }
1.795     www      7910: 
1.544     albertel 7911: .LC_docs_cut {
1.545     albertel 7912:   color: #550044;
1.544     albertel 7913: }
1.795     www      7914: 
1.544     albertel 7915: .LC_docs_rename {
1.545     albertel 7916:   color: #009900;
1.544     albertel 7917: }
1.795     www      7918: 
1.544     albertel 7919: .LC_docs_remove {
1.545     albertel 7920:   color: #990000;
                   7921: }
                   7922: 
1.1284    raeburn  7923: .LC_docs_alias {
                   7924:   color: #440055;  
                   7925: }
                   7926: 
1.1286    raeburn  7927: .LC_domprefs_email,
1.1284    raeburn  7928: .LC_docs_alias_name,
1.547     albertel 7929: .LC_docs_reinit_warn,
                   7930: .LC_docs_ext_edit {
                   7931:   font-size: x-small;
                   7932: }
                   7933: 
1.545     albertel 7934: table.LC_docs_adddocs td,
                   7935: table.LC_docs_adddocs th {
                   7936:   border: 1px solid #BBBBBB;
                   7937:   padding: 4px;
                   7938:   background: #DDDDDD;
1.543     albertel 7939: }
                   7940: 
1.584     albertel 7941: table.LC_sty_begin {
                   7942:   background: #BBFFBB;
                   7943: }
1.795     www      7944: 
1.584     albertel 7945: table.LC_sty_end {
                   7946:   background: #FFBBBB;
                   7947: }
                   7948: 
1.589     raeburn  7949: table.LC_double_column {
1.803     bisitz   7950:   border-width: 0;
1.589     raeburn  7951:   border-collapse: collapse;
                   7952:   width: 100%;
                   7953:   padding: 2px;
                   7954: }
                   7955: 
                   7956: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7957:   top: 2px;
1.589     raeburn  7958:   left: 2px;
                   7959:   width: 47%;
                   7960:   vertical-align: top;
                   7961: }
                   7962: 
                   7963: table.LC_double_column tr td.LC_right_col {
                   7964:   top: 2px;
1.779     bisitz   7965:   right: 2px;
1.589     raeburn  7966:   width: 47%;
                   7967:   vertical-align: top;
                   7968: }
                   7969: 
1.591     raeburn  7970: div.LC_left_float {
                   7971:   float: left;
                   7972:   padding-right: 5%;
1.597     albertel 7973:   padding-bottom: 4px;
1.591     raeburn  7974: }
                   7975: 
                   7976: div.LC_clear_float_header {
1.597     albertel 7977:   padding-bottom: 2px;
1.591     raeburn  7978: }
                   7979: 
                   7980: div.LC_clear_float_footer {
1.597     albertel 7981:   padding-top: 10px;
1.591     raeburn  7982:   clear: both;
                   7983: }
                   7984: 
1.597     albertel 7985: div.LC_grade_show_user {
1.941     bisitz   7986: /*  border-left: 5px solid $sidebg; */
                   7987:   border-top: 5px solid #000000;
                   7988:   margin: 50px 0 0 0;
1.936     bisitz   7989:   padding: 15px 0 5px 10px;
1.597     albertel 7990: }
1.795     www      7991: 
1.936     bisitz   7992: div.LC_grade_show_user_odd_row {
1.941     bisitz   7993: /*  border-left: 5px solid #000000; */
                   7994: }
                   7995: 
                   7996: div.LC_grade_show_user div.LC_Box {
                   7997:   margin-right: 50px;
1.597     albertel 7998: }
                   7999: 
                   8000: div.LC_grade_submissions,
                   8001: div.LC_grade_message_center,
1.936     bisitz   8002: div.LC_grade_info_links {
1.597     albertel 8003:   margin: 5px;
                   8004:   width: 99%;
                   8005:   background: #FFFFFF;
                   8006: }
1.795     www      8007: 
1.597     albertel 8008: div.LC_grade_submissions_header,
1.936     bisitz   8009: div.LC_grade_message_center_header {
1.705     tempelho 8010:   font-weight: bold;
                   8011:   font-size: large;
1.597     albertel 8012: }
1.795     www      8013: 
1.597     albertel 8014: div.LC_grade_submissions_body,
1.936     bisitz   8015: div.LC_grade_message_center_body {
1.597     albertel 8016:   border: 1px solid black;
                   8017:   width: 99%;
                   8018:   background: #FFFFFF;
                   8019: }
1.795     www      8020: 
1.613     albertel 8021: table.LC_scantron_action {
                   8022:   width: 100%;
                   8023: }
1.795     www      8024: 
1.613     albertel 8025: table.LC_scantron_action tr th {
1.698     harmsja  8026:   font-weight:bold;
                   8027:   font-style:normal;
1.613     albertel 8028: }
1.795     www      8029: 
1.779     bisitz   8030: .LC_edit_problem_header,
1.614     albertel 8031: div.LC_edit_problem_footer {
1.705     tempelho 8032:   font-weight: normal;
                   8033:   font-size:  medium;
1.602     albertel 8034:   margin: 2px;
1.1060    bisitz   8035:   background-color: $sidebg;
1.600     albertel 8036: }
1.795     www      8037: 
1.600     albertel 8038: div.LC_edit_problem_header,
1.602     albertel 8039: div.LC_edit_problem_header div,
1.614     albertel 8040: div.LC_edit_problem_footer,
                   8041: div.LC_edit_problem_footer div,
1.602     albertel 8042: div.LC_edit_problem_editxml_header,
                   8043: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8044:   z-index: 100;
1.600     albertel 8045: }
1.795     www      8046: 
1.600     albertel 8047: div.LC_edit_problem_header_title {
1.705     tempelho 8048:   font-weight: bold;
                   8049:   font-size: larger;
1.602     albertel 8050:   background: $tabbg;
                   8051:   padding: 3px;
1.1060    bisitz   8052:   margin: 0 0 5px 0;
1.602     albertel 8053: }
1.795     www      8054: 
1.602     albertel 8055: table.LC_edit_problem_header_title {
                   8056:   width: 100%;
1.600     albertel 8057:   background: $tabbg;
1.602     albertel 8058: }
                   8059: 
1.1205    golterma 8060: div.LC_edit_actionbar {
                   8061:     background-color: $sidebg;
1.1218    droeschl 8062:     margin: 0;
                   8063:     padding: 0;
                   8064:     line-height: 200%;
1.602     albertel 8065: }
1.795     www      8066: 
1.1218    droeschl 8067: div.LC_edit_actionbar div{
                   8068:     padding: 0;
                   8069:     margin: 0;
                   8070:     display: inline-block;
1.600     albertel 8071: }
1.795     www      8072: 
1.1124    bisitz   8073: .LC_edit_opt {
                   8074:   padding-left: 1em;
                   8075:   white-space: nowrap;
                   8076: }
                   8077: 
1.1152    golterma 8078: .LC_edit_problem_latexhelper{
                   8079:     text-align: right;
                   8080: }
                   8081: 
                   8082: #LC_edit_problem_colorful div{
                   8083:     margin-left: 40px;
                   8084: }
                   8085: 
1.1205    golterma 8086: #LC_edit_problem_codemirror div{
                   8087:     margin-left: 0px;
                   8088: }
                   8089: 
1.911     bisitz   8090: img.stift {
1.803     bisitz   8091:   border-width: 0;
                   8092:   vertical-align: middle;
1.677     riegler  8093: }
1.680     riegler  8094: 
1.923     bisitz   8095: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8096:   vertical-align: top;
1.777     tempelho 8097: }
1.795     www      8098: 
1.716     raeburn  8099: div.LC_createcourse {
1.911     bisitz   8100:   margin: 10px 10px 10px 10px;
1.716     raeburn  8101: }
                   8102: 
1.917     raeburn  8103: .LC_dccid {
1.1130    raeburn  8104:   float: right;
1.917     raeburn  8105:   margin: 0.2em 0 0 0;
                   8106:   padding: 0;
                   8107:   font-size: 90%;
                   8108:   display:none;
                   8109: }
                   8110: 
1.897     wenzelju 8111: ol.LC_primary_menu a:hover,
1.721     harmsja  8112: ol#LC_MenuBreadcrumbs a:hover,
                   8113: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8114: ul#LC_secondary_menu a:hover,
1.721     harmsja  8115: .LC_FormSectionClearButton input:hover
1.795     www      8116: ul.LC_TabContent   li:hover a {
1.952     onken    8117:   color:$button_hover;
1.911     bisitz   8118:   text-decoration:none;
1.693     droeschl 8119: }
                   8120: 
1.779     bisitz   8121: h1 {
1.911     bisitz   8122:   padding: 0;
                   8123:   line-height:130%;
1.693     droeschl 8124: }
1.698     harmsja  8125: 
1.911     bisitz   8126: h2,
                   8127: h3,
                   8128: h4,
                   8129: h5,
                   8130: h6 {
                   8131:   margin: 5px 0 5px 0;
                   8132:   padding: 0;
                   8133:   line-height:130%;
1.693     droeschl 8134: }
1.795     www      8135: 
                   8136: .LC_hcell {
1.911     bisitz   8137:   padding:3px 15px 3px 15px;
                   8138:   margin: 0;
                   8139:   background-color:$tabbg;
                   8140:   color:$fontmenu;
                   8141:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8142: }
1.795     www      8143: 
1.840     bisitz   8144: .LC_Box > .LC_hcell {
1.911     bisitz   8145:   margin: 0 -10px 10px -10px;
1.835     bisitz   8146: }
                   8147: 
1.721     harmsja  8148: .LC_noBorder {
1.911     bisitz   8149:   border: 0;
1.698     harmsja  8150: }
1.693     droeschl 8151: 
1.721     harmsja  8152: .LC_FormSectionClearButton input {
1.911     bisitz   8153:   background-color:transparent;
                   8154:   border: none;
                   8155:   cursor:pointer;
                   8156:   text-decoration:underline;
1.693     droeschl 8157: }
1.763     bisitz   8158: 
                   8159: .LC_help_open_topic {
1.911     bisitz   8160:   color: #FFFFFF;
                   8161:   background-color: #EEEEFF;
                   8162:   margin: 1px;
                   8163:   padding: 4px;
                   8164:   border: 1px solid #000033;
                   8165:   white-space: nowrap;
                   8166:   /* vertical-align: middle; */
1.759     neumanie 8167: }
1.693     droeschl 8168: 
1.911     bisitz   8169: dl,
                   8170: ul,
                   8171: div,
                   8172: fieldset {
                   8173:   margin: 10px 10px 10px 0;
                   8174:   /* overflow: hidden; */
1.693     droeschl 8175: }
1.795     www      8176: 
1.1404    raeburn  8177: fieldset#LC_selectuser {
                   8178:     margin: 0;
                   8179:     padding: 0;
                   8180: }
                   8181: 
1.1211    raeburn  8182: article.geogebraweb div {
                   8183:     margin: 0;
                   8184: }
                   8185: 
1.838     bisitz   8186: fieldset > legend {
1.911     bisitz   8187:   font-weight: bold;
                   8188:   padding: 0 5px 0 5px;
1.838     bisitz   8189: }
                   8190: 
1.813     bisitz   8191: #LC_nav_bar {
1.911     bisitz   8192:   float: left;
1.995     raeburn  8193:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8194:   margin: 0 0 2px 0;
1.807     droeschl 8195: }
                   8196: 
1.916     droeschl 8197: #LC_realm {
                   8198:   margin: 0.2em 0 0 0;
                   8199:   padding: 0;
                   8200:   font-weight: bold;
                   8201:   text-align: center;
1.995     raeburn  8202:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8203: }
                   8204: 
1.911     bisitz   8205: #LC_nav_bar em {
                   8206:   font-weight: bold;
                   8207:   font-style: normal;
1.807     droeschl 8208: }
                   8209: 
1.897     wenzelju 8210: ol.LC_primary_menu {
1.934     droeschl 8211:   margin: 0;
1.1076    raeburn  8212:   padding: 0;
1.807     droeschl 8213: }
                   8214: 
1.852     droeschl 8215: ol#LC_PathBreadcrumbs {
1.911     bisitz   8216:   margin: 0;
1.693     droeschl 8217: }
                   8218: 
1.897     wenzelju 8219: ol.LC_primary_menu li {
1.1076    raeburn  8220:   color: RGB(80, 80, 80);
                   8221:   vertical-align: middle;
                   8222:   text-align: left;
                   8223:   list-style: none;
1.1205    golterma 8224:   position: relative;
1.1076    raeburn  8225:   float: left;
1.1205    golterma 8226:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8227:   line-height: 1.5em;
1.1076    raeburn  8228: }
                   8229: 
1.1205    golterma 8230: ol.LC_primary_menu li a,
                   8231: ol.LC_primary_menu li p {
1.1076    raeburn  8232:   display: block;
                   8233:   margin: 0;
                   8234:   padding: 0 5px 0 10px;
                   8235:   text-decoration: none;
                   8236: }
                   8237: 
1.1205    golterma 8238: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8239:   display: inline-block;
                   8240:   width: 95%;
                   8241:   text-align: left;
                   8242: }
                   8243: 
                   8244: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8245:   display: inline-block;	
                   8246:   width: 5%;
                   8247:   float: right;
                   8248:   text-align: right;
                   8249:   font-size: 70%;
                   8250: }
                   8251: 
                   8252: ol.LC_primary_menu ul {
1.1076    raeburn  8253:   display: none;
1.1205    golterma 8254:   width: 15em;
1.1076    raeburn  8255:   background-color: $data_table_light;
1.1205    golterma 8256:   position: absolute;
                   8257:   top: 100%;
1.1076    raeburn  8258: }
                   8259: 
1.1205    golterma 8260: ol.LC_primary_menu ul ul {
                   8261:   left: 100%;
                   8262:   top: 0;
                   8263: }
                   8264: 
                   8265: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8266:   display: block;
                   8267:   position: absolute;
                   8268:   margin: 0;
                   8269:   padding: 0;
1.1078    raeburn  8270:   z-index: 2;
1.1076    raeburn  8271: }
                   8272: 
                   8273: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8274: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8275:   font-size: 90%;
1.911     bisitz   8276:   vertical-align: top;
1.1076    raeburn  8277:   float: none;
1.1079    raeburn  8278:   border-left: 1px solid black;
                   8279:   border-right: 1px solid black;
1.1205    golterma 8280: /* A dark bottom border to visualize different menu options; 
                   8281: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8282:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8283: }
                   8284: 
1.1205    golterma 8285: ol.LC_primary_menu li li p:hover {
                   8286:   color:$button_hover;
                   8287:   text-decoration:none;
                   8288:   background-color:$data_table_dark;
1.1076    raeburn  8289: }
                   8290: 
                   8291: ol.LC_primary_menu li li a:hover {
                   8292:    color:$button_hover;
                   8293:    background-color:$data_table_dark;
1.693     droeschl 8294: }
                   8295: 
1.1205    golterma 8296: /* Font-size equal to the size of the predecessors*/
                   8297: ol.LC_primary_menu li:hover li li {
                   8298:   font-size: 100%;
                   8299: }
                   8300: 
1.897     wenzelju 8301: ol.LC_primary_menu li img {
1.911     bisitz   8302:   vertical-align: bottom;
1.934     droeschl 8303:   height: 1.1em;
1.1077    raeburn  8304:   margin: 0.2em 0 0 0;
1.693     droeschl 8305: }
                   8306: 
1.897     wenzelju 8307: ol.LC_primary_menu a {
1.911     bisitz   8308:   color: RGB(80, 80, 80);
                   8309:   text-decoration: none;
1.693     droeschl 8310: }
1.795     www      8311: 
1.949     droeschl 8312: ol.LC_primary_menu a.LC_new_message {
                   8313:   font-weight:bold;
                   8314:   color: darkred;
                   8315: }
                   8316: 
1.975     raeburn  8317: ol.LC_docs_parameters {
                   8318:   margin-left: 0;
                   8319:   padding: 0;
                   8320:   list-style: none;
                   8321: }
                   8322: 
                   8323: ol.LC_docs_parameters li {
                   8324:   margin: 0;
                   8325:   padding-right: 20px;
                   8326:   display: inline;
                   8327: }
                   8328: 
1.976     raeburn  8329: ol.LC_docs_parameters li:before {
                   8330:   content: "\\002022 \\0020";
                   8331: }
                   8332: 
                   8333: li.LC_docs_parameters_title {
                   8334:   font-weight: bold;
                   8335: }
                   8336: 
                   8337: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8338:   content: "";
                   8339: }
                   8340: 
1.897     wenzelju 8341: ul#LC_secondary_menu {
1.1107    raeburn  8342:   clear: right;
1.911     bisitz   8343:   color: $fontmenu;
                   8344:   background: $tabbg;
                   8345:   list-style: none;
                   8346:   padding: 0;
                   8347:   margin: 0;
                   8348:   width: 100%;
1.995     raeburn  8349:   text-align: left;
1.1107    raeburn  8350:   float: left;
1.808     droeschl 8351: }
                   8352: 
1.897     wenzelju 8353: ul#LC_secondary_menu li {
1.911     bisitz   8354:   font-weight: bold;
                   8355:   line-height: 1.8em;
1.1107    raeburn  8356:   border-right: 1px solid black;
                   8357:   float: left;
                   8358: }
                   8359: 
                   8360: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8361:   background-color: $data_table_light;
                   8362: }
                   8363: 
                   8364: ul#LC_secondary_menu li a {
1.911     bisitz   8365:   padding: 0 0.8em;
1.1107    raeburn  8366: }
                   8367: 
                   8368: ul#LC_secondary_menu li ul {
                   8369:   display: none;
                   8370: }
                   8371: 
                   8372: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8373:   display: block;
                   8374:   position: absolute;
                   8375:   margin: 0;
                   8376:   padding: 0;
                   8377:   list-style:none;
                   8378:   float: none;
                   8379:   background-color: $data_table_light;
                   8380:   z-index: 2;
                   8381:   margin-left: -1px;
                   8382: }
                   8383: 
                   8384: ul#LC_secondary_menu li ul li {
                   8385:   font-size: 90%;
                   8386:   vertical-align: top;
                   8387:   border-left: 1px solid black;
1.911     bisitz   8388:   border-right: 1px solid black;
1.1119    raeburn  8389:   background-color: $data_table_light;
1.1107    raeburn  8390:   list-style:none;
                   8391:   float: none;
                   8392: }
                   8393: 
                   8394: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8395:   background-color: $data_table_dark;
1.807     droeschl 8396: }
                   8397: 
1.847     tempelho 8398: ul.LC_TabContent {
1.911     bisitz   8399:   display:block;
                   8400:   background: $sidebg;
                   8401:   border-bottom: solid 1px $lg_border_color;
                   8402:   list-style:none;
1.1020    raeburn  8403:   margin: -1px -10px 0 -10px;
1.911     bisitz   8404:   padding: 0;
1.693     droeschl 8405: }
                   8406: 
1.795     www      8407: ul.LC_TabContent li,
                   8408: ul.LC_TabContentBigger li {
1.911     bisitz   8409:   float:left;
1.741     harmsja  8410: }
1.795     www      8411: 
1.897     wenzelju 8412: ul#LC_secondary_menu li a {
1.911     bisitz   8413:   color: $fontmenu;
                   8414:   text-decoration: none;
1.693     droeschl 8415: }
1.795     www      8416: 
1.721     harmsja  8417: ul.LC_TabContent {
1.952     onken    8418:   min-height:20px;
1.721     harmsja  8419: }
1.795     www      8420: 
                   8421: ul.LC_TabContent li {
1.911     bisitz   8422:   vertical-align:middle;
1.959     onken    8423:   padding: 0 16px 0 10px;
1.911     bisitz   8424:   background-color:$tabbg;
                   8425:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8426:   border-left: solid 1px $font;
1.721     harmsja  8427: }
1.795     www      8428: 
1.847     tempelho 8429: ul.LC_TabContent .right {
1.911     bisitz   8430:   float:right;
1.847     tempelho 8431: }
                   8432: 
1.911     bisitz   8433: ul.LC_TabContent li a,
                   8434: ul.LC_TabContent li {
                   8435:   color:rgb(47,47,47);
                   8436:   text-decoration:none;
                   8437:   font-size:95%;
                   8438:   font-weight:bold;
1.952     onken    8439:   min-height:20px;
                   8440: }
                   8441: 
1.959     onken    8442: ul.LC_TabContent li a:hover,
                   8443: ul.LC_TabContent li a:focus {
1.952     onken    8444:   color: $button_hover;
1.959     onken    8445:   background:none;
                   8446:   outline:none;
1.952     onken    8447: }
                   8448: 
                   8449: ul.LC_TabContent li:hover {
                   8450:   color: $button_hover;
                   8451:   cursor:pointer;
1.721     harmsja  8452: }
1.795     www      8453: 
1.911     bisitz   8454: ul.LC_TabContent li.active {
1.952     onken    8455:   color: $font;
1.911     bisitz   8456:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8457:   border-bottom:solid 1px #FFFFFF;
                   8458:   cursor: default;
1.744     ehlerst  8459: }
1.795     www      8460: 
1.959     onken    8461: ul.LC_TabContent li.active a {
                   8462:   color:$font;
                   8463:   background:#FFFFFF;
                   8464:   outline: none;
                   8465: }
1.1047    raeburn  8466: 
                   8467: ul.LC_TabContent li.goback {
                   8468:   float: left;
                   8469:   border-left: none;
                   8470: }
                   8471: 
1.870     tempelho 8472: #maincoursedoc {
1.911     bisitz   8473:   clear:both;
1.870     tempelho 8474: }
                   8475: 
                   8476: ul.LC_TabContentBigger {
1.911     bisitz   8477:   display:block;
                   8478:   list-style:none;
                   8479:   padding: 0;
1.870     tempelho 8480: }
                   8481: 
1.795     www      8482: ul.LC_TabContentBigger li {
1.911     bisitz   8483:   vertical-align:bottom;
                   8484:   height: 30px;
                   8485:   font-size:110%;
                   8486:   font-weight:bold;
                   8487:   color: #737373;
1.841     tempelho 8488: }
                   8489: 
1.957     onken    8490: ul.LC_TabContentBigger li.active {
                   8491:   position: relative;
                   8492:   top: 1px;
                   8493: }
                   8494: 
1.870     tempelho 8495: ul.LC_TabContentBigger li a {
1.911     bisitz   8496:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8497:   height: 30px;
                   8498:   line-height: 30px;
                   8499:   text-align: center;
                   8500:   display: block;
                   8501:   text-decoration: none;
1.958     onken    8502:   outline: none;  
1.741     harmsja  8503: }
1.795     www      8504: 
1.870     tempelho 8505: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8506:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8507:   color:$font;
1.744     ehlerst  8508: }
1.795     www      8509: 
1.870     tempelho 8510: ul.LC_TabContentBigger li b {
1.911     bisitz   8511:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8512:   display: block;
                   8513:   float: left;
                   8514:   padding: 0 30px;
1.957     onken    8515:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8516: }
                   8517: 
1.956     onken    8518: ul.LC_TabContentBigger li:hover b {
                   8519:   color:$button_hover;
                   8520: }
                   8521: 
1.870     tempelho 8522: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8523:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8524:   color:$font;
1.957     onken    8525:   border: 0;
1.741     harmsja  8526: }
1.693     droeschl 8527: 
1.870     tempelho 8528: 
1.862     bisitz   8529: ul.LC_CourseBreadcrumbs {
                   8530:   background: $sidebg;
1.1020    raeburn  8531:   height: 2em;
1.862     bisitz   8532:   padding-left: 10px;
1.1020    raeburn  8533:   margin: 0;
1.862     bisitz   8534:   list-style-position: inside;
                   8535: }
                   8536: 
1.911     bisitz   8537: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8538: ol#LC_PathBreadcrumbs {
1.911     bisitz   8539:   padding-left: 10px;
                   8540:   margin: 0;
1.933     droeschl 8541:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8542: }
                   8543: 
1.911     bisitz   8544: ol#LC_MenuBreadcrumbs li,
                   8545: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8546: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8547:   display: inline;
1.933     droeschl 8548:   white-space: normal;  
1.693     droeschl 8549: }
                   8550: 
1.823     bisitz   8551: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8552: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8553:   text-decoration: none;
                   8554:   font-size:90%;
1.693     droeschl 8555: }
1.795     www      8556: 
1.969     droeschl 8557: ol#LC_MenuBreadcrumbs h1 {
                   8558:   display: inline;
                   8559:   font-size: 90%;
                   8560:   line-height: 2.5em;
                   8561:   margin: 0;
                   8562:   padding: 0;
                   8563: }
                   8564: 
1.795     www      8565: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8566:   text-decoration:none;
                   8567:   font-size:100%;
                   8568:   font-weight:bold;
1.693     droeschl 8569: }
1.795     www      8570: 
1.840     bisitz   8571: .LC_Box {
1.911     bisitz   8572:   border: solid 1px $lg_border_color;
                   8573:   padding: 0 10px 10px 10px;
1.746     neumanie 8574: }
1.795     www      8575: 
1.1020    raeburn  8576: .LC_DocsBox {
                   8577:   border: solid 1px $lg_border_color;
                   8578:   padding: 0 0 10px 10px;
                   8579: }
                   8580: 
1.795     www      8581: .LC_AboutMe_Image {
1.911     bisitz   8582:   float:left;
                   8583:   margin-right:10px;
1.747     neumanie 8584: }
1.795     www      8585: 
                   8586: .LC_Clear_AboutMe_Image {
1.911     bisitz   8587:   clear:left;
1.747     neumanie 8588: }
1.795     www      8589: 
1.721     harmsja  8590: dl.LC_ListStyleClean dt {
1.911     bisitz   8591:   padding-right: 5px;
                   8592:   display: table-header-group;
1.693     droeschl 8593: }
                   8594: 
1.721     harmsja  8595: dl.LC_ListStyleClean dd {
1.911     bisitz   8596:   display: table-row;
1.693     droeschl 8597: }
                   8598: 
1.721     harmsja  8599: .LC_ListStyleClean,
                   8600: .LC_ListStyleSimple,
                   8601: .LC_ListStyleNormal,
1.795     www      8602: .LC_ListStyleSpecial {
1.911     bisitz   8603:   /* display:block; */
                   8604:   list-style-position: inside;
                   8605:   list-style-type: none;
                   8606:   overflow: hidden;
                   8607:   padding: 0;
1.693     droeschl 8608: }
                   8609: 
1.721     harmsja  8610: .LC_ListStyleSimple li,
                   8611: .LC_ListStyleSimple dd,
                   8612: .LC_ListStyleNormal li,
                   8613: .LC_ListStyleNormal dd,
                   8614: .LC_ListStyleSpecial li,
1.795     www      8615: .LC_ListStyleSpecial dd {
1.911     bisitz   8616:   margin: 0;
                   8617:   padding: 5px 5px 5px 10px;
                   8618:   clear: both;
1.693     droeschl 8619: }
                   8620: 
1.721     harmsja  8621: .LC_ListStyleClean li,
                   8622: .LC_ListStyleClean dd {
1.911     bisitz   8623:   padding-top: 0;
                   8624:   padding-bottom: 0;
1.693     droeschl 8625: }
                   8626: 
1.721     harmsja  8627: .LC_ListStyleSimple dd,
1.795     www      8628: .LC_ListStyleSimple li {
1.911     bisitz   8629:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8630: }
                   8631: 
1.721     harmsja  8632: .LC_ListStyleSpecial li,
                   8633: .LC_ListStyleSpecial dd {
1.911     bisitz   8634:   list-style-type: none;
                   8635:   background-color: RGB(220, 220, 220);
                   8636:   margin-bottom: 4px;
1.693     droeschl 8637: }
                   8638: 
1.721     harmsja  8639: table.LC_SimpleTable {
1.911     bisitz   8640:   margin:5px;
                   8641:   border:solid 1px $lg_border_color;
1.795     www      8642: }
1.693     droeschl 8643: 
1.721     harmsja  8644: table.LC_SimpleTable tr {
1.911     bisitz   8645:   padding: 0;
                   8646:   border:solid 1px $lg_border_color;
1.693     droeschl 8647: }
1.795     www      8648: 
                   8649: table.LC_SimpleTable thead {
1.911     bisitz   8650:   background:rgb(220,220,220);
1.693     droeschl 8651: }
                   8652: 
1.721     harmsja  8653: div.LC_columnSection {
1.911     bisitz   8654:   display: block;
                   8655:   clear: both;
                   8656:   overflow: hidden;
                   8657:   margin: 0;
1.693     droeschl 8658: }
                   8659: 
1.721     harmsja  8660: div.LC_columnSection>* {
1.911     bisitz   8661:   float: left;
                   8662:   margin: 10px 20px 10px 0;
                   8663:   overflow:hidden;
1.693     droeschl 8664: }
1.721     harmsja  8665: 
1.795     www      8666: table em {
1.911     bisitz   8667:   font-weight: bold;
                   8668:   font-style: normal;
1.748     schulted 8669: }
1.795     www      8670: 
1.779     bisitz   8671: table.LC_tableBrowseRes,
1.795     www      8672: table.LC_tableOfContent {
1.911     bisitz   8673:   border:none;
                   8674:   border-spacing: 1px;
                   8675:   padding: 3px;
                   8676:   background-color: #FFFFFF;
                   8677:   font-size: 90%;
1.753     droeschl 8678: }
1.789     droeschl 8679: 
1.911     bisitz   8680: table.LC_tableOfContent {
                   8681:   border-collapse: collapse;
1.789     droeschl 8682: }
                   8683: 
1.771     droeschl 8684: table.LC_tableBrowseRes a,
1.768     schulted 8685: table.LC_tableOfContent a {
1.911     bisitz   8686:   background-color: transparent;
                   8687:   text-decoration: none;
1.753     droeschl 8688: }
                   8689: 
1.795     www      8690: table.LC_tableOfContent img {
1.911     bisitz   8691:   border: none;
                   8692:   height: 1.3em;
                   8693:   vertical-align: text-bottom;
                   8694:   margin-right: 0.3em;
1.753     droeschl 8695: }
1.757     schulted 8696: 
1.795     www      8697: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8698:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8699: }
                   8700: 
1.795     www      8701: a#LC_content_toolbar_everything {
1.911     bisitz   8702:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8703: }
                   8704: 
1.795     www      8705: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8706:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8707: }
                   8708: 
1.795     www      8709: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8710:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8711: }
                   8712: 
1.795     www      8713: a#LC_content_toolbar_changefolder {
1.911     bisitz   8714:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8715: }
                   8716: 
1.795     www      8717: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8718:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8719: }
                   8720: 
1.1043    raeburn  8721: a#LC_content_toolbar_edittoplevel {
                   8722:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8723: }
                   8724: 
1.1384    raeburn  8725: a#LC_content_toolbar_printout {
                   8726:   background-image:url(/res/adm/pages/printout.gif);
                   8727: }
                   8728: 
1.795     www      8729: ul#LC_toolbar li a:hover {
1.911     bisitz   8730:   background-position: bottom center;
1.757     schulted 8731: }
                   8732: 
1.795     www      8733: ul#LC_toolbar {
1.911     bisitz   8734:   padding: 0;
                   8735:   margin: 2px;
                   8736:   list-style:none;
                   8737:   position:relative;
                   8738:   background-color:white;
1.1082    raeburn  8739:   overflow: auto;
1.757     schulted 8740: }
                   8741: 
1.795     www      8742: ul#LC_toolbar li {
1.911     bisitz   8743:   border:1px solid white;
                   8744:   padding: 0;
                   8745:   margin: 0;
                   8746:   float: left;
                   8747:   display:inline;
                   8748:   vertical-align:middle;
1.1082    raeburn  8749:   white-space: nowrap;
1.911     bisitz   8750: }
1.757     schulted 8751: 
1.783     amueller 8752: 
1.795     www      8753: a.LC_toolbarItem {
1.911     bisitz   8754:   display:block;
                   8755:   padding: 0;
                   8756:   margin: 0;
                   8757:   height: 32px;
                   8758:   width: 32px;
                   8759:   color:white;
                   8760:   border: none;
                   8761:   background-repeat:no-repeat;
                   8762:   background-color:transparent;
1.757     schulted 8763: }
                   8764: 
1.915     droeschl 8765: ul.LC_funclist {
                   8766:     margin: 0;
                   8767:     padding: 0.5em 1em 0.5em 0;
                   8768: }
                   8769: 
1.933     droeschl 8770: ul.LC_funclist > li:first-child {
                   8771:     font-weight:bold; 
                   8772:     margin-left:0.8em;
                   8773: }
                   8774: 
1.915     droeschl 8775: ul.LC_funclist + ul.LC_funclist {
                   8776:     /* 
                   8777:        left border as a seperator if we have more than
                   8778:        one list 
                   8779:     */
                   8780:     border-left: 1px solid $sidebg;
                   8781:     /* 
                   8782:        this hides the left border behind the border of the 
                   8783:        outer box if element is wrapped to the next 'line' 
                   8784:     */
                   8785:     margin-left: -1px;
                   8786: }
                   8787: 
1.843     bisitz   8788: ul.LC_funclist li {
1.915     droeschl 8789:   display: inline;
1.782     bisitz   8790:   white-space: nowrap;
1.915     droeschl 8791:   margin: 0 0 0 25px;
                   8792:   line-height: 150%;
1.782     bisitz   8793: }
                   8794: 
1.974     wenzelju 8795: .LC_hidden {
                   8796:   display: none;
                   8797: }
                   8798: 
1.1030    www      8799: .LCmodal-overlay {
                   8800: 		position:fixed;
                   8801: 		top:0;
                   8802: 		right:0;
                   8803: 		bottom:0;
                   8804: 		left:0;
                   8805: 		height:100%;
                   8806: 		width:100%;
                   8807: 		margin:0;
                   8808: 		padding:0;
                   8809: 		background:#999;
                   8810: 		opacity:.75;
                   8811: 		filter: alpha(opacity=75);
                   8812: 		-moz-opacity: 0.75;
                   8813: 		z-index:101;
                   8814: }
                   8815: 
                   8816: * html .LCmodal-overlay {   
                   8817: 		position: absolute;
                   8818: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8819: }
                   8820: 
                   8821: .LCmodal-window {
                   8822: 		position:fixed;
                   8823: 		top:50%;
                   8824: 		left:50%;
                   8825: 		margin:0;
                   8826: 		padding:0;
                   8827: 		z-index:102;
                   8828: 	}
                   8829: 
                   8830: * html .LCmodal-window {
                   8831: 		position:absolute;
                   8832: }
                   8833: 
                   8834: .LCclose-window {
                   8835: 		position:absolute;
                   8836: 		width:32px;
                   8837: 		height:32px;
                   8838: 		right:8px;
                   8839: 		top:8px;
                   8840: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8841: 		text-indent:-99999px;
                   8842: 		overflow:hidden;
                   8843: 		cursor:pointer;
                   8844: }
                   8845: 
1.1369    raeburn  8846: .LCisDisabled {
                   8847:   cursor: not-allowed;
                   8848:   opacity: 0.5;
                   8849: }
                   8850: 
                   8851: a[aria-disabled="true"] {
                   8852:   color: currentColor;
                   8853:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8854:   pointer-events: none;
                   8855:   text-decoration: none;
                   8856: }
                   8857: 
1.1335    raeburn  8858: pre.LC_wordwrap {
                   8859:   white-space: pre-wrap;
                   8860:   white-space: -moz-pre-wrap;
                   8861:   white-space: -pre-wrap;
                   8862:   white-space: -o-pre-wrap;
                   8863:   word-wrap: break-word;
                   8864: }
                   8865: 
1.1100    raeburn  8866: /*
1.1231    damieng  8867:   styles used for response display
                   8868: */
                   8869: div.LC_radiofoil, div.LC_rankfoil {
                   8870:   margin: .5em 0em .5em 0em;
                   8871: }
                   8872: table.LC_itemgroup {
                   8873:   margin-top: 1em;
                   8874: }
                   8875: 
                   8876: /*
1.1100    raeburn  8877:   styles used by TTH when "Default set of options to pass to tth/m
                   8878:   when converting TeX" in course settings has been set
                   8879: 
                   8880:   option passed: -t
                   8881: 
                   8882: */
                   8883: 
                   8884: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8885: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8886: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8887: td div.norm {line-height:normal;}
                   8888: 
                   8889: /*
                   8890:   option passed -y3
                   8891: */
                   8892: 
                   8893: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8894: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8895: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8896: 
1.1230    damieng  8897: /*
                   8898:   sections with roles, for content only
                   8899: */
                   8900: section[class^="role-"] {
                   8901:   padding-left: 10px;
                   8902:   padding-right: 5px;
                   8903:   margin-top: 8px;
                   8904:   margin-bottom: 8px;
                   8905:   border: 1px solid #2A4;
                   8906:   border-radius: 5px;
                   8907:   box-shadow: 0px 1px 1px #BBB;
                   8908: }
                   8909: section[class^="role-"]>h1 {
                   8910:   position: relative;
                   8911:   margin: 0px;
                   8912:   padding-top: 10px;
                   8913:   padding-left: 40px;
                   8914: }
                   8915: section[class^="role-"]>h1:before {
                   8916:   position: absolute;
                   8917:   left: -5px;
                   8918:   top: 5px;
                   8919: }
                   8920: section.role-activity>h1:before {
                   8921:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8922: }
                   8923: section.role-advice>h1:before {
                   8924:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8925: }
                   8926: section.role-bibliography>h1:before {
                   8927:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8928: }
                   8929: section.role-citation>h1:before {
                   8930:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8931: }
                   8932: section.role-conclusion>h1:before {
                   8933:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8934: }
                   8935: section.role-definition>h1:before {
                   8936:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8937: }
                   8938: section.role-demonstration>h1:before {
                   8939:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8940: }
                   8941: section.role-example>h1:before {
                   8942:   content:url('/adm/daxe/images/section_icons/example.png');
                   8943: }
                   8944: section.role-explanation>h1:before {
                   8945:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8946: }
                   8947: section.role-introduction>h1:before {
                   8948:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8949: }
                   8950: section.role-method>h1:before {
                   8951:   content:url('/adm/daxe/images/section_icons/method.png');
                   8952: }
                   8953: section.role-more_information>h1:before {
                   8954:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8955: }
                   8956: section.role-objectives>h1:before {
                   8957:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8958: }
                   8959: section.role-prerequisites>h1:before {
                   8960:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8961: }
                   8962: section.role-remark>h1:before {
                   8963:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8964: }
                   8965: section.role-reminder>h1:before {
                   8966:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8967: }
                   8968: section.role-summary>h1:before {
                   8969:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8970: }
                   8971: section.role-syntax>h1:before {
                   8972:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8973: }
                   8974: section.role-warning>h1:before {
                   8975:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8976: }
                   8977: 
1.1269    raeburn  8978: #LC_minitab_header {
                   8979:   float:left;
                   8980:   width:100%;
                   8981:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8982:   font-size:93%;
                   8983:   line-height:normal;
                   8984:   margin: 0.5em 0 0.5em 0;
                   8985: }
                   8986: #LC_minitab_header ul {
                   8987:   margin:0;
                   8988:   padding:10px 10px 0;
                   8989:   list-style:none;
                   8990: }
                   8991: #LC_minitab_header li {
                   8992:   float:left;
                   8993:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8994:   margin:0;
                   8995:   padding:0 0 0 9px;
                   8996: }
                   8997: #LC_minitab_header a {
                   8998:   display:block;
                   8999:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9000:   padding:5px 15px 4px 6px;
                   9001: }
                   9002: #LC_minitab_header #LC_current_minitab {
                   9003:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9004: }
                   9005: #LC_minitab_header #LC_current_minitab a {
                   9006:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9007:   padding-bottom:5px;
                   9008: }
                   9009: 
                   9010: 
1.343     albertel 9011: END
                   9012: }
                   9013: 
1.306     albertel 9014: =pod
                   9015: 
                   9016: =item * &headtag()
                   9017: 
                   9018: Returns a uniform footer for LON-CAPA web pages.
                   9019: 
1.307     albertel 9020: Inputs: $title - optional title for the head
                   9021:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9022:         $args - optional arguments
1.319     albertel 9023:             force_register - if is true call registerurl so the remote is 
                   9024:                              informed
1.415     albertel 9025:             redirect       -> array ref of
                   9026:                                    1- seconds before redirect occurs
                   9027:                                    2- url to redirect to
                   9028:                                    3- whether the side effect should occur
1.315     albertel 9029:                            (side effect of setting 
                   9030:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9031:                                redirected to)
                   9032:                                    4- whether the redirect target should be
                   9033:                                       the opener of the current (pop-up)
                   9034:                                       window (side effect of setting
                   9035:                                       $env{'internal.head.to_opener'} to
                   9036:                                       1, if true.
1.1388    raeburn  9037:                                    5- whether encrypt check should be skipped
1.352     albertel 9038:             domain         -> force to color decorate a page for a specific
                   9039:                                domain
                   9040:             function       -> force usage of a specific rolish color scheme
                   9041:             bgcolor        -> override the default page bgcolor
1.460     albertel 9042:             no_auto_mt_title
                   9043:                            -> prevent &mt()ing the title arg
1.464     albertel 9044: 
1.306     albertel 9045: =cut
                   9046: 
                   9047: sub headtag {
1.313     albertel 9048:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9049:     
1.363     albertel 9050:     my $function = $args->{'function'} || &get_users_function();
                   9051:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9052:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9053:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9054:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9055: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9056: 		   #time(),
1.418     albertel 9057: 		   $env{'environment.color.timestamp'},
1.363     albertel 9058: 		   $function,$domain,$bgcolor);
                   9059: 
1.369     www      9060:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9061: 
1.308     albertel 9062:     my $result =
                   9063: 	'<head>'.
1.1160    raeburn  9064: 	&font_settings($args);
1.319     albertel 9065: 
1.1188    raeburn  9066:     my $inhibitprint;
                   9067:     if ($args->{'print_suppress'}) {
                   9068:         $inhibitprint = &print_suppression();
                   9069:     }
1.1064    raeburn  9070: 
1.461     albertel 9071:     if (!$args->{'frameset'}) {
                   9072: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9073:     }
1.962     droeschl 9074:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9075:         $result .= Apache::lonxml::display_title();
1.319     albertel 9076:     }
1.436     albertel 9077:     if (!$args->{'no_nav_bar'} 
                   9078: 	&& !$args->{'only_body'}
                   9079: 	&& !$args->{'frameset'}) {
1.1154    raeburn  9080: 	$result .= &help_menu_js($httphost);
1.1032    www      9081:         $result.=&modal_window();
1.1038    www      9082:         $result.=&togglebox_script();
1.1034    www      9083:         $result.=&wishlist_window();
1.1041    www      9084:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9085:     } else {
                   9086:         if ($args->{'add_modal'}) {
                   9087:            $result.=&modal_window();
                   9088:         }
                   9089:         if ($args->{'add_wishlist'}) {
                   9090:            $result.=&wishlist_window();
                   9091:         }
1.1038    www      9092:         if ($args->{'add_togglebox'}) {
                   9093:            $result.=&togglebox_script();
                   9094:         }
1.1041    www      9095:         if ($args->{'add_progressbar'}) {
                   9096:            $result.=&LCprogressbarUpdate_script();
                   9097:         }
1.436     albertel 9098:     }
1.314     albertel 9099:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9100: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9101:         if (!$skip_enc_check) {
                   9102:             $url = &Apache::lonenc::check_encrypt($url);
                   9103:         }
1.414     albertel 9104: 	if (!$inhibit_continue) {
                   9105: 	    $env{'internal.head.redirect'} = $url;
                   9106: 	}
1.1386    raeburn  9107: 	$result.=<<"ADDMETA";
1.313     albertel 9108: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9109: ADDMETA
                   9110:         if ($to_opener) {
                   9111:             $env{'internal.head.to_opener'} = 1;
                   9112:             my $dest = &js_escape($url);
                   9113:             my $timeout = int($time * 1000);
                   9114:             $result .=<<"ENDJS";
                   9115: <script type="text/javascript">
                   9116: // <![CDATA[
                   9117: function LC_To_Opener() {
                   9118:     var dest = '$dest';
                   9119:     if (dest != '') {
                   9120:         if (window.opener != null && !window.opener.closed) {
                   9121:             window.opener.location.href=dest;
                   9122:             window.close();
                   9123:         } else {
                   9124:             window.location.href=dest;
                   9125:         }
                   9126:     }
                   9127: }
                   9128: \$(document).ready(function () {
                   9129:     setTimeout('LC_To_Opener()',$timeout);
                   9130: });
                   9131: // ]]>
                   9132: </script>
                   9133: ENDJS
                   9134:         } else {
                   9135:             $result.=<<"ADDMETA";
1.344     albertel 9136: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9137: ADDMETA
1.1386    raeburn  9138:         }
1.1210    raeburn  9139:     } else {
                   9140:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9141:             my $requrl = $env{'request.uri'};
                   9142:             if ($requrl eq '') {
                   9143:                 $requrl = $ENV{'REQUEST_URI'};
                   9144:                 $requrl =~ s/\?.+$//;
                   9145:             }
                   9146:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9147:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9148:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9149:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9150:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9151:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9152:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9153:                     my ($offload,$offloadoth);
1.1210    raeburn  9154:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9155:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9156:                             $offload = 1;
1.1353    raeburn  9157:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9158:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9159:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9160:                                     $offloadoth = 1;
                   9161:                                     $dom_in_use = $env{'user.domain'};
                   9162:                                 }
                   9163:                             }
1.1340    raeburn  9164:                         }
                   9165:                     }
                   9166:                     unless ($offload) {
                   9167:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9168:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9169:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9170:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9171:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9172:                                         $offload = 1;
1.1352    raeburn  9173:                                         $offloadoth = 1;
1.1340    raeburn  9174:                                         $dom_in_use = $env{'user.domain'};
                   9175:                                     }
1.1210    raeburn  9176:                                 }
1.1340    raeburn  9177:                             }
                   9178:                         }
                   9179:                     }
                   9180:                     if ($offload) {
1.1358    raeburn  9181:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9182:                         if (($newserver eq '') && ($offloadoth)) {
                   9183:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9184:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9185:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9186:                             }
                   9187:                         }
1.1340    raeburn  9188:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9189:                             my $numsec = 5;
                   9190:                             my $timeout = $numsec * 1000;
                   9191:                             my ($newurl,$locknum,%locks,$msg);
                   9192:                             if ($env{'request.role.adv'}) {
                   9193:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9194:                             }
                   9195:                             my $disable_submit = 0;
                   9196:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9197:                                 $disable_submit = 1;
                   9198:                             }
                   9199:                             if ($locknum) {
                   9200:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9201:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9202:                                        join(", ",sort(values(%locks)))."\n";
                   9203:                                 if (&show_course()) {
                   9204:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9205:                                 } else {
                   9206:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9207:                                 }
1.1340    raeburn  9208:                             } else {
                   9209:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9210:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9211:                                 }
                   9212:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9213:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9214:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9215:                                     $newurl .= '&role='.$env{'request.role'};
                   9216:                                 }
                   9217:                                 if ($env{'request.symb'}) {
                   9218:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9219:                                     if ($shownsymb =~ m{^/enc/}) {
                   9220:                                         my $reqdmajor = 2;
                   9221:                                         my $reqdminor = 11;
                   9222:                                         my $reqdsubminor = 3;
                   9223:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9224:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9225:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9226:                                         if (($major eq '' && $minor eq '') ||
                   9227:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9228:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9229:                                              ($reqdsubminor > $subminor))))) {
                   9230:                                             undef($shownsymb);
                   9231:                                         }
1.1210    raeburn  9232:                                     }
1.1340    raeburn  9233:                                     if ($shownsymb) {
                   9234:                                         &js_escape(\$shownsymb);
                   9235:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9236:                                     }
1.1340    raeburn  9237:                                 } else {
                   9238:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9239:                                     &js_escape(\$shownurl);
                   9240:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9241:                                 }
1.1340    raeburn  9242:                             }
                   9243:                             &js_escape(\$msg);
                   9244:                             $result.=<<OFFLOAD
1.1210    raeburn  9245: <meta http-equiv="pragma" content="no-cache" />
                   9246: <script type="text/javascript">
1.1215    raeburn  9247: // <![CDATA[
1.1210    raeburn  9248: function LC_Offload_Now() {
                   9249:     var dest = "$newurl";
                   9250:     if (dest != '') {
                   9251:         window.location.href="$newurl";
                   9252:     }
                   9253: }
1.1214    raeburn  9254: \$(document).ready(function () {
                   9255:     window.alert('$msg');
                   9256:     if ($disable_submit) {
1.1210    raeburn  9257:         \$(".LC_hwk_submit").prop("disabled", true);
                   9258:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9259:     }
                   9260:     setTimeout('LC_Offload_Now()', $timeout);
                   9261: });
1.1215    raeburn  9262: // ]]>
1.1210    raeburn  9263: </script>
                   9264: OFFLOAD
                   9265:                         }
                   9266:                     }
                   9267:                 }
                   9268:             }
                   9269:         }
1.313     albertel 9270:     }
1.306     albertel 9271:     if (!defined($title)) {
                   9272: 	$title = 'The LearningOnline Network with CAPA';
                   9273:     }
1.460     albertel 9274:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9275:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9276: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9277:     if (!$args->{'frameset'}) {
                   9278:         $result .= ' /';
                   9279:     }
                   9280:     $result .= '>' 
1.1064    raeburn  9281:         .$inhibitprint
1.414     albertel 9282: 	.$head_extra;
1.1242    raeburn  9283:     my $clientmobile;
                   9284:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9285:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9286:     } else {
                   9287:         $clientmobile = $env{'browser.mobile'};
                   9288:     }
                   9289:     if ($clientmobile) {
1.1137    raeburn  9290:         $result .= '
                   9291: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9292: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9293:     }
1.1278    raeburn  9294:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9295:     return $result.'</head>';
1.306     albertel 9296: }
                   9297: 
                   9298: =pod
                   9299: 
1.340     albertel 9300: =item * &font_settings()
                   9301: 
                   9302: Returns neccessary <meta> to set the proper encoding
                   9303: 
1.1160    raeburn  9304: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9305: 
                   9306: =cut
                   9307: 
                   9308: sub font_settings {
1.1160    raeburn  9309:     my ($args) = @_;
1.340     albertel 9310:     my $headerstring='';
1.1160    raeburn  9311:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9312:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9313:         $headerstring.=
                   9314:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9315:         if (!$args->{'frameset'}) {
                   9316: 	    $headerstring.= ' /';
                   9317:         }
                   9318: 	$headerstring .= '>'."\n";
1.340     albertel 9319:     }
                   9320:     return $headerstring;
                   9321: }
                   9322: 
1.341     albertel 9323: =pod
                   9324: 
1.1064    raeburn  9325: =item * &print_suppression()
                   9326: 
                   9327: In course context returns css which causes the body to be blank when media="print",
                   9328: if printout generation is unavailable for the current resource.
                   9329: 
                   9330: This could be because:
                   9331: 
                   9332: (a) printstartdate is in the future
                   9333: 
                   9334: (b) printenddate is in the past
                   9335: 
                   9336: (c) there is an active exam block with "printout"
                   9337: functionality blocked
                   9338: 
                   9339: Users with pav, pfo or evb privileges are exempt.
                   9340: 
                   9341: Inputs: none
                   9342: 
                   9343: =cut
                   9344: 
                   9345: 
                   9346: sub print_suppression {
                   9347:     my $noprint;
                   9348:     if ($env{'request.course.id'}) {
                   9349:         my $scope = $env{'request.course.id'};
                   9350:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9351:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9352:             return;
                   9353:         }
                   9354:         if ($env{'request.course.sec'} ne '') {
                   9355:             $scope .= "/$env{'request.course.sec'}";
                   9356:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9357:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9358:                 return;
1.1064    raeburn  9359:             }
                   9360:         }
                   9361:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9362:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9363:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9364:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9365:         if ($blocked) {
                   9366:             my $checkrole = "cm./$cdom/$cnum";
                   9367:             if ($env{'request.course.sec'} ne '') {
                   9368:                 $checkrole .= "/$env{'request.course.sec'}";
                   9369:             }
                   9370:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9371:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9372:                 $noprint = 1;
                   9373:             }
                   9374:         }
                   9375:         unless ($noprint) {
                   9376:             my $symb = &Apache::lonnet::symbread();
                   9377:             if ($symb ne '') {
                   9378:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9379:                 if (ref($navmap)) {
                   9380:                     my $res = $navmap->getBySymb($symb);
                   9381:                     if (ref($res)) {
                   9382:                         if (!$res->resprintable()) {
                   9383:                             $noprint = 1;
                   9384:                         }
                   9385:                     }
                   9386:                 }
                   9387:             }
                   9388:         }
                   9389:         if ($noprint) {
                   9390:             return <<"ENDSTYLE";
                   9391: <style type="text/css" media="print">
                   9392:     body { display:none }
                   9393: </style>
                   9394: ENDSTYLE
                   9395:         }
                   9396:     }
                   9397:     return;
                   9398: }
                   9399: 
                   9400: =pod
                   9401: 
1.341     albertel 9402: =item * &xml_begin()
                   9403: 
                   9404: Returns the needed doctype and <html>
                   9405: 
                   9406: Inputs: none
                   9407: 
                   9408: =cut
                   9409: 
                   9410: sub xml_begin {
1.1168    raeburn  9411:     my ($is_frameset) = @_;
1.341     albertel 9412:     my $output='';
                   9413: 
                   9414:     if ($env{'browser.mathml'}) {
                   9415: 	$output='<?xml version="1.0"?>'
                   9416:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9417: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9418:             
                   9419: #	    .'<!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">] >'
                   9420: 	    .'<!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">'
                   9421:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9422: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9423:     } elsif ($is_frameset) {
                   9424:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9425:                 '<html>'."\n";
1.341     albertel 9426:     } else {
1.1168    raeburn  9427: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9428:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9429:     }
                   9430:     return $output;
                   9431: }
1.340     albertel 9432: 
                   9433: =pod
                   9434: 
1.306     albertel 9435: =item * &start_page()
                   9436: 
                   9437: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9438: 
1.648     raeburn  9439: Inputs:
                   9440: 
                   9441: =over 4
                   9442: 
                   9443: $title - optional title for the page
                   9444: 
                   9445: $head_extra - optional extra HTML to incude inside the <head>
                   9446: 
                   9447: $args - additional optional args supported are:
                   9448: 
                   9449: =over 8
                   9450: 
                   9451:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9452:                                     arg on
1.814     bisitz   9453:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9454:              add_entries    -> additional attributes to add to the  <body>
                   9455:              domain         -> force to color decorate a page for a 
1.317     albertel 9456:                                     specific domain
1.648     raeburn  9457:              function       -> force usage of a specific rolish color
1.317     albertel 9458:                                     scheme
1.648     raeburn  9459:              redirect       -> see &headtag()
                   9460:              bgcolor        -> override the default page bg color
                   9461:              js_ready       -> return a string ready for being used in 
1.317     albertel 9462:                                     a javascript writeln
1.648     raeburn  9463:              html_encode    -> return a string ready for being used in 
1.320     albertel 9464:                                     a html attribute
1.648     raeburn  9465:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9466:                                     $forcereg arg
1.648     raeburn  9467:              frameset       -> if true will start with a <frameset>
1.330     albertel 9468:                                     rather than <body>
1.648     raeburn  9469:              skip_phases    -> hash ref of 
1.338     albertel 9470:                                     head -> skip the <html><head> generation
                   9471:                                     body -> skip all <body> generation
1.648     raeburn  9472:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9473:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9474:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9475:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9476:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9477:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9478:                                specific group
                   9479:              use_absolute   -> for request for external resource or syllabus, this
                   9480:                                will contain https://<hostname> if server uses
                   9481:                                https (as per hosts.tab), but request is for http
                   9482:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9483:              links_disabled -> Links in primary and secondary menus are disabled
                   9484:                                (Can enable them once page has loaded - see lonroles.pm
                   9485:                                for an example).
1.1380    raeburn  9486:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9487: 
1.648     raeburn  9488: =back
1.460     albertel 9489: 
1.648     raeburn  9490: =back
1.562     albertel 9491: 
1.306     albertel 9492: =cut
                   9493: 
                   9494: sub start_page {
1.309     albertel 9495:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9496:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9497: 
1.315     albertel 9498:     $env{'internal.start_page'}++;
1.1359    raeburn  9499:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9500: 
1.338     albertel 9501:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9502:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9503:     }
1.1316    raeburn  9504: 
                   9505:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9506:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9507:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9508:                 $args->{'no_primary_menu'} = 1;
                   9509:             }
                   9510:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9511:                 $args->{'no_inline_menu'} = 1;
                   9512:             }
                   9513:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9514:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9515:             }
                   9516:         } else {
                   9517:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9518:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9519:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9520:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9521:                     $args->{'no_primary_menu'} = 1;
                   9522:                 }
                   9523:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9524:                     $args->{'no_inline_menu'} = 1;
                   9525:                 }
                   9526:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9527:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9528:                 }
                   9529:             }
                   9530:         }
1.1316    raeburn  9531:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9532:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9533:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9534:     } elsif ($env{'request.course.id'}) {
                   9535:         my $expiretime=600;
                   9536:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9537:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9538:         }
                   9539:         my ($deeplinkmenu,$menuref);
                   9540:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9541:         if ($menucoll) {
                   9542:             if (ref($menuref) eq 'HASH') {
                   9543:                 %menu = %{$menuref};
                   9544:             }
                   9545:             if ($menu{'top'} eq 'n') {
                   9546:                 $args->{'no_primary_menu'} = 1;
                   9547:             }
                   9548:             if ($menu{'inline'} eq 'n') {
                   9549:                 unless (&Apache::lonnet::allowed('opa')) {
                   9550:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9551:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9552:                     my $crstype = &course_type();
                   9553:                     my $now = time;
                   9554:                     my $ccrole;
                   9555:                     if ($crstype eq 'Community') {
                   9556:                         $ccrole = 'co';
                   9557:                     } else {
                   9558:                         $ccrole = 'cc';
                   9559:                     }
                   9560:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9561:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9562:                         if ((($start) && ($start<0)) ||
                   9563:                             (($end) && ($end<$now))  ||
                   9564:                             (($start) && ($now<$start))) {
                   9565:                             $args->{'no_inline_menu'} = 1;
                   9566:                         }
                   9567:                     } else {
                   9568:                         $args->{'no_inline_menu'} = 1;
                   9569:                     }
                   9570:                 }
                   9571:             }
                   9572:         }
1.1316    raeburn  9573:     }
1.1359    raeburn  9574: 
1.1385    raeburn  9575:     my $showncrumbs;
1.338     albertel 9576:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9577: 	if ($args->{'frameset'}) {
                   9578: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9579: 						$args->{'add_entries'});
                   9580: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9581:         } else {
                   9582:             $result .=
                   9583:                 &bodytag($title, 
                   9584:                          $args->{'function'},       $args->{'add_entries'},
                   9585:                          $args->{'only_body'},      $args->{'domain'},
                   9586:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9587:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9588:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9589:                          \%menu,\$showncrumbs);
1.831     bisitz   9590:         }
1.330     albertel 9591:     }
1.338     albertel 9592: 
1.315     albertel 9593:     if ($args->{'js_ready'}) {
1.713     kaisler  9594: 		$result = &js_ready($result);
1.315     albertel 9595:     }
1.320     albertel 9596:     if ($args->{'html_encode'}) {
1.713     kaisler  9597: 		$result = &html_encode($result);
                   9598:     }
                   9599: 
1.813     bisitz   9600:     # Preparation for new and consistent functionlist at top of screen
                   9601:     # if ($args->{'functionlist'}) {
                   9602:     #            $result .= &build_functionlist();
                   9603:     #}
                   9604: 
1.964     droeschl 9605:     # Don't add anything more if only_body wanted or in const space
                   9606:     return $result if    $args->{'only_body'} 
                   9607:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9608: 
                   9609:     #Breadcrumbs
1.758     kaisler  9610:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9611:         unless ($showncrumbs) {
1.758     kaisler  9612: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9613: 		#if any br links exists, add them to the breadcrumbs
                   9614: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9615: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9616: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9617: 			}
                   9618: 		}
1.1096    raeburn  9619:                 # if @advtools array contains items add then to the breadcrumbs
                   9620:                 if (@advtools > 0) {
                   9621:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9622:                 }
1.1272    raeburn  9623:                 my $menulink;
                   9624:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9625:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9626:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9627:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9628:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9629:                      (!$env{'request.role.adv'}))) {
                   9630:                     $menulink = 0;
                   9631:                 } else {
                   9632:                     undef($menulink);
                   9633:                 }
1.1385    raeburn  9634:                 my $linkprotout;
                   9635:                 if ($env{'request.deeplink.login'}) {
                   9636:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9637:                     if ($linkprotout) {
                   9638:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9639:                     }
                   9640:                 }
1.758     kaisler  9641: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9642: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9643: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9644:                 } else {
1.1272    raeburn  9645: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9646: 		}
1.1385    raeburn  9647:         }
1.320     albertel 9648:     }
1.315     albertel 9649:     return $result;
1.306     albertel 9650: }
                   9651: 
                   9652: sub end_page {
1.315     albertel 9653:     my ($args) = @_;
                   9654:     $env{'internal.end_page'}++;
1.330     albertel 9655:     my $result;
1.335     albertel 9656:     if ($args->{'discussion'}) {
                   9657: 	my ($target,$parser);
                   9658: 	if (ref($args->{'discussion'})) {
                   9659: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9660: 				$args->{'discussion'}{'parser'});
                   9661: 	}
                   9662: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9663:     }
1.330     albertel 9664:     if ($args->{'frameset'}) {
                   9665: 	$result .= '</frameset>';
                   9666:     } else {
1.635     raeburn  9667: 	$result .= &endbodytag($args);
1.330     albertel 9668:     }
1.1080    raeburn  9669:     unless ($args->{'notbody'}) {
                   9670:         $result .= "\n</html>";
                   9671:     }
1.330     albertel 9672: 
1.315     albertel 9673:     if ($args->{'js_ready'}) {
1.317     albertel 9674: 	$result = &js_ready($result);
1.315     albertel 9675:     }
1.335     albertel 9676: 
1.320     albertel 9677:     if ($args->{'html_encode'}) {
                   9678: 	$result = &html_encode($result);
                   9679:     }
1.335     albertel 9680: 
1.315     albertel 9681:     return $result;
                   9682: }
                   9683: 
1.1359    raeburn  9684: sub menucoll_in_effect {
                   9685:     my ($menucoll,$deeplinkmenu,%menu);
                   9686:     if ($env{'request.course.id'}) {
                   9687:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9688:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9689:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9690:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9691:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9692:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9693:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9694:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9695:                     if (ref($navmap)) {
                   9696:                         $deeplink = $navmap->get_mapparam(undef,
                   9697:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9698:                                                           '0.deeplink');
1.1370    raeburn  9699:                     } else {
                   9700:                         $check_login_symb = 1;
1.1362    raeburn  9701:                     }
                   9702:                 } else {
1.1370    raeburn  9703:                     my $symb = &Apache::lonnet::symbread();
                   9704:                     if ($symb) {
                   9705:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9706:                     } else {
                   9707:                         $check_login_symb = 1;
                   9708:                     }
1.1362    raeburn  9709:                 }
                   9710:             } else {
1.1370    raeburn  9711:                 $check_login_symb = 1;
                   9712:             }
                   9713:             if ($check_login_symb) {
1.1362    raeburn  9714:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9715:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9716:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9717:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9718:                     if (ref($navmap)) {
                   9719:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9720:                     }
                   9721:                 } else {
                   9722:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9723:                 }
                   9724:             }
1.1359    raeburn  9725:             if ($deeplink ne '') {
1.1378    raeburn  9726:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9727:                 if ($display =~ /^\d+$/) {
                   9728:                     $deeplinkmenu = 1;
                   9729:                     $menucoll = $display;
                   9730:                 }
                   9731:             }
                   9732:         }
                   9733:         if ($menucoll) {
                   9734:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9735:         }
                   9736:     }
                   9737:     return ($menucoll,$deeplinkmenu,\%menu);
                   9738: }
                   9739: 
1.1362    raeburn  9740: sub deeplink_login_symb {
                   9741:     my ($cnum,$cdom) = @_;
                   9742:     my $login_symb;
                   9743:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9744:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9745:     }
                   9746:     return $login_symb;
                   9747: }
                   9748: 
                   9749: sub symb_from_tinyurl {
                   9750:     my ($url,$cnum,$cdom) = @_;
                   9751:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9752:         my $key = $1;
                   9753:         my ($tinyurl,$login);
                   9754:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9755:         if (defined($cached)) {
                   9756:             $tinyurl = $result;
                   9757:         } else {
                   9758:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9759:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9760:             if ($currtiny{$key} ne '') {
                   9761:                 $tinyurl = $currtiny{$key};
                   9762:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9763:             }
1.1364    raeburn  9764:         }
                   9765:         if ($tinyurl ne '') {
                   9766:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9767:             if (wantarray) {
                   9768:                 return ($cnumreq,$symb);
                   9769:             } elsif ($cnumreq eq $cnum) {
                   9770:                 return $symb;
1.1362    raeburn  9771:             }
                   9772:         }
                   9773:     }
1.1364    raeburn  9774:     if (wantarray) {
                   9775:         return ();
                   9776:     } else {
                   9777:         return;
                   9778:     }
1.1362    raeburn  9779: }
                   9780: 
1.1405    raeburn  9781: sub usable_exttools {
                   9782:     my %tooltypes;
                   9783:     if ($env{'request.course.id'}) {
                   9784:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   9785:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   9786:                %tooltypes = (
                   9787:                              crs => 1,
                   9788:                              dom => 1,
                   9789:                             );
                   9790:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   9791:                $tooltypes{'crs'} = 1;
                   9792:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   9793:                $tooltypes{'dom'} = 1;
                   9794:            }
                   9795:         } else {
                   9796:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9797:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9798:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   9799:             if ($crstype eq '') {
                   9800:                 $crstype = 'course';
                   9801:             }
                   9802:             if ($crstype eq 'course') {
                   9803:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   9804:                     $crstype = 'official';
                   9805:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   9806:                     $crstype = 'textbook';
                   9807:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   9808:                     $crstype = 'lti';
                   9809:                 } else {
                   9810:                     $crstype = 'unofficial';
                   9811:                 }
                   9812:             }
                   9813:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   9814:             if ($domdefaults{$crstype.'domexttool'}) {
                   9815:                 $tooltypes{'dom'} = 1;
                   9816:             }
                   9817:             if ($domdefaults{$crstype.'exttool'}) {
                   9818:                 $tooltypes{'crs'} = 1;
                   9819:             }
                   9820:         }
                   9821:     }
                   9822:     return %tooltypes;
                   9823: }
                   9824: 
1.1034    www      9825: sub wishlist_window {
                   9826:     return(<<'ENDWISHLIST');
1.1046    raeburn  9827: <script type="text/javascript">
1.1034    www      9828: // <![CDATA[
                   9829: // <!-- BEGIN LON-CAPA Internal
                   9830: function set_wishlistlink(title, path) {
                   9831:     if (!title) {
                   9832:         title = document.title;
                   9833:         title = title.replace(/^LON-CAPA /,'');
                   9834:     }
1.1175    raeburn  9835:     title = encodeURIComponent(title);
1.1203    raeburn  9836:     title = title.replace("'","\\\'");
1.1034    www      9837:     if (!path) {
                   9838:         path = location.pathname;
                   9839:     }
1.1175    raeburn  9840:     path = encodeURIComponent(path);
1.1203    raeburn  9841:     path = path.replace("'","\\\'");
1.1034    www      9842:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9843:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9844: }
                   9845: // END LON-CAPA Internal -->
                   9846: // ]]>
                   9847: </script>
                   9848: ENDWISHLIST
                   9849: }
                   9850: 
1.1030    www      9851: sub modal_window {
                   9852:     return(<<'ENDMODAL');
1.1046    raeburn  9853: <script type="text/javascript">
1.1030    www      9854: // <![CDATA[
                   9855: // <!-- BEGIN LON-CAPA Internal
                   9856: var modalWindow = {
                   9857: 	parent:"body",
                   9858: 	windowId:null,
                   9859: 	content:null,
                   9860: 	width:null,
                   9861: 	height:null,
                   9862: 	close:function()
                   9863: 	{
                   9864: 	        $(".LCmodal-window").remove();
                   9865: 	        $(".LCmodal-overlay").remove();
                   9866: 	},
                   9867: 	open:function()
                   9868: 	{
                   9869: 		var modal = "";
                   9870: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9871: 		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;\">";
                   9872: 		modal += this.content;
                   9873: 		modal += "</div>";	
                   9874: 
                   9875: 		$(this.parent).append(modal);
                   9876: 
                   9877: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9878: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9879: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9880: 	}
                   9881: };
1.1140    raeburn  9882: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9883: 	{
1.1266    raeburn  9884:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9885: 		modalWindow.windowId = "myModal";
                   9886: 		modalWindow.width = width;
                   9887: 		modalWindow.height = height;
1.1196    raeburn  9888: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9889: 		modalWindow.open();
1.1208    raeburn  9890: 	};
1.1030    www      9891: // END LON-CAPA Internal -->
                   9892: // ]]>
                   9893: </script>
                   9894: ENDMODAL
                   9895: }
                   9896: 
                   9897: sub modal_link {
1.1140    raeburn  9898:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9899:     unless ($width) { $width=480; }
                   9900:     unless ($height) { $height=400; }
1.1031    www      9901:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9902:     unless ($transparency) { $transparency='true'; }
                   9903: 
1.1074    raeburn  9904:     my $target_attr;
                   9905:     if (defined($target)) {
                   9906:         $target_attr = 'target="'.$target.'"';
                   9907:     }
                   9908:     return <<"ENDLINK";
1.1336    raeburn  9909: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9910: ENDLINK
1.1030    www      9911: }
                   9912: 
1.1032    www      9913: sub modal_adhoc_script {
1.1365    raeburn  9914:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9915:     my $mathjax;
                   9916:     if ($possmathjax) {
                   9917:         $mathjax = <<'ENDJAX';
                   9918:                if (typeof MathJax == 'object') {
                   9919:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9920:                }
                   9921: ENDJAX
                   9922:     }
1.1032    www      9923:     return (<<ENDADHOC);
1.1046    raeburn  9924: <script type="text/javascript">
1.1032    www      9925: // <![CDATA[
                   9926:         var $funcname = function()
                   9927:         {
                   9928:                 modalWindow.windowId = "myModal";
                   9929:                 modalWindow.width = $width;
                   9930:                 modalWindow.height = $height;
                   9931:                 modalWindow.content = '$content';
                   9932:                 modalWindow.open();
1.1365    raeburn  9933:                 $mathjax
1.1032    www      9934:         };  
                   9935: // ]]>
                   9936: </script>
                   9937: ENDADHOC
                   9938: }
                   9939: 
1.1041    www      9940: sub modal_adhoc_inner {
1.1365    raeburn  9941:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9942:     my $innerwidth=$width-20;
                   9943:     $content=&js_ready(
1.1140    raeburn  9944:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9945:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9946:                  $content.
1.1041    www      9947:                  &end_scrollbox().
1.1140    raeburn  9948:                  &end_page()
1.1041    www      9949:              );
1.1365    raeburn  9950:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9951: }
                   9952: 
                   9953: sub modal_adhoc_window {
1.1365    raeburn  9954:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9955:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9956:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9957: }
                   9958: 
                   9959: sub modal_adhoc_launch {
                   9960:     my ($funcname,$width,$height,$content)=@_;
                   9961:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9962: <script type="text/javascript">
                   9963: // <![CDATA[
                   9964: $funcname();
                   9965: // ]]>
                   9966: </script>
                   9967: ENDLAUNCH
                   9968: }
                   9969: 
                   9970: sub modal_adhoc_close {
                   9971:     return (<<ENDCLOSE);
                   9972: <script type="text/javascript">
                   9973: // <![CDATA[
                   9974: modalWindow.close();
                   9975: // ]]>
                   9976: </script>
                   9977: ENDCLOSE
                   9978: }
                   9979: 
1.1038    www      9980: sub togglebox_script {
                   9981:    return(<<ENDTOGGLE);
                   9982: <script type="text/javascript"> 
                   9983: // <![CDATA[
                   9984: function LCtoggleDisplay(id,hidetext,showtext) {
                   9985:    link = document.getElementById(id + "link").childNodes[0];
                   9986:    with (document.getElementById(id).style) {
                   9987:       if (display == "none" ) {
                   9988:           display = "inline";
                   9989:           link.nodeValue = hidetext;
                   9990:         } else {
                   9991:           display = "none";
                   9992:           link.nodeValue = showtext;
                   9993:        }
                   9994:    }
                   9995: }
                   9996: // ]]>
                   9997: </script>
                   9998: ENDTOGGLE
                   9999: }
                   10000: 
1.1039    www      10001: sub start_togglebox {
                   10002:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10003:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10004:     unless ($showtext) { $showtext=&mt('show'); }
                   10005:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10006:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10007:     return &start_data_table().
                   10008:            &start_data_table_header_row().
                   10009:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10010:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10011:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10012:            &end_data_table_header_row().
                   10013:            '<tr id="'.$id.'" style="display:none""><td>';
                   10014: }
                   10015: 
                   10016: sub end_togglebox {
                   10017:     return '</td></tr>'.&end_data_table();
                   10018: }
                   10019: 
1.1041    www      10020: sub LCprogressbar_script {
1.1302    raeburn  10021:    my ($id,$number_to_do)=@_;
                   10022:    if ($number_to_do) {
                   10023:        return(<<ENDPROGRESS);
1.1041    www      10024: <script type="text/javascript">
                   10025: // <![CDATA[
1.1045    www      10026: \$('#progressbar$id').progressbar({
1.1041    www      10027:   value: 0,
                   10028:   change: function(event, ui) {
                   10029:     var newVal = \$(this).progressbar('option', 'value');
                   10030:     \$('.pblabel', this).text(LCprogressTxt);
                   10031:   }
                   10032: });
                   10033: // ]]>
                   10034: </script>
                   10035: ENDPROGRESS
1.1302    raeburn  10036:    } else {
                   10037:        return(<<ENDPROGRESS);
                   10038: <script type="text/javascript">
                   10039: // <![CDATA[
                   10040: \$('#progressbar$id').progressbar({
                   10041:   value: false,
                   10042:   create: function(event, ui) {
                   10043:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10044:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10045:   }
                   10046: });
                   10047: // ]]>
                   10048: </script>
                   10049: ENDPROGRESS
                   10050:    }
1.1041    www      10051: }
                   10052: 
                   10053: sub LCprogressbarUpdate_script {
                   10054:    return(<<ENDPROGRESSUPDATE);
                   10055: <style type="text/css">
                   10056: .ui-progressbar { position:relative; }
1.1302    raeburn  10057: .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      10058: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10059: </style>
                   10060: <script type="text/javascript">
                   10061: // <![CDATA[
1.1045    www      10062: var LCprogressTxt='---';
                   10063: 
1.1302    raeburn  10064: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10065:    LCprogressTxt=progresstext;
1.1302    raeburn  10066:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10067:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10068:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10069:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10070:    } else {
                   10071:        \$('#progressbar'+id).progressbar('value',percent);
                   10072:    }
1.1041    www      10073: }
                   10074: // ]]>
                   10075: </script>
                   10076: ENDPROGRESSUPDATE
                   10077: }
                   10078: 
1.1042    www      10079: my $LClastpercent;
1.1045    www      10080: my $LCidcnt;
                   10081: my $LCcurrentid;
1.1042    www      10082: 
1.1041    www      10083: sub LCprogressbar {
1.1302    raeburn  10084:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10085:     $LClastpercent=0;
1.1045    www      10086:     $LCidcnt++;
                   10087:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10088:     my ($starting,$content);
                   10089:     if ($number_to_do) {
                   10090:         $starting=&mt('Starting');
                   10091:         $content=(<<ENDPROGBAR);
                   10092: $preamble
1.1045    www      10093:   <div id="progressbar$LCcurrentid">
1.1041    www      10094:     <span class="pblabel">$starting</span>
                   10095:   </div>
                   10096: ENDPROGBAR
1.1302    raeburn  10097:     } else {
                   10098:         $starting=&mt('Loading...');
                   10099:         $LClastpercent='false';
                   10100:         $content=(<<ENDPROGBAR);
                   10101: $preamble
                   10102:   <div id="progressbar$LCcurrentid">
                   10103:       <div class="progress-label">$starting</div>
                   10104:   </div>
                   10105: ENDPROGBAR
                   10106:     }
                   10107:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10108: }
                   10109: 
                   10110: sub LCprogressbarUpdate {
1.1302    raeburn  10111:     my ($r,$val,$text,$number_to_do)=@_;
                   10112:     if ($number_to_do) {
                   10113:         unless ($val) { 
                   10114:             if ($LClastpercent) {
                   10115:                 $val=$LClastpercent;
                   10116:             } else {
                   10117:                 $val=0;
                   10118:             }
                   10119:         }
                   10120:         if ($val<0) { $val=0; }
                   10121:         if ($val>100) { $val=0; }
                   10122:         $LClastpercent=$val;
                   10123:         unless ($text) { $text=$val.'%'; }
                   10124:     } else {
                   10125:         $val = 'false';
1.1042    www      10126:     }
1.1041    www      10127:     $text=&js_ready($text);
1.1044    www      10128:     &r_print($r,<<ENDUPDATE);
1.1041    www      10129: <script type="text/javascript">
                   10130: // <![CDATA[
1.1302    raeburn  10131: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10132: // ]]>
                   10133: </script>
                   10134: ENDUPDATE
1.1035    www      10135: }
                   10136: 
1.1042    www      10137: sub LCprogressbarClose {
                   10138:     my ($r)=@_;
                   10139:     $LClastpercent=0;
1.1044    www      10140:     &r_print($r,<<ENDCLOSE);
1.1042    www      10141: <script type="text/javascript">
                   10142: // <![CDATA[
1.1045    www      10143: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10144: // ]]>
                   10145: </script>
                   10146: ENDCLOSE
1.1044    www      10147: }
                   10148: 
                   10149: sub r_print {
                   10150:     my ($r,$to_print)=@_;
                   10151:     if ($r) {
                   10152:       $r->print($to_print);
                   10153:       $r->rflush();
                   10154:     } else {
                   10155:       print($to_print);
                   10156:     }
1.1042    www      10157: }
                   10158: 
1.320     albertel 10159: sub html_encode {
                   10160:     my ($result) = @_;
                   10161: 
1.322     albertel 10162:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10163:     
                   10164:     return $result;
                   10165: }
1.1044    www      10166: 
1.317     albertel 10167: sub js_ready {
                   10168:     my ($result) = @_;
                   10169: 
1.323     albertel 10170:     $result =~ s/[\n\r]/ /xmsg;
                   10171:     $result =~ s/\\/\\\\/xmsg;
                   10172:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10173:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10174:     
                   10175:     return $result;
                   10176: }
                   10177: 
1.315     albertel 10178: sub validate_page {
                   10179:     if (  exists($env{'internal.start_page'})
1.316     albertel 10180: 	  &&     $env{'internal.start_page'} > 1) {
                   10181: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10182: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10183: 				 $ENV{'request.filename'});
1.315     albertel 10184:     }
                   10185:     if (  exists($env{'internal.end_page'})
1.316     albertel 10186: 	  &&     $env{'internal.end_page'} > 1) {
                   10187: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10188: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10189: 				 $env{'request.filename'});
1.315     albertel 10190:     }
                   10191:     if (     exists($env{'internal.start_page'})
                   10192: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10193: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10194: 				 $env{'request.filename'});
1.315     albertel 10195:     }
                   10196:     if (   ! exists($env{'internal.start_page'})
                   10197: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10198: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10199: 				 $env{'request.filename'});
1.315     albertel 10200:     }
1.306     albertel 10201: }
1.315     albertel 10202: 
1.996     www      10203: 
                   10204: sub start_scrollbox {
1.1140    raeburn  10205:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10206:     unless ($outerwidth) { $outerwidth='520px'; }
                   10207:     unless ($width) { $width='500px'; }
                   10208:     unless ($height) { $height='200px'; }
1.1075    raeburn  10209:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10210:     if ($id ne '') {
1.1140    raeburn  10211:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10212:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10213:     }
1.1075    raeburn  10214:     if ($bgcolor ne '') {
                   10215:         $tdcol = "background-color: $bgcolor;";
                   10216:     }
1.1137    raeburn  10217:     my $nicescroll_js;
                   10218:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10219:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10220:     }
                   10221:     return <<"END";
                   10222: $nicescroll_js
                   10223: 
                   10224: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10225: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10226: END
                   10227: }
                   10228: 
                   10229: sub end_scrollbox {
                   10230:     return '</div></td></tr></table>';
                   10231: }
                   10232: 
                   10233: sub nicescroll_javascript {
                   10234:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10235:     my %options;
                   10236:     if (ref($cursor) eq 'HASH') {
                   10237:         %options = %{$cursor};
                   10238:     }
                   10239:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10240:         $options{'railalign'} = 'left';
                   10241:     }
                   10242:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10243:         my $function  = &get_users_function();
                   10244:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10245:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10246:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10247:         }
1.1140    raeburn  10248:     }
                   10249:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10250:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10251:             $options{'cursoropacity'}='1.0';
                   10252:         }
1.1140    raeburn  10253:     } else {
                   10254:         $options{'cursoropacity'}='1.0';
                   10255:     }
                   10256:     if ($options{'cursorfixedheight'} eq 'none') {
                   10257:         delete($options{'cursorfixedheight'});
                   10258:     } else {
                   10259:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10260:     }
                   10261:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10262:         delete($options{'railoffset'});
                   10263:     }
                   10264:     my @niceoptions;
                   10265:     while (my($key,$value) = each(%options)) {
                   10266:         if ($value =~ /^\{.+\}$/) {
                   10267:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10268:         } else {
1.1140    raeburn  10269:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10270:         }
1.1140    raeburn  10271:     }
                   10272:     my $nicescroll_js = '
1.1137    raeburn  10273: $(document).ready(
1.1140    raeburn  10274:       function() {
                   10275:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10276:       }
1.1137    raeburn  10277: );
                   10278: ';
1.1140    raeburn  10279:     if ($framecheck) {
                   10280:         $nicescroll_js .= '
                   10281: function expand_div(caller) {
                   10282:     if (top === self) {
                   10283:         document.getElementById("'.$id.'").style.width = "auto";
                   10284:         document.getElementById("'.$id.'").style.height = "auto";
                   10285:     } else {
                   10286:         try {
                   10287:             if (parent.frames) {
                   10288:                 if (parent.frames.length > 1) {
                   10289:                     var framesrc = parent.frames[1].location.href;
                   10290:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10291:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10292:                         document.getElementById("'.$id.'").style.width = "auto";
                   10293:                         document.getElementById("'.$id.'").style.height = "auto";
                   10294:                     }
                   10295:                 }
                   10296:             }
                   10297:         } catch (e) {
                   10298:             return;
                   10299:         }
1.1137    raeburn  10300:     }
1.1140    raeburn  10301:     return;
1.996     www      10302: }
1.1140    raeburn  10303: ';
                   10304:     }
                   10305:     if ($needjsready) {
                   10306:         $nicescroll_js = '
                   10307: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10308:     } else {
                   10309:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10310:     }
                   10311:     return $nicescroll_js;
1.996     www      10312: }
                   10313: 
1.318     albertel 10314: sub simple_error_page {
1.1150    bisitz   10315:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10316:     my %displayargs;
1.1151    raeburn  10317:     if (ref($args) eq 'HASH') {
                   10318:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10319:         if ($args->{'only_body'}) {
                   10320:             $displayargs{'only_body'} = 1;
                   10321:         }
                   10322:         if ($args->{'no_nav_bar'}) {
                   10323:             $displayargs{'no_nav_bar'} = 1;
                   10324:         }
1.1151    raeburn  10325:     } else {
                   10326:         $msg = &mt($msg);
                   10327:     }
1.1150    bisitz   10328: 
1.318     albertel 10329:     my $page =
1.1304    raeburn  10330: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10331: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10332: 	&Apache::loncommon::end_page();
                   10333:     if (ref($r)) {
                   10334: 	$r->print($page);
1.327     albertel 10335: 	return;
1.318     albertel 10336:     }
                   10337:     return $page;
                   10338: }
1.347     albertel 10339: 
                   10340: {
1.610     albertel 10341:     my @row_count;
1.961     onken    10342: 
                   10343:     sub start_data_table_count {
                   10344:         unshift(@row_count, 0);
                   10345:         return;
                   10346:     }
                   10347: 
                   10348:     sub end_data_table_count {
                   10349:         shift(@row_count);
                   10350:         return;
                   10351:     }
                   10352: 
1.347     albertel 10353:     sub start_data_table {
1.1018    raeburn  10354: 	my ($add_class,$id) = @_;
1.422     albertel 10355: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10356:         my $table_id;
                   10357:         if (defined($id)) {
                   10358:             $table_id = ' id="'.$id.'"';
                   10359:         }
1.961     onken    10360: 	&start_data_table_count();
1.1018    raeburn  10361: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10362:     }
                   10363: 
                   10364:     sub end_data_table {
1.961     onken    10365: 	&end_data_table_count();
1.389     albertel 10366: 	return '</table>'."\n";;
1.347     albertel 10367:     }
                   10368: 
                   10369:     sub start_data_table_row {
1.974     wenzelju 10370: 	my ($add_class, $id) = @_;
1.610     albertel 10371: 	$row_count[0]++;
                   10372: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10373: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10374:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10375:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10376:     }
1.471     banghart 10377:     
                   10378:     sub continue_data_table_row {
1.974     wenzelju 10379: 	my ($add_class, $id) = @_;
1.610     albertel 10380: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10381: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10382:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10383:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10384:     }
1.347     albertel 10385: 
                   10386:     sub end_data_table_row {
1.389     albertel 10387: 	return '</tr>'."\n";;
1.347     albertel 10388:     }
1.367     www      10389: 
1.421     albertel 10390:     sub start_data_table_empty_row {
1.707     bisitz   10391: #	$row_count[0]++;
1.421     albertel 10392: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10393:     }
                   10394: 
                   10395:     sub end_data_table_empty_row {
                   10396: 	return '</tr>'."\n";;
                   10397:     }
                   10398: 
1.367     www      10399:     sub start_data_table_header_row {
1.389     albertel 10400: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10401:     }
                   10402: 
                   10403:     sub end_data_table_header_row {
1.389     albertel 10404: 	return '</tr>'."\n";;
1.367     www      10405:     }
1.890     droeschl 10406: 
                   10407:     sub data_table_caption {
                   10408:         my $caption = shift;
                   10409:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10410:     }
1.347     albertel 10411: }
                   10412: 
1.548     albertel 10413: =pod
                   10414: 
                   10415: =item * &inhibit_menu_check($arg)
                   10416: 
                   10417: Checks for a inhibitmenu state and generates output to preserve it
                   10418: 
                   10419: Inputs:         $arg - can be any of
                   10420:                      - undef - in which case the return value is a string 
                   10421:                                to add  into arguments list of a uri
                   10422:                      - 'input' - in which case the return value is a HTML
                   10423:                                  <form> <input> field of type hidden to
                   10424:                                  preserve the value
                   10425:                      - a url - in which case the return value is the url with
                   10426:                                the neccesary cgi args added to preserve the
                   10427:                                inhibitmenu state
                   10428:                      - a ref to a url - no return value, but the string is
                   10429:                                         updated to include the neccessary cgi
                   10430:                                         args to preserve the inhibitmenu state
                   10431: 
                   10432: =cut
                   10433: 
                   10434: sub inhibit_menu_check {
                   10435:     my ($arg) = @_;
                   10436:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10437:     if ($arg eq 'input') {
                   10438: 	if ($env{'form.inhibitmenu'}) {
                   10439: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10440: 	} else {
                   10441: 	    return
                   10442: 	}
                   10443:     }
                   10444:     if ($env{'form.inhibitmenu'}) {
                   10445: 	if (ref($arg)) {
                   10446: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10447: 	} elsif ($arg eq '') {
                   10448: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10449: 	} else {
                   10450: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10451: 	}
                   10452:     }
                   10453:     if (!ref($arg)) {
                   10454: 	return $arg;
                   10455:     }
                   10456: }
                   10457: 
1.251     albertel 10458: ###############################################
1.182     matthew  10459: 
                   10460: =pod
                   10461: 
1.549     albertel 10462: =back
                   10463: 
                   10464: =head1 User Information Routines
                   10465: 
                   10466: =over 4
                   10467: 
1.405     albertel 10468: =item * &get_users_function()
1.182     matthew  10469: 
                   10470: Used by &bodytag to determine the current users primary role.
                   10471: Returns either 'student','coordinator','admin', or 'author'.
                   10472: 
                   10473: =cut
                   10474: 
                   10475: ###############################################
                   10476: sub get_users_function {
1.815     tempelho 10477:     my $function = 'norole';
1.818     tempelho 10478:     if ($env{'request.role'}=~/^(st)/) {
                   10479:         $function='student';
                   10480:     }
1.907     raeburn  10481:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10482:         $function='coordinator';
                   10483:     }
1.258     albertel 10484:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10485:         $function='admin';
                   10486:     }
1.826     bisitz   10487:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10488:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10489:         $function='author';
                   10490:     }
                   10491:     return $function;
1.54      www      10492: }
1.99      www      10493: 
                   10494: ###############################################
                   10495: 
1.233     raeburn  10496: =pod
                   10497: 
1.821     raeburn  10498: =item * &show_course()
                   10499: 
                   10500: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10501: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10502: 
                   10503: Inputs:
                   10504: None
                   10505: 
                   10506: Outputs:
                   10507: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10508: 
                   10509: =cut
                   10510: 
                   10511: ###############################################
                   10512: sub show_course {
1.1408    raeburn  10513:     my ($udom,$uname) = @_;
                   10514:     if (($udom ne '') && ($uname ne '')) {
                   10515:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10516:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10517:                 return 0;
                   10518:             } else {
                   10519:                 return 1;
                   10520:             }
                   10521:         }
                   10522:     }
1.821     raeburn  10523:     my $course = !$env{'user.adv'};
                   10524:     if (!$env{'user.adv'}) {
                   10525:         foreach my $env (keys(%env)) {
                   10526:             next if ($env !~ m/^user\.priv\./);
                   10527:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10528:                 $course = 0;
                   10529:                 last;
                   10530:             }
                   10531:         }
                   10532:     }
                   10533:     return $course;
                   10534: }
                   10535: 
                   10536: ###############################################
                   10537: 
                   10538: =pod
                   10539: 
1.542     raeburn  10540: =item * &check_user_status()
1.274     raeburn  10541: 
                   10542: Determines current status of supplied role for a
                   10543: specific user. Roles can be active, previous or future.
                   10544: 
                   10545: Inputs: 
                   10546: user's domain, user's username, course's domain,
1.375     raeburn  10547: course's number, optional section ID.
1.274     raeburn  10548: 
                   10549: Outputs:
                   10550: role status: active, previous or future. 
                   10551: 
                   10552: =cut
                   10553: 
                   10554: sub check_user_status {
1.412     raeburn  10555:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10556:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10557:     my @uroles = keys(%userinfo);
1.274     raeburn  10558:     my $srchstr;
                   10559:     my $active_chk = 'none';
1.412     raeburn  10560:     my $now = time;
1.274     raeburn  10561:     if (@uroles > 0) {
1.908     raeburn  10562:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10563:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10564:         } else {
1.412     raeburn  10565:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10566:         }
                   10567:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10568:             my $role_end = 0;
                   10569:             my $role_start = 0;
                   10570:             $active_chk = 'active';
1.412     raeburn  10571:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10572:                 $role_end = $1;
                   10573:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10574:                     $role_start = $1;
1.274     raeburn  10575:                 }
                   10576:             }
                   10577:             if ($role_start > 0) {
1.412     raeburn  10578:                 if ($now < $role_start) {
1.274     raeburn  10579:                     $active_chk = 'future';
                   10580:                 }
                   10581:             }
                   10582:             if ($role_end > 0) {
1.412     raeburn  10583:                 if ($now > $role_end) {
1.274     raeburn  10584:                     $active_chk = 'previous';
                   10585:                 }
                   10586:             }
                   10587:         }
                   10588:     }
                   10589:     return $active_chk;
                   10590: }
                   10591: 
                   10592: ###############################################
                   10593: 
                   10594: =pod
                   10595: 
1.405     albertel 10596: =item * &get_sections()
1.233     raeburn  10597: 
                   10598: Determines all the sections for a course including
                   10599: sections with students and sections containing other roles.
1.419     raeburn  10600: Incoming parameters: 
                   10601: 
                   10602: 1. domain
                   10603: 2. course number 
                   10604: 3. reference to array containing roles for which sections should 
                   10605: be gathered (optional).
                   10606: 4. reference to array containing status types for which sections 
                   10607: should be gathered (optional).
                   10608: 
                   10609: If the third argument is undefined, sections are gathered for any role. 
                   10610: If the fourth argument is undefined, sections are gathered for any status.
                   10611: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10612:  
1.374     raeburn  10613: Returns section hash (keys are section IDs, values are
                   10614: number of users in each section), subject to the
1.419     raeburn  10615: optional roles filter, optional status filter 
1.233     raeburn  10616: 
                   10617: =cut
                   10618: 
                   10619: ###############################################
                   10620: sub get_sections {
1.419     raeburn  10621:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10622:     if (!defined($cdom) || !defined($cnum)) {
                   10623:         my $cid =  $env{'request.course.id'};
                   10624: 
                   10625: 	return if (!defined($cid));
                   10626: 
                   10627:         $cdom = $env{'course.'.$cid.'.domain'};
                   10628:         $cnum = $env{'course.'.$cid.'.num'};
                   10629:     }
                   10630: 
                   10631:     my %sectioncount;
1.419     raeburn  10632:     my $now = time;
1.240     albertel 10633: 
1.1118    raeburn  10634:     my $check_students = 1;
                   10635:     my $only_students = 0;
                   10636:     if (ref($possible_roles) eq 'ARRAY') {
                   10637:         if (grep(/^st$/,@{$possible_roles})) {
                   10638:             if (@{$possible_roles} == 1) {
                   10639:                 $only_students = 1;
                   10640:             }
                   10641:         } else {
                   10642:             $check_students = 0;
                   10643:         }
                   10644:     }
                   10645: 
                   10646:     if ($check_students) { 
1.276     albertel 10647: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10648: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10649: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10650:         my $start_index = &Apache::loncoursedata::CL_START();
                   10651:         my $end_index = &Apache::loncoursedata::CL_END();
                   10652:         my $status;
1.366     albertel 10653: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10654: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10655: 				                     $data->[$status_index],
                   10656:                                                      $data->[$start_index],
                   10657:                                                      $data->[$end_index]);
                   10658:             if ($stu_status eq 'Active') {
                   10659:                 $status = 'active';
                   10660:             } elsif ($end < $now) {
                   10661:                 $status = 'previous';
                   10662:             } elsif ($start > $now) {
                   10663:                 $status = 'future';
                   10664:             } 
                   10665: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10666:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10667:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10668: 		    $sectioncount{$section}++;
                   10669:                 }
1.240     albertel 10670: 	    }
                   10671: 	}
                   10672:     }
1.1118    raeburn  10673:     if ($only_students) {
                   10674:         return %sectioncount;
                   10675:     }
1.240     albertel 10676:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10677:     foreach my $user (sort(keys(%courseroles))) {
                   10678: 	if ($user !~ /^(\w{2})/) { next; }
                   10679: 	my ($role) = ($user =~ /^(\w{2})/);
                   10680: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10681: 	my ($section,$status);
1.240     albertel 10682: 	if ($role eq 'cr' &&
                   10683: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10684: 	    $section=$1;
                   10685: 	}
                   10686: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10687: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10688:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10689:         if ($end == -1 && $start == -1) {
                   10690:             next; #deleted role
                   10691:         }
                   10692:         if (!defined($possible_status)) { 
                   10693:             $sectioncount{$section}++;
                   10694:         } else {
                   10695:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10696:                 $status = 'active';
                   10697:             } elsif ($end < $now) {
                   10698:                 $status = 'future';
                   10699:             } elsif ($start > $now) {
                   10700:                 $status = 'previous';
                   10701:             }
                   10702:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10703:                 $sectioncount{$section}++;
                   10704:             }
                   10705:         }
1.233     raeburn  10706:     }
1.366     albertel 10707:     return %sectioncount;
1.233     raeburn  10708: }
                   10709: 
1.274     raeburn  10710: ###############################################
1.294     raeburn  10711: 
                   10712: =pod
1.405     albertel 10713: 
                   10714: =item * &get_course_users()
                   10715: 
1.275     raeburn  10716: Retrieves usernames:domains for users in the specified course
                   10717: with specific role(s), and access status. 
                   10718: 
                   10719: Incoming parameters:
1.277     albertel 10720: 1. course domain
                   10721: 2. course number
                   10722: 3. access status: users must have - either active, 
1.275     raeburn  10723: previous, future, or all.
1.277     albertel 10724: 4. reference to array of permissible roles
1.288     raeburn  10725: 5. reference to array of section restrictions (optional)
                   10726: 6. reference to results object (hash of hashes).
                   10727: 7. reference to optional userdata hash
1.609     raeburn  10728: 8. reference to optional statushash
1.630     raeburn  10729: 9. flag if privileged users (except those set to unhide in
                   10730:    course settings) should be excluded    
1.609     raeburn  10731: Keys of top level results hash are roles.
1.275     raeburn  10732: Keys of inner hashes are username:domain, with 
                   10733: values set to access type.
1.288     raeburn  10734: Optional userdata hash returns an array with arguments in the 
                   10735: same order as loncoursedata::get_classlist() for student data.
                   10736: 
1.609     raeburn  10737: Optional statushash returns
                   10738: 
1.288     raeburn  10739: Entries for end, start, section and status are blank because
                   10740: of the possibility of multiple values for non-student roles.
                   10741: 
1.275     raeburn  10742: =cut
1.405     albertel 10743: 
1.275     raeburn  10744: ###############################################
1.405     albertel 10745: 
1.275     raeburn  10746: sub get_course_users {
1.630     raeburn  10747:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10748:     my %idx = ();
1.419     raeburn  10749:     my %seclists;
1.288     raeburn  10750: 
                   10751:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10752:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10753:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10754:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10755:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10756:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10757:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10758:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10759: 
1.290     albertel 10760:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10761:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10762:         my $now = time;
1.277     albertel 10763:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10764:             my $match = 0;
1.412     raeburn  10765:             my $secmatch = 0;
1.419     raeburn  10766:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10767:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10768:             if ($section eq '') {
                   10769:                 $section = 'none';
                   10770:             }
1.291     albertel 10771:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10772:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10773:                     $secmatch = 1;
                   10774:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10775:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10776:                         $secmatch = 1;
                   10777:                     }
                   10778:                 } else {  
1.419     raeburn  10779: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10780: 		        $secmatch = 1;
                   10781:                     }
1.290     albertel 10782: 		}
1.412     raeburn  10783:                 if (!$secmatch) {
                   10784:                     next;
                   10785:                 }
1.419     raeburn  10786:             }
1.275     raeburn  10787:             if (defined($$types{'active'})) {
1.288     raeburn  10788:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10789:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10790:                     $match = 1;
1.275     raeburn  10791:                 }
                   10792:             }
                   10793:             if (defined($$types{'previous'})) {
1.609     raeburn  10794:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10795:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10796:                     $match = 1;
1.275     raeburn  10797:                 }
                   10798:             }
                   10799:             if (defined($$types{'future'})) {
1.609     raeburn  10800:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10801:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10802:                     $match = 1;
1.275     raeburn  10803:                 }
                   10804:             }
1.609     raeburn  10805:             if ($match) {
                   10806:                 push(@{$seclists{$student}},$section);
                   10807:                 if (ref($userdata) eq 'HASH') {
                   10808:                     $$userdata{$student} = $$classlist{$student};
                   10809:                 }
                   10810:                 if (ref($statushash) eq 'HASH') {
                   10811:                     $statushash->{$student}{'st'}{$section} = $status;
                   10812:                 }
1.288     raeburn  10813:             }
1.275     raeburn  10814:         }
                   10815:     }
1.412     raeburn  10816:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10817:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10818:         my $now = time;
1.609     raeburn  10819:         my %displaystatus = ( previous => 'Expired',
                   10820:                               active   => 'Active',
                   10821:                               future   => 'Future',
                   10822:                             );
1.1121    raeburn  10823:         my (%nothide,@possdoms);
1.630     raeburn  10824:         if ($hidepriv) {
                   10825:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10826:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10827:                 if ($user !~ /:/) {
                   10828:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10829:                 } else {
                   10830:                     $nothide{$user} = 1;
                   10831:                 }
                   10832:             }
1.1121    raeburn  10833:             my @possdoms = ($cdom);
                   10834:             if ($coursehash{'checkforpriv'}) {
                   10835:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10836:             }
1.630     raeburn  10837:         }
1.439     raeburn  10838:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10839:             my $match = 0;
1.412     raeburn  10840:             my $secmatch = 0;
1.439     raeburn  10841:             my $status;
1.412     raeburn  10842:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10843:             $user =~ s/:$//;
1.439     raeburn  10844:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10845:             if ($end == -1 || $start == -1) {
                   10846:                 next;
                   10847:             }
                   10848:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10849:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10850:                 my ($uname,$udom) = split(/:/,$user);
                   10851:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10852:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10853:                         $secmatch = 1;
                   10854:                     } elsif ($usec eq '') {
1.420     albertel 10855:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10856:                             $secmatch = 1;
                   10857:                         }
                   10858:                     } else {
                   10859:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10860:                             $secmatch = 1;
                   10861:                         }
                   10862:                     }
                   10863:                     if (!$secmatch) {
                   10864:                         next;
                   10865:                     }
1.288     raeburn  10866:                 }
1.419     raeburn  10867:                 if ($usec eq '') {
                   10868:                     $usec = 'none';
                   10869:                 }
1.275     raeburn  10870:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10871:                     if ($hidepriv) {
1.1121    raeburn  10872:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10873:                             (!$nothide{$uname.':'.$udom})) {
                   10874:                             next;
                   10875:                         }
                   10876:                     }
1.503     raeburn  10877:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10878:                         $status = 'previous';
                   10879:                     } elsif ($start > $now) {
                   10880:                         $status = 'future';
                   10881:                     } else {
                   10882:                         $status = 'active';
                   10883:                     }
1.277     albertel 10884:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10885:                         if ($status eq $type) {
1.420     albertel 10886:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10887:                                 push(@{$$users{$role}{$user}},$type);
                   10888:                             }
1.288     raeburn  10889:                             $match = 1;
                   10890:                         }
                   10891:                     }
1.419     raeburn  10892:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10893:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10894: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10895:                         }
1.420     albertel 10896:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10897:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10898:                         }
1.609     raeburn  10899:                         if (ref($statushash) eq 'HASH') {
                   10900:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10901:                         }
1.275     raeburn  10902:                     }
                   10903:                 }
                   10904:             }
                   10905:         }
1.290     albertel 10906:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10907:             if ((defined($cdom)) && (defined($cnum))) {
                   10908:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10909:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10910:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10911:                     next if ($owner eq '');
                   10912:                     my ($ownername,$ownerdom);
                   10913:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10914:                         $ownername = $1;
                   10915:                         $ownerdom = $2;
                   10916:                     } else {
                   10917:                         $ownername = $owner;
                   10918:                         $ownerdom = $cdom;
                   10919:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10920:                     }
                   10921:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10922:                     if (defined($userdata) && 
1.609     raeburn  10923: 			!exists($$userdata{$owner})) {
                   10924: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10925:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10926:                             push(@{$seclists{$owner}},'none');
                   10927:                         }
                   10928:                         if (ref($statushash) eq 'HASH') {
                   10929:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10930:                         }
1.290     albertel 10931: 		    }
1.279     raeburn  10932:                 }
                   10933:             }
                   10934:         }
1.419     raeburn  10935:         foreach my $user (keys(%seclists)) {
                   10936:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10937:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10938:         }
1.275     raeburn  10939:     }
                   10940:     return;
                   10941: }
                   10942: 
1.288     raeburn  10943: sub get_user_info {
                   10944:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10945:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10946: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10947:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10948:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10949:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10950:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10951:     return;
                   10952: }
1.275     raeburn  10953: 
1.472     raeburn  10954: ###############################################
                   10955: 
                   10956: =pod
                   10957: 
                   10958: =item * &get_user_quota()
                   10959: 
1.1134    raeburn  10960: Retrieves quota assigned for storage of user files.
                   10961: Default is to report quota for portfolio files.
1.472     raeburn  10962: 
                   10963: Incoming parameters:
                   10964: 1. user's username
                   10965: 2. user's domain
1.1134    raeburn  10966: 3. quota name - portfolio, author, or course
1.1136    raeburn  10967:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10968: 4. crstype - official, unofficial, textbook, placement or community, 
                   10969:    if quota name is course
1.472     raeburn  10970: 
                   10971: Returns:
1.1163    raeburn  10972: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10973: 2. (Optional) Type of setting: custom or default
                   10974:    (individually assigned or default for user's 
                   10975:    institutional status).
                   10976: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10977:    or student - types as defined in localenroll::inst_usertypes 
                   10978:    for user's domain, which determines default quota for user.
                   10979: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10980: 
                   10981: If a value has been stored in the user's environment, 
1.536     raeburn  10982: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10983: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10984: 
                   10985: =cut
                   10986: 
                   10987: ###############################################
                   10988: 
                   10989: 
                   10990: sub get_user_quota {
1.1136    raeburn  10991:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10992:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10993:     if (!defined($udom)) {
                   10994:         $udom = $env{'user.domain'};
                   10995:     }
                   10996:     if (!defined($uname)) {
                   10997:         $uname = $env{'user.name'};
                   10998:     }
                   10999:     if (($udom eq '' || $uname eq '') ||
                   11000:         ($udom eq 'public') && ($uname eq 'public')) {
                   11001:         $quota = 0;
1.536     raeburn  11002:         $quotatype = 'default';
                   11003:         $defquota = 0; 
1.472     raeburn  11004:     } else {
1.536     raeburn  11005:         my $inststatus;
1.1134    raeburn  11006:         if ($quotaname eq 'course') {
                   11007:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11008:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11009:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11010:             } else {
                   11011:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11012:                 $quota = $cenv{'internal.uploadquota'};
                   11013:             }
1.536     raeburn  11014:         } else {
1.1134    raeburn  11015:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11016:                 if ($quotaname eq 'author') {
                   11017:                     $quota = $env{'environment.authorquota'};
                   11018:                 } else {
                   11019:                     $quota = $env{'environment.portfolioquota'};
                   11020:                 }
                   11021:                 $inststatus = $env{'environment.inststatus'};
                   11022:             } else {
                   11023:                 my %userenv = 
                   11024:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11025:                                          'authorquota','inststatus'],$udom,$uname);
                   11026:                 my ($tmp) = keys(%userenv);
                   11027:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11028:                     if ($quotaname eq 'author') {
                   11029:                         $quota = $userenv{'authorquota'};
                   11030:                     } else {
                   11031:                         $quota = $userenv{'portfolioquota'};
                   11032:                     }
                   11033:                     $inststatus = $userenv{'inststatus'};
                   11034:                 } else {
                   11035:                     undef(%userenv);
                   11036:                 }
                   11037:             }
                   11038:         }
                   11039:         if ($quota eq '' || wantarray) {
                   11040:             if ($quotaname eq 'course') {
                   11041:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11042:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11043:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11044:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11045:                     $defquota = $domdefs{$crstype.'quota'};
                   11046:                 }
                   11047:                 if ($defquota eq '') {
                   11048:                     $defquota = 500;
                   11049:                 }
1.1134    raeburn  11050:             } else {
                   11051:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11052:             }
                   11053:             if ($quota eq '') {
                   11054:                 $quota = $defquota;
                   11055:                 $quotatype = 'default';
                   11056:             } else {
                   11057:                 $quotatype = 'custom';
                   11058:             }
1.472     raeburn  11059:         }
                   11060:     }
1.536     raeburn  11061:     if (wantarray) {
                   11062:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11063:     } else {
                   11064:         return $quota;
                   11065:     }
1.472     raeburn  11066: }
                   11067: 
                   11068: ###############################################
                   11069: 
                   11070: =pod
                   11071: 
                   11072: =item * &default_quota()
                   11073: 
1.536     raeburn  11074: Retrieves default quota assigned for storage of user portfolio files,
                   11075: given an (optional) user's institutional status.
1.472     raeburn  11076: 
                   11077: Incoming parameters:
1.1142    raeburn  11078: 
1.472     raeburn  11079: 1. domain
1.536     raeburn  11080: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11081:    status types (e.g., faculty, staff, student etc.)
                   11082:    which apply to the user for whom the default is being retrieved.
                   11083:    If the institutional status string in undefined, the domain
1.1134    raeburn  11084:    default quota will be returned.
                   11085: 3.  quota name - portfolio, author, or course
                   11086:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11087: 
                   11088: Returns:
1.1142    raeburn  11089: 
1.1163    raeburn  11090: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11091: 2. (Optional) institutional type which determined the value of the
                   11092:    default quota.
1.472     raeburn  11093: 
                   11094: If a value has been stored in the domain's configuration db,
                   11095: it will return that, otherwise it returns 20 (for backwards 
                   11096: compatibility with domains which have not set up a configuration
1.1163    raeburn  11097: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11098: 
1.536     raeburn  11099: If the user's status includes multiple types (e.g., staff and student),
                   11100: the largest default quota which applies to the user determines the
                   11101: default quota returned.
                   11102: 
1.472     raeburn  11103: =cut
                   11104: 
                   11105: ###############################################
                   11106: 
                   11107: 
                   11108: sub default_quota {
1.1134    raeburn  11109:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11110:     my ($defquota,$settingstatus);
                   11111:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11112:                                             ['quotas'],$udom);
1.1134    raeburn  11113:     my $key = 'defaultquota';
                   11114:     if ($quotaname eq 'author') {
                   11115:         $key = 'authorquota';
                   11116:     }
1.622     raeburn  11117:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11118:         if ($inststatus ne '') {
1.765     raeburn  11119:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11120:             foreach my $item (@statuses) {
1.1134    raeburn  11121:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11122:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11123:                         if ($defquota eq '') {
1.1134    raeburn  11124:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11125:                             $settingstatus = $item;
1.1134    raeburn  11126:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11127:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11128:                             $settingstatus = $item;
                   11129:                         }
                   11130:                     }
1.1134    raeburn  11131:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11132:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11133:                         if ($defquota eq '') {
                   11134:                             $defquota = $quotahash{'quotas'}{$item};
                   11135:                             $settingstatus = $item;
                   11136:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11137:                             $defquota = $quotahash{'quotas'}{$item};
                   11138:                             $settingstatus = $item;
                   11139:                         }
1.536     raeburn  11140:                     }
                   11141:                 }
                   11142:             }
                   11143:         }
                   11144:         if ($defquota eq '') {
1.1134    raeburn  11145:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11146:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11147:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11148:                 $defquota = $quotahash{'quotas'}{'default'};
                   11149:             }
1.536     raeburn  11150:             $settingstatus = 'default';
1.1139    raeburn  11151:             if ($defquota eq '') {
                   11152:                 if ($quotaname eq 'author') {
                   11153:                     $defquota = 500;
                   11154:                 }
                   11155:             }
1.536     raeburn  11156:         }
                   11157:     } else {
                   11158:         $settingstatus = 'default';
1.1134    raeburn  11159:         if ($quotaname eq 'author') {
                   11160:             $defquota = 500;
                   11161:         } else {
                   11162:             $defquota = 20;
                   11163:         }
1.536     raeburn  11164:     }
                   11165:     if (wantarray) {
                   11166:         return ($defquota,$settingstatus);
1.472     raeburn  11167:     } else {
1.536     raeburn  11168:         return $defquota;
1.472     raeburn  11169:     }
                   11170: }
                   11171: 
1.1135    raeburn  11172: ###############################################
                   11173: 
                   11174: =pod
                   11175: 
1.1136    raeburn  11176: =item * &excess_filesize_warning()
1.1135    raeburn  11177: 
                   11178: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11179: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11180: space to be exceeded.
1.1136    raeburn  11181: 
                   11182: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11183: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11184: 
1.1165    raeburn  11185: Inputs: 7 
1.1136    raeburn  11186: 1. username or coursenum
1.1135    raeburn  11187: 2. domain
1.1136    raeburn  11188: 3. context ('author' or 'course')
1.1135    raeburn  11189: 4. filename of file for which action is being requested
                   11190: 5. filesize (kB) of file
                   11191: 6. action being taken: copy or upload.
1.1237    raeburn  11192: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11193: 
                   11194: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11195:          otherwise return null.
                   11196: 
                   11197: =back
1.1135    raeburn  11198: 
                   11199: =cut
                   11200: 
1.1136    raeburn  11201: sub excess_filesize_warning {
1.1165    raeburn  11202:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11203:     my $current_disk_usage = 0;
1.1165    raeburn  11204:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11205:     if ($context eq 'author') {
                   11206:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11207:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11208:     } else {
                   11209:         foreach my $subdir ('docs','supplemental') {
                   11210:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11211:         }
                   11212:     }
1.1135    raeburn  11213:     $disk_quota = int($disk_quota * 1000);
                   11214:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11215:         return '<p class="LC_warning">'.
1.1135    raeburn  11216:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11217:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11218:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11219:                             $disk_quota,$current_disk_usage).
                   11220:                '</p>';
                   11221:     }
                   11222:     return;
                   11223: }
                   11224: 
                   11225: ###############################################
                   11226: 
                   11227: 
1.1136    raeburn  11228: 
                   11229: 
1.384     raeburn  11230: sub get_secgrprole_info {
                   11231:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11232:     my %sections_count = &get_sections($cdom,$cnum);
                   11233:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11234:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11235:     my @groups = sort(keys(%curr_groups));
                   11236:     my $allroles = [];
                   11237:     my $rolehash;
                   11238:     my $accesshash = {
                   11239:                      active => 'Currently has access',
                   11240:                      future => 'Will have future access',
                   11241:                      previous => 'Previously had access',
                   11242:                   };
                   11243:     if ($needroles) {
                   11244:         $rolehash = {'all' => 'all'};
1.385     albertel 11245:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11246: 	if (&Apache::lonnet::error(%user_roles)) {
                   11247: 	    undef(%user_roles);
                   11248: 	}
                   11249:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11250:             my ($role)=split(/\:/,$item,2);
                   11251:             if ($role eq 'cr') { next; }
                   11252:             if ($role =~ /^cr/) {
                   11253:                 $$rolehash{$role} = (split('/',$role))[3];
                   11254:             } else {
                   11255:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11256:             }
                   11257:         }
                   11258:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11259:             push(@{$allroles},$key);
                   11260:         }
                   11261:         push (@{$allroles},'st');
                   11262:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11263:     }
                   11264:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11265: }
                   11266: 
1.555     raeburn  11267: sub user_picker {
1.1279    raeburn  11268:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11269:     my $currdom = $dom;
1.1253    raeburn  11270:     my @alldoms = &Apache::lonnet::all_domains();
                   11271:     if (@alldoms == 1) {
                   11272:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11273:                                                ['directorysrch'],$alldoms[0]);
                   11274:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11275:         my $showdom = $domdesc;
                   11276:         if ($showdom eq '') {
                   11277:             $showdom = $dom;
                   11278:         }
                   11279:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11280:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11281:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11282:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11283:             }
                   11284:         }
                   11285:     }
1.555     raeburn  11286:     my %curr_selected = (
                   11287:                         srchin => 'dom',
1.580     raeburn  11288:                         srchby => 'lastname',
1.555     raeburn  11289:                       );
                   11290:     my $srchterm;
1.625     raeburn  11291:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11292:         if ($srch->{'srchby'} ne '') {
                   11293:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11294:         }
                   11295:         if ($srch->{'srchin'} ne '') {
                   11296:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11297:         }
                   11298:         if ($srch->{'srchtype'} ne '') {
                   11299:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11300:         }
                   11301:         if ($srch->{'srchdomain'} ne '') {
                   11302:             $currdom = $srch->{'srchdomain'};
                   11303:         }
                   11304:         $srchterm = $srch->{'srchterm'};
                   11305:     }
1.1222    damieng  11306:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11307:                     'usr'       => 'Search criteria',
1.563     raeburn  11308:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11309:                     'uname'     => 'username',
                   11310:                     'lastname'  => 'last name',
1.555     raeburn  11311:                     'lastfirst' => 'last name, first name',
1.558     albertel 11312:                     'crs'       => 'in this course',
1.576     raeburn  11313:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11314:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11315:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11316:                     'exact'     => 'is',
                   11317:                     'contains'  => 'contains',
1.569     raeburn  11318:                     'begins'    => 'begins with',
1.1222    damieng  11319:                                        );
                   11320:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11321:                     'youm'      => "You must include some text to search for.",
                   11322:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11323:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11324:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11325:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11326:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11327:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11328:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11329:                                        );
1.1222    damieng  11330:     &html_escape(\%html_lt);
                   11331:     &js_escape(\%js_lt);
1.1255    raeburn  11332:     my $domform;
1.1277    raeburn  11333:     my $allow_blank = 1;
1.1255    raeburn  11334:     if ($fixeddom) {
1.1277    raeburn  11335:         $allow_blank = 0;
                   11336:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11337:     } else {
1.1287    raeburn  11338:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11339:         my ($trusted,$untrusted);
1.1287    raeburn  11340:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11341:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11342:         } elsif ($context eq 'author') {
1.1288    raeburn  11343:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11344:         } elsif ($context eq 'domain') {
1.1288    raeburn  11345:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11346:         }
1.1288    raeburn  11347:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11348:     }
1.563     raeburn  11349:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11350: 
                   11351:     my @srchins = ('crs','dom','alc','instd');
                   11352: 
                   11353:     foreach my $option (@srchins) {
                   11354:         # FIXME 'alc' option unavailable until 
                   11355:         #       loncreateuser::print_user_query_page()
                   11356:         #       has been completed.
                   11357:         next if ($option eq 'alc');
1.880     raeburn  11358:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11359:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11360:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11361:         if ($curr_selected{'srchin'} eq $option) {
                   11362:             $srchinsel .= ' 
1.1222    damieng  11363:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11364:         } else {
                   11365:             $srchinsel .= '
1.1222    damieng  11366:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11367:         }
1.555     raeburn  11368:     }
1.563     raeburn  11369:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11370: 
                   11371:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11372:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11373:         if ($curr_selected{'srchby'} eq $option) {
                   11374:             $srchbysel .= '
1.1222    damieng  11375:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11376:         } else {
                   11377:             $srchbysel .= '
1.1222    damieng  11378:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11379:          }
                   11380:     }
                   11381:     $srchbysel .= "\n  </select>\n";
                   11382: 
                   11383:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11384:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11385:         if ($curr_selected{'srchtype'} eq $option) {
                   11386:             $srchtypesel .= '
1.1222    damieng  11387:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11388:         } else {
                   11389:             $srchtypesel .= '
1.1222    damieng  11390:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11391:         }
                   11392:     }
                   11393:     $srchtypesel .= "\n  </select>\n";
                   11394: 
1.558     albertel 11395:     my ($newuserscript,$new_user_create);
1.994     raeburn  11396:     my $context_dom = $env{'request.role.domain'};
                   11397:     if ($context eq 'requestcrs') {
                   11398:         if ($env{'form.coursedom'} ne '') { 
                   11399:             $context_dom = $env{'form.coursedom'};
                   11400:         }
                   11401:     }
1.556     raeburn  11402:     if ($forcenewuser) {
1.576     raeburn  11403:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11404:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11405:                 if ($cancreate) {
                   11406:                     $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>';
                   11407:                 } else {
1.799     bisitz   11408:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11409:                     my %usertypetext = (
                   11410:                         official   => 'institutional',
                   11411:                         unofficial => 'non-institutional',
                   11412:                     );
1.799     bisitz   11413:                     $new_user_create = '<p class="LC_warning">'
                   11414:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11415:                                       .' '
                   11416:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11417:                                           ,'<a href="'.$helplink.'">','</a>')
                   11418:                                       .'</p><br />';
1.627     raeburn  11419:                 }
1.576     raeburn  11420:             }
                   11421:         }
                   11422: 
1.556     raeburn  11423:         $newuserscript = <<"ENDSCRIPT";
                   11424: 
1.570     raeburn  11425: function setSearch(createnew,callingForm) {
1.556     raeburn  11426:     if (createnew == 1) {
1.570     raeburn  11427:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11428:             if (callingForm.srchby.options[i].value == 'uname') {
                   11429:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11430:             }
                   11431:         }
1.570     raeburn  11432:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11433:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11434: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11435:             }
                   11436:         }
1.570     raeburn  11437:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11438:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11439:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11440:             }
                   11441:         }
1.570     raeburn  11442:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11443:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11444:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11445:             }
                   11446:         }
                   11447:     }
                   11448: }
                   11449: ENDSCRIPT
1.558     albertel 11450: 
1.556     raeburn  11451:     }
                   11452: 
1.555     raeburn  11453:     my $output = <<"END_BLOCK";
1.556     raeburn  11454: <script type="text/javascript">
1.824     bisitz   11455: // <![CDATA[
1.570     raeburn  11456: function validateEntry(callingForm) {
1.558     albertel 11457: 
1.556     raeburn  11458:     var checkok = 1;
1.558     albertel 11459:     var srchin;
1.570     raeburn  11460:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11461: 	if ( callingForm.srchin[i].checked ) {
                   11462: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11463: 	}
                   11464:     }
                   11465: 
1.570     raeburn  11466:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11467:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11468:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11469:     var srchterm =  callingForm.srchterm.value;
                   11470:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11471:     var msg = "";
                   11472: 
                   11473:     if (srchterm == "") {
                   11474:         checkok = 0;
1.1222    damieng  11475:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11476:     }
                   11477: 
1.569     raeburn  11478:     if (srchtype== 'begins') {
                   11479:         if (srchterm.length < 2) {
                   11480:             checkok = 0;
1.1222    damieng  11481:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11482:         }
                   11483:     }
                   11484: 
1.556     raeburn  11485:     if (srchtype== 'contains') {
                   11486:         if (srchterm.length < 3) {
                   11487:             checkok = 0;
1.1222    damieng  11488:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11489:         }
                   11490:     }
                   11491:     if (srchin == 'instd') {
                   11492:         if (srchdomain == '') {
                   11493:             checkok = 0;
1.1222    damieng  11494:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11495:         }
                   11496:     }
                   11497:     if (srchin == 'dom') {
                   11498:         if (srchdomain == '') {
                   11499:             checkok = 0;
1.1222    damieng  11500:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11501:         }
                   11502:     }
                   11503:     if (srchby == 'lastfirst') {
                   11504:         if (srchterm.indexOf(",") == -1) {
                   11505:             checkok = 0;
1.1222    damieng  11506:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11507:         }
                   11508:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11509:             checkok = 0;
1.1222    damieng  11510:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11511:         }
                   11512:     }
                   11513:     if (checkok == 0) {
1.1222    damieng  11514:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11515:         return;
                   11516:     }
                   11517:     if (checkok == 1) {
1.570     raeburn  11518:         callingForm.submit();
1.556     raeburn  11519:     }
                   11520: }
                   11521: 
                   11522: $newuserscript
                   11523: 
1.824     bisitz   11524: // ]]>
1.556     raeburn  11525: </script>
1.558     albertel 11526: 
                   11527: $new_user_create
                   11528: 
1.555     raeburn  11529: END_BLOCK
1.558     albertel 11530: 
1.876     raeburn  11531:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11532:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11533:                $domform.
                   11534:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11535:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11536:                $srchbysel.
                   11537:                $srchtypesel. 
                   11538:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11539:                $srchinsel.
                   11540:                &Apache::lonhtmlcommon::row_closure(1). 
                   11541:                &Apache::lonhtmlcommon::end_pick_box().
                   11542:                '<br />';
1.1253    raeburn  11543:     return ($output,1);
1.555     raeburn  11544: }
                   11545: 
1.612     raeburn  11546: sub user_rule_check {
1.615     raeburn  11547:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11548:     my ($response,%inst_response);
1.612     raeburn  11549:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11550:         if (keys(%{$usershash}) > 1) {
                   11551:             my (%by_username,%by_id,%userdoms);
                   11552:             my $checkid; 
                   11553:             if (ref($checks) eq 'HASH') {
                   11554:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11555:                     $checkid = 1;
                   11556:                 }
                   11557:             }
                   11558:             foreach my $user (keys(%{$usershash})) {
                   11559:                 my ($uname,$udom) = split(/:/,$user);
                   11560:                 if ($checkid) {
                   11561:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11562:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11563:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11564:                             $userdoms{$udom} = 1;
1.1227    raeburn  11565:                             if (ref($inst_results) eq 'HASH') {
                   11566:                                 $inst_results->{$uname.':'.$udom} = {};
                   11567:                             }
1.1226    raeburn  11568:                         }
                   11569:                     }
                   11570:                 } else {
                   11571:                     $by_username{$udom}{$uname} = 1;
                   11572:                     $userdoms{$udom} = 1;
1.1227    raeburn  11573:                     if (ref($inst_results) eq 'HASH') {
                   11574:                         $inst_results->{$uname.':'.$udom} = {};
                   11575:                     }
1.1226    raeburn  11576:                 }
                   11577:             }
                   11578:             foreach my $udom (keys(%userdoms)) {
                   11579:                 if (!$got_rules->{$udom}) {
                   11580:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11581:                                                              ['usercreation'],$udom);
                   11582:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11583:                         foreach my $item ('username','id') {
                   11584:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11585:                                 $$curr_rules{$udom}{$item} =
                   11586:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11587:                             }
                   11588:                         }
                   11589:                     }
                   11590:                     $got_rules->{$udom} = 1;
                   11591:                 }
1.612     raeburn  11592:             }
1.1226    raeburn  11593:             if ($checkid) {
                   11594:                 foreach my $udom (keys(%by_id)) {
                   11595:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11596:                     if ($outcome eq 'ok') {
1.1227    raeburn  11597:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11598:                             my $uname = $by_id{$udom}{$id};
                   11599:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11600:                         }
1.1226    raeburn  11601:                         if (ref($results) eq 'HASH') {
                   11602:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11603:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11604:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11605:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11606:                                 }
1.1226    raeburn  11607:                             }
                   11608:                         }
                   11609:                     }
1.612     raeburn  11610:                 }
1.615     raeburn  11611:             } else {
1.1226    raeburn  11612:                 foreach my $udom (keys(%by_username)) {
                   11613:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11614:                     if ($outcome eq 'ok') {
1.1227    raeburn  11615:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11616:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11617:                         }
1.1226    raeburn  11618:                         if (ref($results) eq 'HASH') {
                   11619:                             foreach my $uname (keys(%{$results})) {
                   11620:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11621:                             }
                   11622:                         }
                   11623:                     }
                   11624:                 }
1.612     raeburn  11625:             }
1.1226    raeburn  11626:         } elsif (keys(%{$usershash}) == 1) {
                   11627:             my $user = (keys(%{$usershash}))[0];
                   11628:             my ($uname,$udom) = split(/:/,$user);
                   11629:             if (($udom ne '') && ($uname ne '')) {
                   11630:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11631:                     if (ref($checks) eq 'HASH') {
                   11632:                         if (defined($checks->{'username'})) {
                   11633:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11634:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11635:                         } elsif (defined($checks->{'id'})) {
                   11636:                             if ($usershash->{$user}->{'id'} ne '') {
                   11637:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11638:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11639:                                                                   $usershash->{$user}->{'id'});
                   11640:                             } else {
                   11641:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11642:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11643:                             }
1.585     raeburn  11644:                         }
1.1226    raeburn  11645:                     } else {
                   11646:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11647:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11648:                        return;
                   11649:                     }
                   11650:                     if (!$got_rules->{$udom}) {
                   11651:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11652:                                                                  ['usercreation'],$udom);
                   11653:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11654:                             foreach my $item ('username','id') {
                   11655:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11656:                                    $$curr_rules{$udom}{$item} = 
                   11657:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11658:                                 }
                   11659:                             }
                   11660:                         }
                   11661:                         $got_rules->{$udom} = 1;
1.585     raeburn  11662:                     }
                   11663:                 }
1.1226    raeburn  11664:             } else {
                   11665:                 return;
                   11666:             }
                   11667:         } else {
                   11668:             return;
                   11669:         }
                   11670:         foreach my $user (keys(%{$usershash})) {
                   11671:             my ($uname,$udom) = split(/:/,$user);
                   11672:             next if (($udom eq '') || ($uname eq ''));
                   11673:             my $id;
1.1227    raeburn  11674:             if (ref($inst_results) eq 'HASH') {
                   11675:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11676:                     $id = $inst_results->{$user}->{'id'};
                   11677:                 }
                   11678:             }
                   11679:             if ($id eq '') { 
                   11680:                 if (ref($usershash->{$user})) {
                   11681:                     $id = $usershash->{$user}->{'id'};
                   11682:                 }
1.585     raeburn  11683:             }
1.612     raeburn  11684:             foreach my $item (keys(%{$checks})) {
                   11685:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11686:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11687:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11688:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11689:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11690:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11691:                                 if ($rule_check{$rule}) {
                   11692:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11693:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11694:                                         if (ref($inst_results) eq 'HASH') {
                   11695:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11696:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11697:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11698:                                                 } elsif ($item eq 'id') {
                   11699:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11700:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11701:                                                     }
1.615     raeburn  11702:                                                 }
1.612     raeburn  11703:                                             }
                   11704:                                         }
1.615     raeburn  11705:                                     }
                   11706:                                     last;
1.585     raeburn  11707:                                 }
                   11708:                             }
                   11709:                         }
                   11710:                     }
                   11711:                 }
                   11712:             }
                   11713:         }
                   11714:     }
1.612     raeburn  11715:     return;
                   11716: }
                   11717: 
                   11718: sub user_rule_formats {
                   11719:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11720:     my %text = ( 
                   11721:                  'username' => 'Usernames',
                   11722:                  'id'       => 'IDs',
                   11723:                );
                   11724:     my $output;
                   11725:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11726:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11727:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11728:             $output = '<br />'.
                   11729:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11730:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11731:                       ' <ul>';
1.612     raeburn  11732:             foreach my $rule (@{$ruleorder}) {
                   11733:                 if (ref($curr_rules) eq 'ARRAY') {
                   11734:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11735:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11736:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11737:                                         $rules->{$rule}{'desc'}.'</li>';
                   11738:                         }
                   11739:                     }
                   11740:                 }
                   11741:             }
                   11742:             $output .= '</ul>';
                   11743:         }
                   11744:     }
                   11745:     return $output;
                   11746: }
                   11747: 
                   11748: sub instrule_disallow_msg {
1.615     raeburn  11749:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11750:     my $response;
                   11751:     my %text = (
                   11752:                   item   => 'username',
                   11753:                   items  => 'usernames',
                   11754:                   match  => 'matches',
                   11755:                   do     => 'does',
                   11756:                   action => 'a username',
                   11757:                   one    => 'one',
                   11758:                );
                   11759:     if ($count > 1) {
                   11760:         $text{'item'} = 'usernames';
                   11761:         $text{'match'} ='match';
                   11762:         $text{'do'} = 'do';
                   11763:         $text{'action'} = 'usernames',
                   11764:         $text{'one'} = 'ones';
                   11765:     }
                   11766:     if ($checkitem eq 'id') {
                   11767:         $text{'items'} = 'IDs';
                   11768:         $text{'item'} = 'ID';
                   11769:         $text{'action'} = 'an ID';
1.615     raeburn  11770:         if ($count > 1) {
                   11771:             $text{'item'} = 'IDs';
                   11772:             $text{'action'} = 'IDs';
                   11773:         }
1.612     raeburn  11774:     }
1.674     bisitz   11775:     $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  11776:     if ($mode eq 'upload') {
                   11777:         if ($checkitem eq 'username') {
                   11778:             $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'}.");
                   11779:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11780:             $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  11781:         }
1.669     raeburn  11782:     } elsif ($mode eq 'selfcreate') {
                   11783:         if ($checkitem eq 'id') {
                   11784:             $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.");
                   11785:         }
1.615     raeburn  11786:     } else {
                   11787:         if ($checkitem eq 'username') {
                   11788:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11789:         } elsif ($checkitem eq 'id') {
                   11790:             $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.");
                   11791:         }
1.612     raeburn  11792:     }
                   11793:     return $response;
1.585     raeburn  11794: }
                   11795: 
1.624     raeburn  11796: sub personal_data_fieldtitles {
                   11797:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11798:                         id => 'Student/Employee ID',
                   11799:                         permanentemail => 'E-mail address',
                   11800:                         lastname => 'Last Name',
                   11801:                         firstname => 'First Name',
                   11802:                         middlename => 'Middle Name',
                   11803:                         generation => 'Generation',
                   11804:                         gen => 'Generation',
1.765     raeburn  11805:                         inststatus => 'Affiliation',
1.624     raeburn  11806:                    );
                   11807:     return %fieldtitles;
                   11808: }
                   11809: 
1.642     raeburn  11810: sub sorted_inst_types {
                   11811:     my ($dom) = @_;
1.1185    raeburn  11812:     my ($usertypes,$order);
                   11813:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11814:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11815:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11816:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11817:     } else {
                   11818:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11819:     }
1.642     raeburn  11820:     my $othertitle = &mt('All users');
                   11821:     if ($env{'request.course.id'}) {
1.668     raeburn  11822:         $othertitle  = &mt('Any users');
1.642     raeburn  11823:     }
                   11824:     my @types;
                   11825:     if (ref($order) eq 'ARRAY') {
                   11826:         @types = @{$order};
                   11827:     }
                   11828:     if (@types == 0) {
                   11829:         if (ref($usertypes) eq 'HASH') {
                   11830:             @types = sort(keys(%{$usertypes}));
                   11831:         }
                   11832:     }
                   11833:     if (keys(%{$usertypes}) > 0) {
                   11834:         $othertitle = &mt('Other users');
                   11835:     }
                   11836:     return ($othertitle,$usertypes,\@types);
                   11837: }
                   11838: 
1.645     raeburn  11839: sub get_institutional_codes {
1.1361    raeburn  11840:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11841: # Get complete list of course sections to update
                   11842:     my @currsections = ();
                   11843:     my @currxlists = ();
1.1361    raeburn  11844:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11845:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11846:     my $crskey = $crs.':'.$coursecode;
                   11847:     @{$unclutteredsec{$crskey}} = ();
                   11848:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11849: 
                   11850:     if ($$settings{'internal.sectionnums'} ne '') {
                   11851:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11852:     }
                   11853: 
                   11854:     if ($$settings{'internal.crosslistings'} ne '') {
                   11855:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11856:     }
                   11857: 
                   11858:     if (@currxlists > 0) {
1.1361    raeburn  11859:         foreach my $xl (@currxlists) {
                   11860:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11861:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11862:                     push(@{$allcourses},$1);
1.645     raeburn  11863:                     $$LC_code{$1} = $2;
                   11864:                 }
                   11865:             }
                   11866:         }
                   11867:     }
1.1361    raeburn  11868: 
1.645     raeburn  11869:     if (@currsections > 0) {
1.1361    raeburn  11870:         foreach my $sec (@currsections) {
                   11871:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11872:                 my $instsec = $1;
1.645     raeburn  11873:                 my $lc_sec = $2;
1.1361    raeburn  11874:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11875:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11876:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11877:                 }
                   11878:             }
                   11879:         }
                   11880:     }
                   11881: 
                   11882:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11883:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11884:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11885:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11886:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11887:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11888:                     push(@{$allcourses},$sec);
1.1361    raeburn  11889:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11890:                 }
                   11891:             }
                   11892:         }
                   11893:     }
                   11894:     return;
                   11895: }
                   11896: 
1.971     raeburn  11897: sub get_standard_codeitems {
                   11898:     return ('Year','Semester','Department','Number','Section');
                   11899: }
                   11900: 
1.112     bowersj2 11901: =pod
                   11902: 
1.780     raeburn  11903: =head1 Slot Helpers
                   11904: 
                   11905: =over 4
                   11906: 
                   11907: =item * sorted_slots()
                   11908: 
1.1040    raeburn  11909: Sorts an array of slot names in order of an optional sort key,
                   11910: default sort is by slot start time (earliest first). 
1.780     raeburn  11911: 
                   11912: Inputs:
                   11913: 
                   11914: =over 4
                   11915: 
                   11916: slotsarr  - Reference to array of unsorted slot names.
                   11917: 
                   11918: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11919: 
1.1040    raeburn  11920: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11921: 
1.549     albertel 11922: =back
                   11923: 
1.780     raeburn  11924: Returns:
                   11925: 
                   11926: =over 4
                   11927: 
1.1040    raeburn  11928: sorted   - An array of slot names sorted by a specified sort key 
                   11929:            (default sort key is start time of the slot).
1.780     raeburn  11930: 
                   11931: =back
                   11932: 
                   11933: =cut
                   11934: 
                   11935: 
                   11936: sub sorted_slots {
1.1040    raeburn  11937:     my ($slotsarr,$slots,$sortkey) = @_;
                   11938:     if ($sortkey eq '') {
                   11939:         $sortkey = 'starttime';
                   11940:     }
1.780     raeburn  11941:     my @sorted;
                   11942:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11943:         @sorted =
                   11944:             sort {
                   11945:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11946:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11947:                      }
                   11948:                      if (ref($slots->{$a})) { return -1;}
                   11949:                      if (ref($slots->{$b})) { return 1;}
                   11950:                      return 0;
                   11951:                  } @{$slotsarr};
                   11952:     }
                   11953:     return @sorted;
                   11954: }
                   11955: 
1.1040    raeburn  11956: =pod
                   11957: 
                   11958: =item * get_future_slots()
                   11959: 
                   11960: Inputs:
                   11961: 
                   11962: =over 4
                   11963: 
                   11964: cnum - course number
                   11965: 
                   11966: cdom - course domain
                   11967: 
                   11968: now - current UNIX time
                   11969: 
                   11970: symb - optional symb
                   11971: 
                   11972: =back
                   11973: 
                   11974: Returns:
                   11975: 
                   11976: =over 4
                   11977: 
                   11978: sorted_reservable - ref to array of student_schedulable slots currently 
                   11979:                     reservable, ordered by end date of reservation period.
                   11980: 
                   11981: reservable_now - ref to hash of student_schedulable slots currently
                   11982:                  reservable.
                   11983: 
                   11984:     Keys in inner hash are:
                   11985:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11986:     (b) endreserve: end date of reservation period.
                   11987:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11988:         selected.
1.1040    raeburn  11989: 
                   11990: sorted_future - ref to array of student_schedulable slots reservable in
                   11991:                 the future, ordered by start date of reservation period.
                   11992: 
                   11993: future_reservable - ref to hash of student_schedulable slots reservable
                   11994:                     in the future.
                   11995: 
                   11996:     Keys in inner hash are:
                   11997:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11998:     (b) startreserve: start date of reservation period.
                   11999:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12000:         selected.
1.1040    raeburn  12001: 
                   12002: =back
                   12003: 
                   12004: =cut
                   12005: 
                   12006: sub get_future_slots {
                   12007:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12008:     my $map;
                   12009:     if ($symb) {
                   12010:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12011:     }
1.1040    raeburn  12012:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12013:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12014:     foreach my $slot (keys(%slots)) {
                   12015:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12016:         if ($symb) {
1.1229    raeburn  12017:             if ($slots{$slot}->{'symb'} ne '') {
                   12018:                 my $canuse;
                   12019:                 my %oksymbs;
                   12020:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12021:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12022:                 if ($oksymbs{$symb}) {
                   12023:                     $canuse = 1;
                   12024:                 } else {
                   12025:                     foreach my $item (@slotsymbs) {
                   12026:                         if ($item =~ /\.(page|sequence)$/) {
                   12027:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12028:                             if (($map ne '') && ($map eq $sloturl)) {
                   12029:                                 $canuse = 1;
                   12030:                                 last;
                   12031:                             }
                   12032:                         }
                   12033:                     }
                   12034:                 }
                   12035:                 next unless ($canuse);
                   12036:             }
1.1040    raeburn  12037:         }
                   12038:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12039:             ($slots{$slot}->{'endtime'} > $now)) {
                   12040:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12041:                 my $userallowed = 0;
                   12042:                 if ($slots{$slot}->{'allowedsections'}) {
                   12043:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12044:                     if (!defined($env{'request.role.sec'})
                   12045:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12046:                         $userallowed=1;
                   12047:                     } else {
                   12048:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12049:                             $userallowed=1;
                   12050:                         }
                   12051:                     }
                   12052:                     unless ($userallowed) {
                   12053:                         if (defined($env{'request.course.groups'})) {
                   12054:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12055:                             foreach my $group (@groups) {
                   12056:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12057:                                     $userallowed=1;
                   12058:                                     last;
                   12059:                                 }
                   12060:                             }
                   12061:                         }
                   12062:                     }
                   12063:                 }
                   12064:                 if ($slots{$slot}->{'allowedusers'}) {
                   12065:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12066:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12067:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12068:                         $userallowed = 1;
                   12069:                     }
                   12070:                 }
                   12071:                 next unless($userallowed);
                   12072:             }
                   12073:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12074:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12075:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12076:             my $uniqueperiod;
                   12077:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12078:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12079:             }
1.1040    raeburn  12080:             if (($startreserve < $now) &&
                   12081:                 (!$endreserve || $endreserve > $now)) {
                   12082:                 my $lastres = $endreserve;
                   12083:                 if (!$lastres) {
                   12084:                     $lastres = $slots{$slot}->{'starttime'};
                   12085:                 }
                   12086:                 $reservable_now{$slot} = {
                   12087:                                            symb       => $symb,
1.1250    raeburn  12088:                                            endreserve => $lastres,
                   12089:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12090:                                          };
                   12091:             } elsif (($startreserve > $now) &&
                   12092:                      (!$endreserve || $endreserve > $startreserve)) {
                   12093:                 $future_reservable{$slot} = {
                   12094:                                               symb         => $symb,
1.1250    raeburn  12095:                                               startreserve => $startreserve,
                   12096:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12097:                                             };
                   12098:             }
                   12099:         }
                   12100:     }
                   12101:     my @unsorted_reservable = keys(%reservable_now);
                   12102:     if (@unsorted_reservable > 0) {
                   12103:         @sorted_reservable = 
                   12104:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12105:     }
                   12106:     my @unsorted_future = keys(%future_reservable);
                   12107:     if (@unsorted_future > 0) {
                   12108:         @sorted_future =
                   12109:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12110:     }
                   12111:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12112: }
1.780     raeburn  12113: 
                   12114: =pod
                   12115: 
1.1057    foxr     12116: =back
                   12117: 
1.549     albertel 12118: =head1 HTTP Helpers
                   12119: 
                   12120: =over 4
                   12121: 
1.648     raeburn  12122: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12123: 
1.258     albertel 12124: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12125: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12126: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12127: 
                   12128: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12129: $possible_names is an ref to an array of form element names.  As an example:
                   12130: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12131: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12132: 
                   12133: =cut
1.1       albertel 12134: 
1.6       albertel 12135: sub get_unprocessed_cgi {
1.25      albertel 12136:   my ($query,$possible_names)= @_;
1.26      matthew  12137:   # $Apache::lonxml::debug=1;
1.356     albertel 12138:   foreach my $pair (split(/&/,$query)) {
                   12139:     my ($name, $value) = split(/=/,$pair);
1.369     www      12140:     $name = &unescape($name);
1.25      albertel 12141:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12142:       $value =~ tr/+/ /;
                   12143:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12144:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12145:     }
1.16      harris41 12146:   }
1.6       albertel 12147: }
                   12148: 
1.112     bowersj2 12149: =pod
                   12150: 
1.648     raeburn  12151: =item * &cacheheader() 
1.112     bowersj2 12152: 
                   12153: returns cache-controlling header code
                   12154: 
                   12155: =cut
                   12156: 
1.7       albertel 12157: sub cacheheader {
1.258     albertel 12158:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12159:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12160:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12161:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12162:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12163:     return $output;
1.7       albertel 12164: }
                   12165: 
1.112     bowersj2 12166: =pod
                   12167: 
1.648     raeburn  12168: =item * &no_cache($r) 
1.112     bowersj2 12169: 
                   12170: specifies header code to not have cache
                   12171: 
                   12172: =cut
                   12173: 
1.9       albertel 12174: sub no_cache {
1.216     albertel 12175:     my ($r) = @_;
                   12176:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12177: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12178:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12179:     $r->no_cache(1);
                   12180:     $r->header_out("Expires" => $date);
                   12181:     $r->header_out("Pragma" => "no-cache");
1.123     www      12182: }
                   12183: 
                   12184: sub content_type {
1.181     albertel 12185:     my ($r,$type,$charset) = @_;
1.299     foxr     12186:     if ($r) {
                   12187: 	#  Note that printout.pl calls this with undef for $r.
                   12188: 	&no_cache($r);
                   12189:     }
1.258     albertel 12190:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12191:     unless ($charset) {
                   12192: 	$charset=&Apache::lonlocal::current_encoding;
                   12193:     }
                   12194:     if ($charset) { $type.='; charset='.$charset; }
                   12195:     if ($r) {
                   12196: 	$r->content_type($type);
                   12197:     } else {
                   12198: 	print("Content-type: $type\n\n");
                   12199:     }
1.9       albertel 12200: }
1.25      albertel 12201: 
1.112     bowersj2 12202: =pod
                   12203: 
1.648     raeburn  12204: =item * &add_to_env($name,$value) 
1.112     bowersj2 12205: 
1.258     albertel 12206: adds $name to the %env hash with value
1.112     bowersj2 12207: $value, if $name already exists, the entry is converted to an array
                   12208: reference and $value is added to the array.
                   12209: 
                   12210: =cut
                   12211: 
1.25      albertel 12212: sub add_to_env {
                   12213:   my ($name,$value)=@_;
1.258     albertel 12214:   if (defined($env{$name})) {
                   12215:     if (ref($env{$name})) {
1.25      albertel 12216:       #already have multiple values
1.258     albertel 12217:       push(@{ $env{$name} },$value);
1.25      albertel 12218:     } else {
                   12219:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12220:       my $first=$env{$name};
                   12221:       undef($env{$name});
                   12222:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12223:     }
                   12224:   } else {
1.258     albertel 12225:     $env{$name}=$value;
1.25      albertel 12226:   }
1.31      albertel 12227: }
1.149     albertel 12228: 
                   12229: =pod
                   12230: 
1.648     raeburn  12231: =item * &get_env_multiple($name) 
1.149     albertel 12232: 
1.258     albertel 12233: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12234: values may be defined and end up as an array ref.
                   12235: 
                   12236: returns an array of values
                   12237: 
                   12238: =cut
                   12239: 
                   12240: sub get_env_multiple {
                   12241:     my ($name) = @_;
                   12242:     my @values;
1.258     albertel 12243:     if (defined($env{$name})) {
1.149     albertel 12244:         # exists is it an array
1.258     albertel 12245:         if (ref($env{$name})) {
                   12246:             @values=@{ $env{$name} };
1.149     albertel 12247:         } else {
1.258     albertel 12248:             $values[0]=$env{$name};
1.149     albertel 12249:         }
                   12250:     }
                   12251:     return(@values);
                   12252: }
                   12253: 
1.1249    damieng  12254: # Looks at given dependencies, and returns something depending on the context.
                   12255: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12256: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12257: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12258: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12259: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   12260: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12261: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12262: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12263: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12264: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12265: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12266: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12267: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   12268: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12269: sub ask_for_embedded_content {
1.1249    damieng  12270:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12271:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12272:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12273:         %currsubfile,%unused,$rem);
1.1071    raeburn  12274:     my $counter = 0;
                   12275:     my $numnew = 0;
1.987     raeburn  12276:     my $numremref = 0;
                   12277:     my $numinvalid = 0;
                   12278:     my $numpathchg = 0;
                   12279:     my $numexisting = 0;
1.1071    raeburn  12280:     my $numunused = 0;
                   12281:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12282:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12283:     my $heading = &mt('Upload embedded files');
                   12284:     my $buttontext = &mt('Upload');
                   12285: 
1.1249    damieng  12286:     # fills these variables based on the context:
                   12287:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12288:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12289:     if ($env{'request.course.id'}) {
1.1123    raeburn  12290:         if ($actionurl eq '/adm/dependencies') {
                   12291:             $navmap = Apache::lonnavmaps::navmap->new();
                   12292:         }
                   12293:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12294:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12295:     }
1.1123    raeburn  12296:     if (($actionurl eq '/adm/portfolio') || 
                   12297:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12298:         my $current_path='/';
                   12299:         if ($env{'form.currentpath'}) {
                   12300:             $current_path = $env{'form.currentpath'};
                   12301:         }
                   12302:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12303:             $udom = $cdom;
                   12304:             $uname = $cnum;
1.984     raeburn  12305:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12306:         } else {
                   12307:             $udom = $env{'user.domain'};
                   12308:             $uname = $env{'user.name'};
                   12309:             $url = '/userfiles/portfolio';
                   12310:         }
1.987     raeburn  12311:         $toplevel = $url.'/';
1.984     raeburn  12312:         $url .= $current_path;
                   12313:         $getpropath = 1;
1.987     raeburn  12314:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12315:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12316:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12317:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12318:         $toplevel = $url;
1.984     raeburn  12319:         if ($rest ne '') {
1.987     raeburn  12320:             $url .= $rest;
                   12321:         }
                   12322:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12323:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12324:             $url = $args->{'docs_url'};
                   12325:             $toplevel = $url;
1.1084    raeburn  12326:             if ($args->{'context'} eq 'paste') {
                   12327:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12328:                 ($path) = 
                   12329:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12330:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12331:                 $fileloc =~ s{^/}{};
                   12332:             }
1.1071    raeburn  12333:         }
1.1084    raeburn  12334:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12335:         if ($env{'request.course.id'} ne '') {
                   12336:             if (ref($args) eq 'HASH') {
                   12337:                 $url = $args->{'docs_url'};
                   12338:                 $title = $args->{'docs_title'};
1.1126    raeburn  12339:                 $toplevel = $url; 
                   12340:                 unless ($toplevel =~ m{^/}) {
                   12341:                     $toplevel = "/$url";
                   12342:                 }
1.1085    raeburn  12343:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12344:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12345:                     $path = $1;
                   12346:                 } else {
                   12347:                     ($path) =
                   12348:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12349:                 }
1.1195    raeburn  12350:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12351:                     $fileloc = $toplevel;
                   12352:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12353:                     my ($udom,$uname,$fname) =
                   12354:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12355:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12356:                 } else {
                   12357:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12358:                 }
1.1071    raeburn  12359:                 $fileloc =~ s{^/}{};
                   12360:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12361:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12362:             }
1.987     raeburn  12363:         }
1.1123    raeburn  12364:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12365:         $udom = $cdom;
                   12366:         $uname = $cnum;
                   12367:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12368:         $toplevel = $url;
                   12369:         $path = $url;
                   12370:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12371:         $fileloc =~ s{^/}{};
1.987     raeburn  12372:     }
1.1249    damieng  12373:     
                   12374:     # parses the dependency paths to get some info
                   12375:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12376:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12377:     # (will be completed later)
                   12378:     # $mapping:
                   12379:     #   for external URLs: external URL -> external URL
                   12380:     #   for relative paths: clean path -> original path
                   12381:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12382:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12383:     foreach my $file (keys(%{$allfiles})) {
                   12384:         my $embed_file;
                   12385:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12386:             $embed_file = $1;
                   12387:         } else {
                   12388:             $embed_file = $file;
                   12389:         }
1.1158    raeburn  12390:         my ($absolutepath,$cleaned_file);
                   12391:         if ($embed_file =~ m{^\w+://}) {
                   12392:             $cleaned_file = $embed_file;
1.1147    raeburn  12393:             $newfiles{$cleaned_file} = 1;
                   12394:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12395:         } else {
1.1158    raeburn  12396:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12397:             if ($embed_file =~ m{^/}) {
                   12398:                 $absolutepath = $embed_file;
                   12399:             }
1.1147    raeburn  12400:             if ($cleaned_file =~ m{/}) {
                   12401:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12402:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12403:                 my $item = $fname;
                   12404:                 if ($path ne '') {
                   12405:                     $item = $path.'/'.$fname;
                   12406:                     $subdependencies{$path}{$fname} = 1;
                   12407:                 } else {
                   12408:                     $dependencies{$item} = 1;
                   12409:                 }
                   12410:                 if ($absolutepath) {
                   12411:                     $mapping{$item} = $absolutepath;
                   12412:                 } else {
                   12413:                     $mapping{$item} = $embed_file;
                   12414:                 }
                   12415:             } else {
                   12416:                 $dependencies{$embed_file} = 1;
                   12417:                 if ($absolutepath) {
1.1147    raeburn  12418:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12419:                 } else {
1.1147    raeburn  12420:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12421:                 }
                   12422:             }
1.984     raeburn  12423:         }
                   12424:     }
1.1249    damieng  12425:     
                   12426:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12427:     # and lists
                   12428:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12429:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12430:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12431:     #                                    the path had to be cleaned up
                   12432:     # $existing: hash clean path -> 1 if the file exists
                   12433:     # $numexisting: number of keys in $existing
                   12434:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12435:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12436:     #                                      dependency subdirectories that are
                   12437:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12438:     my $dirptr = 16384;
1.984     raeburn  12439:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12440:         $currsubfile{$path} = {};
1.1123    raeburn  12441:         if (($actionurl eq '/adm/portfolio') || 
                   12442:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12443:             my ($sublistref,$listerror) =
                   12444:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12445:             if (ref($sublistref) eq 'ARRAY') {
                   12446:                 foreach my $line (@{$sublistref}) {
                   12447:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12448:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12449:                 }
1.984     raeburn  12450:             }
1.987     raeburn  12451:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12452:             if (opendir(my $dir,$url.'/'.$path)) {
                   12453:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12454:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12455:             }
1.1084    raeburn  12456:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12457:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12458:                   ($args->{'context'} eq 'paste')) ||
                   12459:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12460:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12461:                 my $dir;
                   12462:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12463:                     $dir = $fileloc;
                   12464:                 } else {
                   12465:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12466:                 }
1.1071    raeburn  12467:                 if ($dir ne '') {
                   12468:                     my ($sublistref,$listerror) =
                   12469:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12470:                     if (ref($sublistref) eq 'ARRAY') {
                   12471:                         foreach my $line (@{$sublistref}) {
                   12472:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12473:                                 undef,$mtime)=split(/\&/,$line,12);
                   12474:                             unless (($testdir&$dirptr) ||
                   12475:                                     ($file_name =~ /^\.\.?$/)) {
                   12476:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12477:                             }
                   12478:                         }
                   12479:                     }
                   12480:                 }
1.984     raeburn  12481:             }
                   12482:         }
                   12483:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12484:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12485:                 my $item = $path.'/'.$file;
                   12486:                 unless ($mapping{$item} eq $item) {
                   12487:                     $pathchanges{$item} = 1;
                   12488:                 }
                   12489:                 $existing{$item} = 1;
                   12490:                 $numexisting ++;
                   12491:             } else {
                   12492:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12493:             }
                   12494:         }
1.1071    raeburn  12495:         if ($actionurl eq '/adm/dependencies') {
                   12496:             foreach my $path (keys(%currsubfile)) {
                   12497:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12498:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12499:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12500:                              next if (($rem ne '') &&
                   12501:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12502:                                        (ref($navmap) &&
                   12503:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12504:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12505:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12506:                              $unused{$path.'/'.$file} = 1; 
                   12507:                          }
                   12508:                     }
                   12509:                 }
                   12510:             }
                   12511:         }
1.984     raeburn  12512:     }
1.1249    damieng  12513:     
                   12514:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12515:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12516:     my %currfile;
1.1123    raeburn  12517:     if (($actionurl eq '/adm/portfolio') ||
                   12518:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12519:         my ($dirlistref,$listerror) =
                   12520:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12521:         if (ref($dirlistref) eq 'ARRAY') {
                   12522:             foreach my $line (@{$dirlistref}) {
                   12523:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12524:                 $currfile{$file_name} = 1;
                   12525:             }
1.984     raeburn  12526:         }
1.987     raeburn  12527:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12528:         if (opendir(my $dir,$url)) {
1.987     raeburn  12529:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12530:             map {$currfile{$_} = 1;} @dir_list;
                   12531:         }
1.1084    raeburn  12532:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12533:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12534:               ($args->{'context'} eq 'paste')) ||
                   12535:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12536:         if ($env{'request.course.id'} ne '') {
                   12537:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12538:             if ($dir ne '') {
                   12539:                 my ($dirlistref,$listerror) =
                   12540:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12541:                 if (ref($dirlistref) eq 'ARRAY') {
                   12542:                     foreach my $line (@{$dirlistref}) {
                   12543:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12544:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12545:                         unless (($testdir&$dirptr) ||
                   12546:                                 ($file_name =~ /^\.\.?$/)) {
                   12547:                             $currfile{$file_name} = [$size,$mtime];
                   12548:                         }
                   12549:                     }
                   12550:                 }
                   12551:             }
                   12552:         }
1.984     raeburn  12553:     }
1.1249    damieng  12554:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12555:     # are not in subdirectories, using $currfile
1.984     raeburn  12556:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12557:         if (exists($currfile{$file})) {
1.987     raeburn  12558:             unless ($mapping{$file} eq $file) {
                   12559:                 $pathchanges{$file} = 1;
                   12560:             }
                   12561:             $existing{$file} = 1;
                   12562:             $numexisting ++;
                   12563:         } else {
1.984     raeburn  12564:             $newfiles{$file} = 1;
                   12565:         }
                   12566:     }
1.1071    raeburn  12567:     foreach my $file (keys(%currfile)) {
                   12568:         unless (($file eq $filename) ||
                   12569:                 ($file eq $filename.'.bak') ||
                   12570:                 ($dependencies{$file})) {
1.1085    raeburn  12571:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12572:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12573:                     next if (($rem ne '') &&
                   12574:                              (($env{"httpref.$rem".$file} ne '') ||
                   12575:                               (ref($navmap) &&
                   12576:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12577:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12578:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12579:                 }
1.1085    raeburn  12580:             }
1.1071    raeburn  12581:             $unused{$file} = 1;
                   12582:         }
                   12583:     }
1.1249    damieng  12584:     
                   12585:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12586:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12587:         ($args->{'context'} eq 'paste')) {
                   12588:         $counter = scalar(keys(%existing));
                   12589:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12590:         return ($output,$counter,$numpathchg,\%existing);
                   12591:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12592:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12593:         $counter = scalar(keys(%existing));
                   12594:         $numpathchg = scalar(keys(%pathchanges));
                   12595:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12596:     }
1.1249    damieng  12597:     
                   12598:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12599:     
                   12600:     # $upload_output: missing dependencies (with upload form)
                   12601:     # $modify_output: uploaded dependencies (in use)
                   12602:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12603:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12604:         if ($actionurl eq '/adm/dependencies') {
                   12605:             next if ($embed_file =~ m{^\w+://});
                   12606:         }
1.660     raeburn  12607:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12608:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12609:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12610:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12611:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12612:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12613:         }
1.1123    raeburn  12614:         $upload_output .= '</td>';
1.1071    raeburn  12615:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12616:             $upload_output.='<td align="right">'.
                   12617:                             '<span class="LC_info LC_fontsize_medium">'.
                   12618:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12619:             $numremref++;
1.660     raeburn  12620:         } elsif ($args->{'error_on_invalid_names'}
                   12621:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12622:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12623:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12624:             $numinvalid++;
1.660     raeburn  12625:         } else {
1.1123    raeburn  12626:             $upload_output .= '<td>'.
                   12627:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12628:                                                      $embed_file,\%mapping,
1.1071    raeburn  12629:                                                      $allfiles,$codebase,'upload');
                   12630:             $counter ++;
                   12631:             $numnew ++;
1.987     raeburn  12632:         }
                   12633:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12634:     }
                   12635:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12636:         if ($actionurl eq '/adm/dependencies') {
                   12637:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12638:             $modify_output .= &start_data_table_row().
                   12639:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12640:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12641:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12642:                               '<td>'.$size.'</td>'.
                   12643:                               '<td>'.$mtime.'</td>'.
                   12644:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12645:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12646:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12647:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12648:                               &embedded_file_element('upload_embedded',$counter,
                   12649:                                                      $embed_file,\%mapping,
                   12650:                                                      $allfiles,$codebase,'modify').
                   12651:                               '</div></td>'.
                   12652:                               &end_data_table_row()."\n";
                   12653:             $counter ++;
                   12654:         } else {
                   12655:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12656:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12657:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12658:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12659:                               &Apache::loncommon::end_data_table_row()."\n";
                   12660:         }
                   12661:     }
                   12662:     my $delidx = $counter;
                   12663:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12664:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12665:         $delete_output .= &start_data_table_row().
                   12666:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12667:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12668:                           '<td>'.$size.'</td>'.
                   12669:                           '<td>'.$mtime.'</td>'.
                   12670:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12671:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12672:                           &embedded_file_element('upload_embedded',$delidx,
                   12673:                                                  $oldfile,\%mapping,$allfiles,
                   12674:                                                  $codebase,'delete').'</td>'.
                   12675:                           &end_data_table_row()."\n"; 
                   12676:         $numunused ++;
                   12677:         $delidx ++;
1.987     raeburn  12678:     }
                   12679:     if ($upload_output) {
                   12680:         $upload_output = &start_data_table().
                   12681:                          $upload_output.
                   12682:                          &end_data_table()."\n";
                   12683:     }
1.1071    raeburn  12684:     if ($modify_output) {
                   12685:         $modify_output = &start_data_table().
                   12686:                          &start_data_table_header_row().
                   12687:                          '<th>'.&mt('File').'</th>'.
                   12688:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12689:                          '<th>'.&mt('Modified').'</th>'.
                   12690:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12691:                          &end_data_table_header_row().
                   12692:                          $modify_output.
                   12693:                          &end_data_table()."\n";
                   12694:     }
                   12695:     if ($delete_output) {
                   12696:         $delete_output = &start_data_table().
                   12697:                          &start_data_table_header_row().
                   12698:                          '<th>'.&mt('File').'</th>'.
                   12699:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12700:                          '<th>'.&mt('Modified').'</th>'.
                   12701:                          '<th>'.&mt('Delete?').'</th>'.
                   12702:                          &end_data_table_header_row().
                   12703:                          $delete_output.
                   12704:                          &end_data_table()."\n";
                   12705:     }
1.987     raeburn  12706:     my $applies = 0;
                   12707:     if ($numremref) {
                   12708:         $applies ++;
                   12709:     }
                   12710:     if ($numinvalid) {
                   12711:         $applies ++;
                   12712:     }
                   12713:     if ($numexisting) {
                   12714:         $applies ++;
                   12715:     }
1.1071    raeburn  12716:     if ($counter || $numunused) {
1.987     raeburn  12717:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12718:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12719:                   $state.'<h3>'.$heading.'</h3>'; 
                   12720:         if ($actionurl eq '/adm/dependencies') {
                   12721:             if ($numnew) {
                   12722:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12723:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12724:                            $upload_output.'<br />'."\n";
                   12725:             }
                   12726:             if ($numexisting) {
                   12727:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12728:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12729:                            $modify_output.'<br />'."\n";
                   12730:                            $buttontext = &mt('Save changes');
                   12731:             }
                   12732:             if ($numunused) {
                   12733:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12734:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12735:                            $delete_output.'<br />'."\n";
                   12736:                            $buttontext = &mt('Save changes');
                   12737:             }
                   12738:         } else {
                   12739:             $output .= $upload_output.'<br />'."\n";
                   12740:         }
                   12741:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12742:                    $counter.'" />'."\n";
                   12743:         if ($actionurl eq '/adm/dependencies') { 
                   12744:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12745:                        $numnew.'" />'."\n";
                   12746:         } elsif ($actionurl eq '') {
1.987     raeburn  12747:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12748:         }
                   12749:     } elsif ($applies) {
                   12750:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12751:         if ($applies > 1) {
                   12752:             $output .=  
1.1123    raeburn  12753:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12754:             if ($numremref) {
                   12755:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12756:             }
                   12757:             if ($numinvalid) {
                   12758:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12759:             }
                   12760:             if ($numexisting) {
                   12761:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12762:             }
                   12763:             $output .= '</ul><br />';
                   12764:         } elsif ($numremref) {
                   12765:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12766:         } elsif ($numinvalid) {
                   12767:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12768:         } elsif ($numexisting) {
                   12769:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12770:         }
                   12771:         $output .= $upload_output.'<br />';
                   12772:     }
                   12773:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12774:     $chgcount = $counter;
1.987     raeburn  12775:     if (keys(%pathchanges) > 0) {
                   12776:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12777:             if ($counter) {
1.987     raeburn  12778:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12779:                                                   $embed_file,\%mapping,
1.1071    raeburn  12780:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12781:             } else {
                   12782:                 $pathchange_output .= 
                   12783:                     &start_data_table_row().
                   12784:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12785:                     $chgcount.'" checked="checked" /></td>'.
                   12786:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12787:                     '<td>'.$embed_file.
                   12788:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12789:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12790:                     '</td>'.&end_data_table_row();
1.660     raeburn  12791:             }
1.987     raeburn  12792:             $numpathchg ++;
                   12793:             $chgcount ++;
1.660     raeburn  12794:         }
                   12795:     }
1.1127    raeburn  12796:     if (($counter) || ($numunused)) {
1.987     raeburn  12797:         if ($numpathchg) {
                   12798:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12799:                        $numpathchg.'" />'."\n";
                   12800:         }
                   12801:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12802:             ($actionurl eq '/adm/imsimport')) {
                   12803:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12804:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12805:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12806:         } elsif ($actionurl eq '/adm/dependencies') {
                   12807:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12808:         }
1.1123    raeburn  12809:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12810:     } elsif ($numpathchg) {
                   12811:         my %pathchange = ();
                   12812:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12813:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12814:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12815:         }
1.987     raeburn  12816:     }
1.1071    raeburn  12817:     return ($output,$counter,$numpathchg);
1.987     raeburn  12818: }
                   12819: 
1.1147    raeburn  12820: =pod
                   12821: 
                   12822: =item * clean_path($name)
                   12823: 
                   12824: Performs clean-up of directories, subdirectories and filename in an
                   12825: embedded object, referenced in an HTML file which is being uploaded
                   12826: to a course or portfolio, where 
                   12827: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12828: checked.
                   12829: 
                   12830: Clean-up is similar to replacements in lonnet::clean_filename()
                   12831: except each / between sub-directory and next level is preserved.
                   12832: 
                   12833: =cut
                   12834: 
                   12835: sub clean_path {
                   12836:     my ($embed_file) = @_;
                   12837:     $embed_file =~s{^/+}{};
                   12838:     my @contents;
                   12839:     if ($embed_file =~ m{/}) {
                   12840:         @contents = split(/\//,$embed_file);
                   12841:     } else {
                   12842:         @contents = ($embed_file);
                   12843:     }
                   12844:     my $lastidx = scalar(@contents)-1;
                   12845:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12846:         $contents[$i]=~s{\\}{/}g;
                   12847:         $contents[$i]=~s/\s+/\_/g;
                   12848:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12849:         if ($i == $lastidx) {
                   12850:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12851:         }
                   12852:     }
                   12853:     if ($lastidx > 0) {
                   12854:         return join('/',@contents);
                   12855:     } else {
                   12856:         return $contents[0];
                   12857:     }
                   12858: }
                   12859: 
1.987     raeburn  12860: sub embedded_file_element {
1.1071    raeburn  12861:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12862:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12863:                    (ref($codebase) eq 'HASH'));
                   12864:     my $output;
1.1071    raeburn  12865:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12866:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12867:     }
                   12868:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12869:                &escape($embed_file).'" />';
                   12870:     unless (($context eq 'upload_embedded') && 
                   12871:             ($mapping->{$embed_file} eq $embed_file)) {
                   12872:         $output .='
                   12873:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12874:     }
                   12875:     my $attrib;
                   12876:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12877:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12878:     }
                   12879:     $output .=
                   12880:         "\n\t\t".
                   12881:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12882:         $attrib.'" />';
                   12883:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12884:         $output .=
                   12885:             "\n\t\t".
                   12886:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12887:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12888:     }
1.987     raeburn  12889:     return $output;
1.660     raeburn  12890: }
                   12891: 
1.1071    raeburn  12892: sub get_dependency_details {
                   12893:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12894:     my ($size,$mtime,$showsize,$showmtime);
                   12895:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12896:         if ($embed_file =~ m{/}) {
                   12897:             my ($path,$fname) = split(/\//,$embed_file);
                   12898:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12899:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12900:             }
                   12901:         } else {
                   12902:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12903:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12904:             }
                   12905:         }
                   12906:         $showsize = $size/1024.0;
                   12907:         $showsize = sprintf("%.1f",$showsize);
                   12908:         if ($mtime > 0) {
                   12909:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12910:         }
                   12911:     }
                   12912:     return ($showsize,$showmtime);
                   12913: }
                   12914: 
                   12915: sub ask_embedded_js {
                   12916:     return <<"END";
                   12917: <script type="text/javascript"">
                   12918: // <![CDATA[
                   12919: function toggleBrowse(counter) {
                   12920:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12921:     var fileid = document.getElementById('embedded_item_'+counter);
                   12922:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12923:     if (chkboxid.checked == true) {
                   12924:         uploaddivid.style.display='block';
                   12925:     } else {
                   12926:         uploaddivid.style.display='none';
                   12927:         fileid.value = '';
                   12928:     }
                   12929: }
                   12930: // ]]>
                   12931: </script>
                   12932: 
                   12933: END
                   12934: }
                   12935: 
1.661     raeburn  12936: sub upload_embedded {
                   12937:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12938:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12939:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12940:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12941:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12942:         my $orig_uploaded_filename =
                   12943:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12944:         foreach my $type ('orig','ref','attrib','codebase') {
                   12945:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12946:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12947:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12948:             }
                   12949:         }
1.661     raeburn  12950:         my ($path,$fname) =
                   12951:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12952:         # no path, whole string is fname
                   12953:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12954:         $fname = &Apache::lonnet::clean_filename($fname);
                   12955:         # See if there is anything left
                   12956:         next if ($fname eq '');
                   12957: 
                   12958:         # Check if file already exists as a file or directory.
                   12959:         my ($state,$msg);
                   12960:         if ($context eq 'portfolio') {
                   12961:             my $port_path = $dirpath;
                   12962:             if ($group ne '') {
                   12963:                 $port_path = "groups/$group/$port_path";
                   12964:             }
1.987     raeburn  12965:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12966:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12967:                                               $dir_root,$port_path,$disk_quota,
                   12968:                                               $current_disk_usage,$uname,$udom);
                   12969:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12970:                 || $state eq 'file_locked') {
1.661     raeburn  12971:                 $output .= $msg;
                   12972:                 next;
                   12973:             }
                   12974:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12975:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12976:             if ($state eq 'exists') {
                   12977:                 $output .= $msg;
                   12978:                 next;
                   12979:             }
                   12980:         }
                   12981:         # Check if extension is valid
                   12982:         if (($fname =~ /\.(\w+)$/) &&
                   12983:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12984:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12985:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12986:             next;
                   12987:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12988:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12989:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12990:             next;
                   12991:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12992:             $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  12993:             next;
                   12994:         }
                   12995:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12996:         my $subdir = $path;
                   12997:         $subdir =~ s{/+$}{};
1.661     raeburn  12998:         if ($context eq 'portfolio') {
1.984     raeburn  12999:             my $result;
                   13000:             if ($state eq 'existingfile') {
                   13001:                 $result=
                   13002:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13003:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13004:             } else {
1.984     raeburn  13005:                 $result=
                   13006:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13007:                                                     $dirpath.
1.1123    raeburn  13008:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13009:                 if ($result !~ m|^/uploaded/|) {
                   13010:                     $output .= '<span class="LC_error">'
                   13011:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13012:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13013:                                .'</span><br />';
                   13014:                     next;
                   13015:                 } else {
1.987     raeburn  13016:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13017:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13018:                 }
1.661     raeburn  13019:             }
1.1123    raeburn  13020:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13021:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13022:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13023:             my $result =
1.1126    raeburn  13024:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13025:             if ($result !~ m|^/uploaded/|) {
                   13026:                 $output .= '<span class="LC_error">'
                   13027:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13028:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13029:                            .'</span><br />';
                   13030:                     next;
                   13031:             } else {
                   13032:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13033:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13034:                 if ($context eq 'syllabus') {
                   13035:                     &Apache::lonnet::make_public_indefinitely($result);
                   13036:                 }
1.987     raeburn  13037:             }
1.661     raeburn  13038:         } else {
                   13039: # Save the file
                   13040:             my $target = $env{'form.embedded_item_'.$i};
                   13041:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13042:             my $dest = $fullpath.$fname;
                   13043:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13044:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13045:             my $count;
                   13046:             my $filepath = $dir_root;
1.1027    raeburn  13047:             foreach my $subdir (@parts) {
                   13048:                 $filepath .= "/$subdir";
                   13049:                 if (!-e $filepath) {
1.661     raeburn  13050:                     mkdir($filepath,0770);
                   13051:                 }
                   13052:             }
                   13053:             my $fh;
                   13054:             if (!open($fh,'>'.$dest)) {
                   13055:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13056:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13057:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13058:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13059:                            '</span><br />';
                   13060:             } else {
                   13061:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13062:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13063:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13064:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13065:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13066:                               '</span><br />';
                   13067:                 } else {
1.987     raeburn  13068:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13069:                                $url.'</span>').'<br />';
                   13070:                     unless ($context eq 'testbank') {
                   13071:                         $footer .= &mt('View embedded file: [_1]',
                   13072:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13073:                     }
                   13074:                 }
                   13075:                 close($fh);
                   13076:             }
                   13077:         }
                   13078:         if ($env{'form.embedded_ref_'.$i}) {
                   13079:             $pathchange{$i} = 1;
                   13080:         }
                   13081:     }
                   13082:     if ($output) {
                   13083:         $output = '<p>'.$output.'</p>';
                   13084:     }
                   13085:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13086:     $returnflag = 'ok';
1.1071    raeburn  13087:     my $numpathchgs = scalar(keys(%pathchange));
                   13088:     if ($numpathchgs > 0) {
1.987     raeburn  13089:         if ($context eq 'portfolio') {
                   13090:             $output .= '<p>'.&mt('or').'</p>';
                   13091:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13092:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13093:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13094:             $returnflag = 'modify_orightml';
                   13095:         }
                   13096:     }
1.1071    raeburn  13097:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13098: }
                   13099: 
                   13100: sub modify_html_form {
                   13101:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13102:     my $end = 0;
                   13103:     my $modifyform;
                   13104:     if ($context eq 'upload_embedded') {
                   13105:         return unless (ref($pathchange) eq 'HASH');
                   13106:         if ($env{'form.number_embedded_items'}) {
                   13107:             $end += $env{'form.number_embedded_items'};
                   13108:         }
                   13109:         if ($env{'form.number_pathchange_items'}) {
                   13110:             $end += $env{'form.number_pathchange_items'};
                   13111:         }
                   13112:         if ($end) {
                   13113:             for (my $i=0; $i<$end; $i++) {
                   13114:                 if ($i < $env{'form.number_embedded_items'}) {
                   13115:                     next unless($pathchange->{$i});
                   13116:                 }
                   13117:                 $modifyform .=
                   13118:                     &start_data_table_row().
                   13119:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13120:                     'checked="checked" /></td>'.
                   13121:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13122:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13123:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13124:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13125:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13126:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13127:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13128:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13129:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13130:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13131:                     &end_data_table_row();
1.1071    raeburn  13132:             }
1.987     raeburn  13133:         }
                   13134:     } else {
                   13135:         $modifyform = $pathchgtable;
                   13136:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13137:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13138:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13139:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13140:         }
                   13141:     }
                   13142:     if ($modifyform) {
1.1071    raeburn  13143:         if ($actionurl eq '/adm/dependencies') {
                   13144:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13145:         }
1.987     raeburn  13146:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13147:                '<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".
                   13148:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13149:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13150:                '</ol></p>'."\n".'<p>'.
                   13151:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13152:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13153:                &start_data_table()."\n".
                   13154:                &start_data_table_header_row().
                   13155:                '<th>'.&mt('Change?').'</th>'.
                   13156:                '<th>'.&mt('Current reference').'</th>'.
                   13157:                '<th>'.&mt('Required reference').'</th>'.
                   13158:                &end_data_table_header_row()."\n".
                   13159:                $modifyform.
                   13160:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13161:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13162:                '</form>'."\n";
                   13163:     }
                   13164:     return;
                   13165: }
                   13166: 
                   13167: sub modify_html_refs {
1.1123    raeburn  13168:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13169:     my $container;
                   13170:     if ($context eq 'portfolio') {
                   13171:         $container = $env{'form.container'};
                   13172:     } elsif ($context eq 'coursedoc') {
                   13173:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13174:     } elsif ($context eq 'manage_dependencies') {
                   13175:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13176:         $container = "/$container";
1.1123    raeburn  13177:     } elsif ($context eq 'syllabus') {
                   13178:         $container = $url;
1.987     raeburn  13179:     } else {
1.1027    raeburn  13180:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13181:     }
                   13182:     my (%allfiles,%codebase,$output,$content);
                   13183:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13184:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13185:         if (wantarray) {
                   13186:             return ('',0,0); 
                   13187:         } else {
                   13188:             return;
                   13189:         }
                   13190:     }
                   13191:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13192:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13193:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13194:             if (wantarray) {
                   13195:                 return ('',0,0);
                   13196:             } else {
                   13197:                 return;
                   13198:             }
                   13199:         } 
1.987     raeburn  13200:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13201:         if ($content eq '-1') {
                   13202:             if (wantarray) {
                   13203:                 return ('',0,0);
                   13204:             } else {
                   13205:                 return;
                   13206:             }
                   13207:         }
1.987     raeburn  13208:     } else {
1.1071    raeburn  13209:         unless ($container =~ /^\Q$dir_root\E/) {
                   13210:             if (wantarray) {
                   13211:                 return ('',0,0);
                   13212:             } else {
                   13213:                 return;
                   13214:             }
                   13215:         } 
1.1317    raeburn  13216:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13217:             $content = join('', <$fh>);
                   13218:             close($fh);
                   13219:         } else {
1.1071    raeburn  13220:             if (wantarray) {
                   13221:                 return ('',0,0);
                   13222:             } else {
                   13223:                 return;
                   13224:             }
1.987     raeburn  13225:         }
                   13226:     }
                   13227:     my ($count,$codebasecount) = (0,0);
                   13228:     my $mm = new File::MMagic;
                   13229:     my $mime_type = $mm->checktype_contents($content);
                   13230:     if ($mime_type eq 'text/html') {
                   13231:         my $parse_result = 
                   13232:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13233:                                                     \%codebase,\$content);
                   13234:         if ($parse_result eq 'ok') {
                   13235:             foreach my $i (@changes) {
                   13236:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13237:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13238:                 if ($allfiles{$ref}) {
                   13239:                     my $newname =  $orig;
                   13240:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13241:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13242:                     if ($attrib_regexp =~ /:/) {
                   13243:                         $attrib_regexp =~ s/\:/|/g;
                   13244:                     }
                   13245:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13246:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13247:                         $count += $numchg;
1.1123    raeburn  13248:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13249:                         delete($allfiles{$ref});
1.987     raeburn  13250:                     }
                   13251:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13252:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13253:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13254:                         $codebasecount ++;
                   13255:                     }
                   13256:                 }
                   13257:             }
1.1123    raeburn  13258:             my $skiprewrites;
1.987     raeburn  13259:             if ($count || $codebasecount) {
                   13260:                 my $saveresult;
1.1071    raeburn  13261:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13262:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13263:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13264:                     if ($url eq $container) {
                   13265:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13266:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13267:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13268:                                             $fname.'</span>').'</p>';
1.987     raeburn  13269:                     } else {
                   13270:                          $output = '<p class="LC_error">'.
                   13271:                                    &mt('Error: update failed for: [_1].',
                   13272:                                    '<span class="LC_filename">'.
                   13273:                                    $container.'</span>').'</p>';
                   13274:                     }
1.1123    raeburn  13275:                     if ($context eq 'syllabus') {
                   13276:                         unless ($saveresult eq 'ok') {
                   13277:                             $skiprewrites = 1;
                   13278:                         }
                   13279:                     }
1.987     raeburn  13280:                 } else {
1.1317    raeburn  13281:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13282:                         print $fh $content;
                   13283:                         close($fh);
                   13284:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13285:                                   $count,'<span class="LC_filename">'.
                   13286:                                   $container.'</span>').'</p>';
1.661     raeburn  13287:                     } else {
1.987     raeburn  13288:                          $output = '<p class="LC_error">'.
                   13289:                                    &mt('Error: could not update [_1].',
                   13290:                                    '<span class="LC_filename">'.
                   13291:                                    $container.'</span>').'</p>';
1.661     raeburn  13292:                     }
                   13293:                 }
                   13294:             }
1.1123    raeburn  13295:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13296:                 my ($actionurl,$state);
                   13297:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13298:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13299:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13300:                                               \%codebase,
                   13301:                                               {'context' => 'rewrites',
                   13302:                                                'ignore_remote_references' => 1,});
                   13303:                 if (ref($mapping) eq 'HASH') {
                   13304:                     my $rewrites = 0;
                   13305:                     foreach my $key (keys(%{$mapping})) {
                   13306:                         next if ($key =~ m{^https?://});
                   13307:                         my $ref = $mapping->{$key};
                   13308:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13309:                         my $attrib;
                   13310:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13311:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13312:                         }
                   13313:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13314:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13315:                             $rewrites += $numchg;
                   13316:                         }
                   13317:                     }
                   13318:                     if ($rewrites) {
                   13319:                         my $saveresult; 
                   13320:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13321:                         if ($url eq $container) {
                   13322:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13323:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13324:                                             $count,'<span class="LC_filename">'.
                   13325:                                             $fname.'</span>').'</p>';
                   13326:                         } else {
                   13327:                             $output .= '<p class="LC_error">'.
                   13328:                                        &mt('Error: could not update links in [_1].',
                   13329:                                        '<span class="LC_filename">'.
                   13330:                                        $container.'</span>').'</p>';
                   13331: 
                   13332:                         }
                   13333:                     }
                   13334:                 }
                   13335:             }
1.987     raeburn  13336:         } else {
                   13337:             &logthis('Failed to parse '.$container.
                   13338:                      ' to modify references: '.$parse_result);
1.661     raeburn  13339:         }
                   13340:     }
1.1071    raeburn  13341:     if (wantarray) {
                   13342:         return ($output,$count,$codebasecount);
                   13343:     } else {
                   13344:         return $output;
                   13345:     }
1.661     raeburn  13346: }
                   13347: 
                   13348: sub check_for_existing {
                   13349:     my ($path,$fname,$element) = @_;
                   13350:     my ($state,$msg);
                   13351:     if (-d $path.'/'.$fname) {
                   13352:         $state = 'exists';
                   13353:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13354:     } elsif (-e $path.'/'.$fname) {
                   13355:         $state = 'exists';
                   13356:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13357:     }
                   13358:     if ($state eq 'exists') {
                   13359:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13360:     }
                   13361:     return ($state,$msg);
                   13362: }
                   13363: 
                   13364: sub check_for_upload {
                   13365:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13366:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13367:     my $filesize = length($env{'form.'.$element});
                   13368:     if (!$filesize) {
                   13369:         my $msg = '<span class="LC_error">'.
                   13370:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13371:                       '<span class="LC_filename">'.$fname.'</span>',
                   13372:                       $filesize).'<br />'.
1.1007    raeburn  13373:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13374:                   '</span>';
                   13375:         return ('zero_bytes',$msg);
                   13376:     }
                   13377:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13378:     my $getpropath = 1;
1.1021    raeburn  13379:     my ($dirlistref,$listerror) =
                   13380:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13381:     my $found_file = 0;
                   13382:     my $locked_file = 0;
1.991     raeburn  13383:     my @lockers;
                   13384:     my $navmap;
                   13385:     if ($env{'request.course.id'}) {
                   13386:         $navmap = Apache::lonnavmaps::navmap->new();
                   13387:     }
1.1021    raeburn  13388:     if (ref($dirlistref) eq 'ARRAY') {
                   13389:         foreach my $line (@{$dirlistref}) {
                   13390:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13391:             if ($file_name eq $fname){
                   13392:                 $file_name = $path.$file_name;
                   13393:                 if ($group ne '') {
                   13394:                     $file_name = $group.$file_name;
                   13395:                 }
                   13396:                 $found_file = 1;
                   13397:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13398:                     foreach my $lock (@lockers) {
                   13399:                         if (ref($lock) eq 'ARRAY') {
                   13400:                             my ($symb,$crsid) = @{$lock};
                   13401:                             if ($crsid eq $env{'request.course.id'}) {
                   13402:                                 if (ref($navmap)) {
                   13403:                                     my $res = $navmap->getBySymb($symb);
                   13404:                                     foreach my $part (@{$res->parts()}) { 
                   13405:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13406:                                         unless (($slot_status == $res->RESERVED) ||
                   13407:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13408:                                             $locked_file = 1;
                   13409:                                         }
1.991     raeburn  13410:                                     }
1.1021    raeburn  13411:                                 } else {
                   13412:                                     $locked_file = 1;
1.991     raeburn  13413:                                 }
                   13414:                             } else {
                   13415:                                 $locked_file = 1;
                   13416:                             }
                   13417:                         }
1.1021    raeburn  13418:                    }
                   13419:                 } else {
                   13420:                     my @info = split(/\&/,$rest);
                   13421:                     my $currsize = $info[6]/1000;
                   13422:                     if ($currsize < $filesize) {
                   13423:                         my $extra = $filesize - $currsize;
                   13424:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13425:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13426:                                       &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.1179    bisitz   13427:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13428:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13429:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13430:                             return ('will_exceed_quota',$msg);
                   13431:                         }
1.984     raeburn  13432:                     }
                   13433:                 }
1.661     raeburn  13434:             }
                   13435:         }
                   13436:     }
                   13437:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13438:         my $msg = '<p class="LC_warning">'.
                   13439:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13440:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13441:         return ('will_exceed_quota',$msg);
                   13442:     } elsif ($found_file) {
                   13443:         if ($locked_file) {
1.1179    bisitz   13444:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13445:             $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.1179    bisitz   13446:             $msg .= '</p>';
1.661     raeburn  13447:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13448:             return ('file_locked',$msg);
                   13449:         } else {
1.1179    bisitz   13450:             my $msg = '<p class="LC_error">';
1.984     raeburn  13451:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   13452:             $msg .= '</p>';
1.984     raeburn  13453:             return ('existingfile',$msg);
1.661     raeburn  13454:         }
                   13455:     }
                   13456: }
                   13457: 
1.987     raeburn  13458: sub check_for_traversal {
                   13459:     my ($path,$url,$toplevel) = @_;
                   13460:     my @parts=split(/\//,$path);
                   13461:     my $cleanpath;
                   13462:     my $fullpath = $url;
                   13463:     for (my $i=0;$i<@parts;$i++) {
                   13464:         next if ($parts[$i] eq '.');
                   13465:         if ($parts[$i] eq '..') {
                   13466:             $fullpath =~ s{([^/]+/)$}{};
                   13467:         } else {
                   13468:             $fullpath .= $parts[$i].'/';
                   13469:         }
                   13470:     }
                   13471:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13472:         $cleanpath = $1;
                   13473:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13474:         my $curr_toprel = $1;
                   13475:         my @parts = split(/\//,$curr_toprel);
                   13476:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13477:         my @urlparts = split(/\//,$url_toprel);
                   13478:         my $doubledots;
                   13479:         my $startdiff = -1;
                   13480:         for (my $i=0; $i<@urlparts; $i++) {
                   13481:             if ($startdiff == -1) {
                   13482:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13483:                     $startdiff = $i;
                   13484:                     $doubledots .= '../';
                   13485:                 }
                   13486:             } else {
                   13487:                 $doubledots .= '../';
                   13488:             }
                   13489:         }
                   13490:         if ($startdiff > -1) {
                   13491:             $cleanpath = $doubledots;
                   13492:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13493:                 $cleanpath .= $parts[$i].'/';
                   13494:             }
                   13495:         }
                   13496:     }
                   13497:     $cleanpath =~ s{(/)$}{};
                   13498:     return $cleanpath;
                   13499: }
1.31      albertel 13500: 
1.1053    raeburn  13501: sub is_archive_file {
                   13502:     my ($mimetype) = @_;
                   13503:     if (($mimetype eq 'application/octet-stream') ||
                   13504:         ($mimetype eq 'application/x-stuffit') ||
                   13505:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13506:         return 1;
                   13507:     }
                   13508:     return;
                   13509: }
                   13510: 
                   13511: sub decompress_form {
1.1065    raeburn  13512:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13513:     my %lt = &Apache::lonlocal::texthash (
                   13514:         this => 'This file is an archive file.',
1.1067    raeburn  13515:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13516:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13517:         youm => 'You may wish to extract its contents.',
                   13518:         extr => 'Extract contents',
1.1067    raeburn  13519:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13520:         proa => 'Process automatically?',
1.1053    raeburn  13521:         yes  => 'Yes',
                   13522:         no   => 'No',
1.1067    raeburn  13523:         fold => 'Title for folder containing movie',
                   13524:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13525:     );
1.1065    raeburn  13526:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13527:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13528:     my $info = &list_archive_contents($fileloc,\@paths);
                   13529:     if (@paths) {
                   13530:         foreach my $path (@paths) {
                   13531:             $path =~ s{^/}{};
1.1067    raeburn  13532:             if ($path =~ m{^([^/]+)/$}) {
                   13533:                 $topdir = $1;
                   13534:             }
1.1065    raeburn  13535:             if ($path =~ m{^([^/]+)/}) {
                   13536:                 $toplevel{$1} = $path;
                   13537:             } else {
                   13538:                 $toplevel{$path} = $path;
                   13539:             }
                   13540:         }
                   13541:     }
1.1067    raeburn  13542:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13543:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13544:                         "$topdir/media/",
                   13545:                         "$topdir/media/$topdir.mp4",
                   13546:                         "$topdir/media/FirstFrame.png",
                   13547:                         "$topdir/media/player.swf",
                   13548:                         "$topdir/media/swfobject.js",
                   13549:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13550:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13551:                          "$topdir/$topdir.mp4",
                   13552:                          "$topdir/$topdir\_config.xml",
                   13553:                          "$topdir/$topdir\_controller.swf",
                   13554:                          "$topdir/$topdir\_embed.css",
                   13555:                          "$topdir/$topdir\_First_Frame.png",
                   13556:                          "$topdir/$topdir\_player.html",
                   13557:                          "$topdir/$topdir\_Thumbnails.png",
                   13558:                          "$topdir/playerProductInstall.swf",
                   13559:                          "$topdir/scripts/",
                   13560:                          "$topdir/scripts/config_xml.js",
                   13561:                          "$topdir/scripts/handlebars.js",
                   13562:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13563:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13564:                          "$topdir/scripts/modernizr.js",
                   13565:                          "$topdir/scripts/player-min.js",
                   13566:                          "$topdir/scripts/swfobject.js",
                   13567:                          "$topdir/skins/",
                   13568:                          "$topdir/skins/configuration_express.xml",
                   13569:                          "$topdir/skins/express_show/",
                   13570:                          "$topdir/skins/express_show/player-min.css",
                   13571:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13572:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13573:                          "$topdir/$topdir.mp4",
                   13574:                          "$topdir/$topdir\_config.xml",
                   13575:                          "$topdir/$topdir\_controller.swf",
                   13576:                          "$topdir/$topdir\_embed.css",
                   13577:                          "$topdir/$topdir\_First_Frame.png",
                   13578:                          "$topdir/$topdir\_player.html",
                   13579:                          "$topdir/$topdir\_Thumbnails.png",
                   13580:                          "$topdir/playerProductInstall.swf",
                   13581:                          "$topdir/scripts/",
                   13582:                          "$topdir/scripts/config_xml.js",
                   13583:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13584:                          "$topdir/skins/",
                   13585:                          "$topdir/skins/configuration_express.xml",
                   13586:                          "$topdir/skins/express_show/",
                   13587:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13588:                          "$topdir/skins/express_show/spritesheet.png",
                   13589:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13590:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13591:         if (@diffs == 0) {
1.1164    raeburn  13592:             $is_camtasia = 6;
                   13593:         } else {
1.1197    raeburn  13594:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13595:             if (@diffs == 0) {
                   13596:                 $is_camtasia = 8;
1.1197    raeburn  13597:             } else {
                   13598:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13599:                 if (@diffs == 0) {
                   13600:                     $is_camtasia = 8;
                   13601:                 }
1.1164    raeburn  13602:             }
1.1067    raeburn  13603:         }
                   13604:     }
                   13605:     my $output;
                   13606:     if ($is_camtasia) {
                   13607:         $output = <<"ENDCAM";
                   13608: <script type="text/javascript" language="Javascript">
                   13609: // <![CDATA[
                   13610: 
                   13611: function camtasiaToggle() {
                   13612:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13613:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13614:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13615:                 document.getElementById('camtasia_titles').style.display='block';
                   13616:             } else {
                   13617:                 document.getElementById('camtasia_titles').style.display='none';
                   13618:             }
                   13619:         }
                   13620:     }
                   13621:     return;
                   13622: }
                   13623: 
                   13624: // ]]>
                   13625: </script>
                   13626: <p>$lt{'camt'}</p>
                   13627: ENDCAM
1.1065    raeburn  13628:     } else {
1.1067    raeburn  13629:         $output = '<p>'.$lt{'this'};
                   13630:         if ($info eq '') {
                   13631:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13632:         } else {
                   13633:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13634:                        '<div><pre>'.$info.'</pre></div>';
                   13635:         }
1.1065    raeburn  13636:     }
1.1067    raeburn  13637:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13638:     my $duplicates;
                   13639:     my $num = 0;
                   13640:     if (ref($dirlist) eq 'ARRAY') {
                   13641:         foreach my $item (@{$dirlist}) {
                   13642:             if (ref($item) eq 'ARRAY') {
                   13643:                 if (exists($toplevel{$item->[0]})) {
                   13644:                     $duplicates .= 
                   13645:                         &start_data_table_row().
                   13646:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13647:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13648:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13649:                         'value="1" />'.&mt('Yes').'</label>'.
                   13650:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13651:                         '<td>'.$item->[0].'</td>';
                   13652:                     if ($item->[2]) {
                   13653:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13654:                     } else {
                   13655:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13656:                     }
                   13657:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13658:                                    '<td>'.
                   13659:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13660:                                    '</td>'.
                   13661:                                    &end_data_table_row();
                   13662:                     $num ++;
                   13663:                 }
                   13664:             }
                   13665:         }
                   13666:     }
                   13667:     my $itemcount;
                   13668:     if (@paths > 0) {
                   13669:         $itemcount = scalar(@paths);
                   13670:     } else {
                   13671:         $itemcount = 1;
                   13672:     }
1.1067    raeburn  13673:     if ($is_camtasia) {
                   13674:         $output .= $lt{'auto'}.'<br />'.
                   13675:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13676:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13677:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13678:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13679:                    $lt{'no'}.'</label></span><br />'.
                   13680:                    '<div id="camtasia_titles" style="display:block">'.
                   13681:                    &Apache::lonhtmlcommon::start_pick_box().
                   13682:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13683:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13684:                    &Apache::lonhtmlcommon::row_closure().
                   13685:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13686:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13687:                    &Apache::lonhtmlcommon::row_closure(1).
                   13688:                    &Apache::lonhtmlcommon::end_pick_box().
                   13689:                    '</div>';
                   13690:     }
1.1065    raeburn  13691:     $output .= 
                   13692:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13693:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13694:         "\n";
1.1065    raeburn  13695:     if ($duplicates ne '') {
                   13696:         $output .= '<p><span class="LC_warning">'.
                   13697:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13698:                    &start_data_table().
                   13699:                    &start_data_table_header_row().
                   13700:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13701:                    '<th>'.&mt('Name').'</th>'.
                   13702:                    '<th>'.&mt('Type').'</th>'.
                   13703:                    '<th>'.&mt('Size').'</th>'.
                   13704:                    '<th>'.&mt('Last modified').'</th>'.
                   13705:                    &end_data_table_header_row().
                   13706:                    $duplicates.
                   13707:                    &end_data_table().
                   13708:                    '</p>';
                   13709:     }
1.1067    raeburn  13710:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13711:     if (ref($hiddenelements) eq 'HASH') {
                   13712:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13713:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13714:         }
                   13715:     }
                   13716:     $output .= <<"END";
1.1067    raeburn  13717: <br />
1.1053    raeburn  13718: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13719: </form>
                   13720: $noextract
                   13721: END
                   13722:     return $output;
                   13723: }
                   13724: 
1.1065    raeburn  13725: sub decompression_utility {
                   13726:     my ($program) = @_;
                   13727:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13728:     my $location;
                   13729:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13730:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13731:                          '/usr/sbin/') {
                   13732:             if (-x $dir.$program) {
                   13733:                 $location = $dir.$program;
                   13734:                 last;
                   13735:             }
                   13736:         }
                   13737:     }
                   13738:     return $location;
                   13739: }
                   13740: 
                   13741: sub list_archive_contents {
                   13742:     my ($file,$pathsref) = @_;
                   13743:     my (@cmd,$output);
                   13744:     my $needsregexp;
                   13745:     if ($file =~ /\.zip$/) {
                   13746:         @cmd = (&decompression_utility('unzip'),"-l");
                   13747:         $needsregexp = 1;
                   13748:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13749:              ($file =~ /\.tgz$/)) {
                   13750:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13751:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13752:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13753:     } elsif ($file =~ m|\.tar$|) {
                   13754:         @cmd = (&decompression_utility('tar'),"-tf");
                   13755:     }
                   13756:     if (@cmd) {
                   13757:         undef($!);
                   13758:         undef($@);
                   13759:         if (open(my $fh,"-|", @cmd, $file)) {
                   13760:             while (my $line = <$fh>) {
                   13761:                 $output .= $line;
                   13762:                 chomp($line);
                   13763:                 my $item;
                   13764:                 if ($needsregexp) {
                   13765:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13766:                 } else {
                   13767:                     $item = $line;
                   13768:                 }
                   13769:                 if ($item ne '') {
                   13770:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13771:                         push(@{$pathsref},$item);
                   13772:                     } 
                   13773:                 }
                   13774:             }
                   13775:             close($fh);
                   13776:         }
                   13777:     }
                   13778:     return $output;
                   13779: }
                   13780: 
1.1053    raeburn  13781: sub decompress_uploaded_file {
                   13782:     my ($file,$dir) = @_;
                   13783:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13784:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13785:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13786:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13787:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13788:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13789:     my $decompressed = $env{'cgi.decompressed'};
                   13790:     &Apache::lonnet::delenv('cgi.file');
                   13791:     &Apache::lonnet::delenv('cgi.dir');
                   13792:     &Apache::lonnet::delenv('cgi.decompressed');
                   13793:     return ($decompressed,$result);
                   13794: }
                   13795: 
1.1055    raeburn  13796: sub process_decompression {
                   13797:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13798:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13799:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13800:                &mt('Unexpected file path.').'</p>'."\n";
                   13801:     }
                   13802:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13803:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13804:                &mt('Unexpected course context.').'</p>'."\n";
                   13805:     }
1.1293    raeburn  13806:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13807:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13808:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13809:     }
1.1055    raeburn  13810:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13811:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13812:         $error = &mt('Filename not a supported archive file type.').
                   13813:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13814:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13815:     } else {
                   13816:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13817:         if ($docuhome eq 'no_host') {
                   13818:             $error = &mt('Could not determine home server for course.');
                   13819:         } else {
                   13820:             my @ids=&Apache::lonnet::current_machine_ids();
                   13821:             my $currdir = "$dir_root/$destination";
                   13822:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13823:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13824:                        "$dir_root/$destination";
                   13825:             } else {
                   13826:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13827:                        "$dir_root/$docudom/$docuname/$destination";
                   13828:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13829:                     $error = &mt('Archive file not found.');
                   13830:                 }
                   13831:             }
1.1065    raeburn  13832:             my (@to_overwrite,@to_skip);
                   13833:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13834:                 my $total = $env{'form.archive_overwrite_total'};
                   13835:                 for (my $i=0; $i<$total; $i++) {
                   13836:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13837:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13838:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13839:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13840:                     }
                   13841:                 }
                   13842:             }
                   13843:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13844:             my $numoverwrite = scalar(@to_overwrite);
                   13845:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13846:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13847:             } elsif ($dir eq '') {
1.1055    raeburn  13848:                 $error = &mt('Directory containing archive file unavailable.');
                   13849:             } elsif (!$error) {
1.1065    raeburn  13850:                 my ($decompressed,$display);
1.1292    raeburn  13851:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13852:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13853:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13854:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13855:                         ($decompressed,$display) = 
                   13856:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13857:                         foreach my $item (@to_skip) {
                   13858:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13859:                                 if (-f "$dir/$tempdir/$item") { 
                   13860:                                     unlink("$dir/$tempdir/$item");
                   13861:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13862:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13863:                                 }
                   13864:                             }
                   13865:                         }
                   13866:                         foreach my $item (@to_overwrite) {
                   13867:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13868:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13869:                                     if (-f "$dir/$item") {
                   13870:                                         unlink("$dir/$item");
                   13871:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13872:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13873:                                     }
                   13874:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13875:                                 }
1.1065    raeburn  13876:                             }
                   13877:                         }
1.1292    raeburn  13878:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13879:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13880:                         }
1.1065    raeburn  13881:                     }
                   13882:                 } else {
                   13883:                     ($decompressed,$display) = 
                   13884:                         &decompress_uploaded_file($file,$dir);
                   13885:                 }
1.1055    raeburn  13886:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13887:                     $output = '<p class="LC_info">'.
                   13888:                               &mt('Files extracted successfully from archive.').
                   13889:                               '</p>'."\n";
1.1055    raeburn  13890:                     my ($warning,$result,@contents);
                   13891:                     my ($newdirlistref,$newlisterror) =
                   13892:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13893:                                                  $docuname,1);
                   13894:                     my (%is_dir,%changes,@newitems);
                   13895:                     my $dirptr = 16384;
1.1065    raeburn  13896:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13897:                         foreach my $dir_line (@{$newdirlistref}) {
                   13898:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13899:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13900:                                 push(@newitems,$item);
                   13901:                                 if ($dirptr&$testdir) {
                   13902:                                     $is_dir{$item} = 1;
                   13903:                                 }
                   13904:                                 $changes{$item} = 1;
                   13905:                             }
                   13906:                         }
                   13907:                     }
                   13908:                     if (keys(%changes) > 0) {
                   13909:                         foreach my $item (sort(@newitems)) {
                   13910:                             if ($changes{$item}) {
                   13911:                                 push(@contents,$item);
                   13912:                             }
                   13913:                         }
                   13914:                     }
                   13915:                     if (@contents > 0) {
1.1067    raeburn  13916:                         my $wantform;
                   13917:                         unless ($env{'form.autoextract_camtasia'}) {
                   13918:                             $wantform = 1;
                   13919:                         }
1.1056    raeburn  13920:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13921:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13922:                                                                 $currdir,\%is_dir,
                   13923:                                                                 \%children,\%parent,
1.1056    raeburn  13924:                                                                 \@contents,\%dirorder,
                   13925:                                                                 \%titles,$wantform);
1.1055    raeburn  13926:                         if ($datatable ne '') {
                   13927:                             $output .= &archive_options_form('decompressed',$datatable,
                   13928:                                                              $count,$hiddenelem);
1.1065    raeburn  13929:                             my $startcount = 6;
1.1055    raeburn  13930:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13931:                                                            \%titles,\%children);
1.1055    raeburn  13932:                         }
1.1067    raeburn  13933:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13934:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13935:                             my %displayed;
                   13936:                             my $total = 1;
                   13937:                             $env{'form.archive_directory'} = [];
                   13938:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13939:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13940:                                 $path =~ s{/$}{};
                   13941:                                 my $item;
                   13942:                                 if ($path ne '') {
                   13943:                                     $item = "$path/$titles{$i}";
                   13944:                                 } else {
                   13945:                                     $item = $titles{$i};
                   13946:                                 }
                   13947:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13948:                                 if ($item eq $contents[0]) {
                   13949:                                     push(@{$env{'form.archive_directory'}},$i);
                   13950:                                     $env{'form.archive_'.$i} = 'display';
                   13951:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13952:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13953:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13954:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13955:                                     $env{'form.archive_'.$i} = 'display';
                   13956:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13957:                                     $displayed{'web'} = $i;
                   13958:                                 } else {
1.1164    raeburn  13959:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13960:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13961:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13962:                                         push(@{$env{'form.archive_directory'}},$i);
                   13963:                                     }
                   13964:                                     $env{'form.archive_'.$i} = 'dependency';
                   13965:                                 }
                   13966:                                 $total ++;
                   13967:                             }
                   13968:                             for (my $i=1; $i<$total; $i++) {
                   13969:                                 next if ($i == $displayed{'web'});
                   13970:                                 next if ($i == $displayed{'folder'});
                   13971:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13972:                             }
                   13973:                             $env{'form.phase'} = 'decompress_cleanup';
                   13974:                             $env{'form.archivedelete'} = 1;
                   13975:                             $env{'form.archive_count'} = $total-1;
                   13976:                             $output .=
                   13977:                                 &process_extracted_files('coursedocs',$docudom,
                   13978:                                                          $docuname,$destination,
                   13979:                                                          $dir_root,$hiddenelem);
                   13980:                         }
1.1055    raeburn  13981:                     } else {
                   13982:                         $warning = &mt('No new items extracted from archive file.');
                   13983:                     }
                   13984:                 } else {
                   13985:                     $output = $display;
                   13986:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13987:                 }
                   13988:             }
                   13989:         }
                   13990:     }
                   13991:     if ($error) {
                   13992:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13993:                    $error.'</p>'."\n";
                   13994:     }
                   13995:     if ($warning) {
                   13996:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13997:     }
                   13998:     return $output;
                   13999: }
                   14000: 
                   14001: sub get_extracted {
1.1056    raeburn  14002:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14003:         $titles,$wantform) = @_;
1.1055    raeburn  14004:     my $count = 0;
                   14005:     my $depth = 0;
                   14006:     my $datatable;
1.1056    raeburn  14007:     my @hierarchy;
1.1055    raeburn  14008:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14009:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14010:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14011:     foreach my $item (@{$contents}) {
                   14012:         $count ++;
1.1056    raeburn  14013:         @{$dirorder->{$count}} = @hierarchy;
                   14014:         $titles->{$count} = $item;
1.1055    raeburn  14015:         &archive_hierarchy($depth,$count,$parent,$children);
                   14016:         if ($wantform) {
                   14017:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14018:                                        $currdir,$depth,$count);
                   14019:         }
                   14020:         if ($is_dir->{$item}) {
                   14021:             $depth ++;
1.1056    raeburn  14022:             push(@hierarchy,$count);
                   14023:             $parent->{$depth} = $count;
1.1055    raeburn  14024:             $datatable .=
                   14025:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14026:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14027:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14028:             $depth --;
1.1056    raeburn  14029:             pop(@hierarchy);
1.1055    raeburn  14030:         }
                   14031:     }
                   14032:     return ($count,$datatable);
                   14033: }
                   14034: 
                   14035: sub recurse_extracted_archive {
1.1056    raeburn  14036:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14037:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14038:     my $result='';
1.1056    raeburn  14039:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14040:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14041:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14042:         return $result;
                   14043:     }
                   14044:     my $dirptr = 16384;
                   14045:     my ($newdirlistref,$newlisterror) =
                   14046:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14047:     if (ref($newdirlistref) eq 'ARRAY') {
                   14048:         foreach my $dir_line (@{$newdirlistref}) {
                   14049:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14050:             unless ($item =~ /^\.+$/) {
                   14051:                 $$count ++;
1.1056    raeburn  14052:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14053:                 $titles->{$$count} = $item;
1.1055    raeburn  14054:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14055: 
1.1055    raeburn  14056:                 my $is_dir;
                   14057:                 if ($dirptr&$testdir) {
                   14058:                     $is_dir = 1;
                   14059:                 }
                   14060:                 if ($wantform) {
                   14061:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14062:                 }
                   14063:                 if ($is_dir) {
                   14064:                     $$depth ++;
1.1056    raeburn  14065:                     push(@{$hierarchy},$$count);
                   14066:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14067:                     $result .=
                   14068:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14069:                                                    $docuname,$depth,$count,
1.1056    raeburn  14070:                                                    $hierarchy,$dirorder,$children,
                   14071:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14072:                     $$depth --;
1.1056    raeburn  14073:                     pop(@{$hierarchy});
1.1055    raeburn  14074:                 }
                   14075:             }
                   14076:         }
                   14077:     }
                   14078:     return $result;
                   14079: }
                   14080: 
                   14081: sub archive_hierarchy {
                   14082:     my ($depth,$count,$parent,$children) =@_;
                   14083:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14084:         if (exists($parent->{$depth})) {
                   14085:              $children->{$parent->{$depth}} .= $count.':';
                   14086:         }
                   14087:     }
                   14088:     return;
                   14089: }
                   14090: 
                   14091: sub archive_row {
                   14092:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14093:     my ($name) = ($item =~ m{([^/]+)$});
                   14094:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14095:                                        'display'    => 'Add as file',
1.1055    raeburn  14096:                                        'dependency' => 'Include as dependency',
                   14097:                                        'discard'    => 'Discard',
                   14098:                                       );
                   14099:     if ($is_dir) {
1.1059    raeburn  14100:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14101:     }
1.1056    raeburn  14102:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14103:     my $offset = 0;
1.1055    raeburn  14104:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14105:         $offset ++;
1.1065    raeburn  14106:         if ($action ne 'display') {
                   14107:             $offset ++;
                   14108:         }  
1.1055    raeburn  14109:         $output .= '<td><span class="LC_nobreak">'.
                   14110:                    '<label><input type="radio" name="archive_'.$count.
                   14111:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14112:         my $text = $choices{$action};
                   14113:         if ($is_dir) {
                   14114:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14115:             if ($action eq 'display') {
1.1059    raeburn  14116:                 $text = &mt('Add as folder');
1.1055    raeburn  14117:             }
1.1056    raeburn  14118:         } else {
                   14119:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14120: 
                   14121:         }
                   14122:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14123:         if ($action eq 'dependency') {
                   14124:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14125:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14126:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14127:                        '<option value=""></option>'."\n".
                   14128:                        '</select>'."\n".
                   14129:                        '</div>';
1.1059    raeburn  14130:         } elsif ($action eq 'display') {
                   14131:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14132:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14133:                        '</div>';
1.1055    raeburn  14134:         }
1.1056    raeburn  14135:         $output .= '</td>';
1.1055    raeburn  14136:     }
                   14137:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14138:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14139:     for (my $i=0; $i<$depth; $i++) {
                   14140:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14141:     }
                   14142:     if ($is_dir) {
                   14143:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14144:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14145:     } else {
                   14146:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14147:     }
                   14148:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14149:                &end_data_table_row();
                   14150:     return $output;
                   14151: }
                   14152: 
                   14153: sub archive_options_form {
1.1065    raeburn  14154:     my ($form,$display,$count,$hiddenelem) = @_;
                   14155:     my %lt = &Apache::lonlocal::texthash(
                   14156:                perm => 'Permanently remove archive file?',
                   14157:                hows => 'How should each extracted item be incorporated in the course?',
                   14158:                cont => 'Content actions for all',
                   14159:                addf => 'Add as folder/file',
                   14160:                incd => 'Include as dependency for a displayed file',
                   14161:                disc => 'Discard',
                   14162:                no   => 'No',
                   14163:                yes  => 'Yes',
                   14164:                save => 'Save',
                   14165:     );
                   14166:     my $output = <<"END";
                   14167: <form name="$form" method="post" action="">
                   14168: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14169: <label>
                   14170:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14171: </label>
                   14172: &nbsp;
                   14173: <label>
                   14174:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14175: </span>
                   14176: </p>
                   14177: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14178: <br />$lt{'hows'}
                   14179: <div class="LC_columnSection">
                   14180:   <fieldset>
                   14181:     <legend>$lt{'cont'}</legend>
                   14182:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14183:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14184:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14185:   </fieldset>
                   14186: </div>
                   14187: END
                   14188:     return $output.
1.1055    raeburn  14189:            &start_data_table()."\n".
1.1065    raeburn  14190:            $display."\n".
1.1055    raeburn  14191:            &end_data_table()."\n".
                   14192:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14193:            $hiddenelem.
1.1065    raeburn  14194:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14195:            '</form>';
                   14196: }
                   14197: 
                   14198: sub archive_javascript {
1.1056    raeburn  14199:     my ($startcount,$numitems,$titles,$children) = @_;
                   14200:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14201:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14202:     my $scripttag = <<START;
                   14203: <script type="text/javascript">
                   14204: // <![CDATA[
                   14205: 
                   14206: function checkAll(form,prefix) {
                   14207:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14208:     for (var i=0; i < form.elements.length; i++) {
                   14209:         var id = form.elements[i].id;
                   14210:         if ((id != '') && (id != undefined)) {
                   14211:             if (idstr.test(id)) {
                   14212:                 if (form.elements[i].type == 'radio') {
                   14213:                     form.elements[i].checked = true;
1.1056    raeburn  14214:                     var nostart = i-$startcount;
1.1059    raeburn  14215:                     var offset = nostart%7;
                   14216:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14217:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14218:                 }
                   14219:             }
                   14220:         }
                   14221:     }
                   14222: }
                   14223: 
                   14224: function propagateCheck(form,count) {
                   14225:     if (count > 0) {
1.1059    raeburn  14226:         var startelement = $startcount + ((count-1) * 7);
                   14227:         for (var j=1; j<6; j++) {
                   14228:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14229:                 var item = startelement + j; 
                   14230:                 if (form.elements[item].type == 'radio') {
                   14231:                     if (form.elements[item].checked) {
                   14232:                         containerCheck(form,count,j);
                   14233:                         break;
                   14234:                     }
1.1055    raeburn  14235:                 }
                   14236:             }
                   14237:         }
                   14238:     }
                   14239: }
                   14240: 
                   14241: numitems = $numitems
1.1056    raeburn  14242: var titles = new Array(numitems);
                   14243: var parents = new Array(numitems);
1.1055    raeburn  14244: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14245:     parents[i] = new Array;
1.1055    raeburn  14246: }
1.1059    raeburn  14247: var maintitle = '$maintitle';
1.1055    raeburn  14248: 
                   14249: START
                   14250: 
1.1056    raeburn  14251:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14252:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14253:         for (my $i=0; $i<@contents; $i ++) {
                   14254:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14255:         }
                   14256:     }
                   14257: 
1.1056    raeburn  14258:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14259:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14260:     }
                   14261: 
1.1055    raeburn  14262:     $scripttag .= <<END;
                   14263: 
                   14264: function containerCheck(form,count,offset) {
                   14265:     if (count > 0) {
1.1056    raeburn  14266:         dependencyCheck(form,count,offset);
1.1059    raeburn  14267:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14268:         form.elements[item].checked = true;
                   14269:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14270:             if (parents[count].length > 0) {
                   14271:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14272:                     containerCheck(form,parents[count][j],offset);
                   14273:                 }
                   14274:             }
                   14275:         }
                   14276:     }
                   14277: }
                   14278: 
                   14279: function dependencyCheck(form,count,offset) {
                   14280:     if (count > 0) {
1.1059    raeburn  14281:         var chosen = (offset+$startcount)+7*(count-1);
                   14282:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14283:         var currtype = form.elements[depitem].type;
                   14284:         if (form.elements[chosen].value == 'dependency') {
                   14285:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14286:             form.elements[depitem].options.length = 0;
                   14287:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14288:             for (var i=1; i<=numitems; i++) {
                   14289:                 if (i == count) {
                   14290:                     continue;
                   14291:                 }
1.1059    raeburn  14292:                 var startelement = $startcount + (i-1) * 7;
                   14293:                 for (var j=1; j<6; j++) {
                   14294:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14295:                         var item = startelement + j;
                   14296:                         if (form.elements[item].type == 'radio') {
                   14297:                             if (form.elements[item].checked) {
                   14298:                                 if (form.elements[item].value == 'display') {
                   14299:                                     var n = form.elements[depitem].options.length;
                   14300:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14301:                                 }
                   14302:                             }
                   14303:                         }
                   14304:                     }
                   14305:                 }
                   14306:             }
                   14307:         } else {
                   14308:             document.getElementById('arc_depon_'+count).style.display='none';
                   14309:             form.elements[depitem].options.length = 0;
                   14310:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14311:         }
1.1059    raeburn  14312:         titleCheck(form,count,offset);
1.1056    raeburn  14313:     }
                   14314: }
                   14315: 
                   14316: function propagateSelect(form,count,offset) {
                   14317:     if (count > 0) {
1.1065    raeburn  14318:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14319:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14320:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14321:             if (parents[count].length > 0) {
                   14322:                 for (var j=0; j<parents[count].length; j++) {
                   14323:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14324:                 }
                   14325:             }
                   14326:         }
                   14327:     }
                   14328: }
1.1056    raeburn  14329: 
                   14330: function containerSelect(form,count,offset,picked) {
                   14331:     if (count > 0) {
1.1065    raeburn  14332:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14333:         if (form.elements[item].type == 'radio') {
                   14334:             if (form.elements[item].value == 'dependency') {
                   14335:                 if (form.elements[item+1].type == 'select-one') {
                   14336:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14337:                         if (form.elements[item+1].options[i].value == picked) {
                   14338:                             form.elements[item+1].selectedIndex = i;
                   14339:                             break;
                   14340:                         }
                   14341:                     }
                   14342:                 }
                   14343:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14344:                     if (parents[count].length > 0) {
                   14345:                         for (var j=0; j<parents[count].length; j++) {
                   14346:                             containerSelect(form,parents[count][j],offset,picked);
                   14347:                         }
                   14348:                     }
                   14349:                 }
                   14350:             }
                   14351:         }
                   14352:     }
                   14353: }
                   14354: 
1.1059    raeburn  14355: function titleCheck(form,count,offset) {
                   14356:     if (count > 0) {
                   14357:         var chosen = (offset+$startcount)+7*(count-1);
                   14358:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14359:         var currtype = form.elements[depitem].type;
                   14360:         if (form.elements[chosen].value == 'display') {
                   14361:             document.getElementById('arc_title_'+count).style.display='block';
                   14362:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14363:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14364:             }
                   14365:         } else {
                   14366:             document.getElementById('arc_title_'+count).style.display='none';
                   14367:             if (currtype == 'text') { 
                   14368:                 document.getElementById('archive_title_'+count).value='';
                   14369:             }
                   14370:         }
                   14371:     }
                   14372:     return;
                   14373: }
                   14374: 
1.1055    raeburn  14375: // ]]>
                   14376: </script>
                   14377: END
                   14378:     return $scripttag;
                   14379: }
                   14380: 
                   14381: sub process_extracted_files {
1.1067    raeburn  14382:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14383:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14384:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14385:     my @ids=&Apache::lonnet::current_machine_ids();
                   14386:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14387:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14388:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14389:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14390:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14391:         $pathtocheck = "$dir_root/$destination";
                   14392:         $dir = $dir_root;
                   14393:         $ishome = 1;
                   14394:     } else {
                   14395:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14396:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14397:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14398:     }
                   14399:     my $currdir = "$dir_root/$destination";
                   14400:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14401:     if ($env{'form.folderpath'}) {
                   14402:         my @items = split('&',$env{'form.folderpath'});
                   14403:         $folders{'0'} = $items[-2];
1.1099    raeburn  14404:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14405:             $containers{'0'}='page';
                   14406:         } else {  
                   14407:             $containers{'0'}='sequence';
                   14408:         }
1.1055    raeburn  14409:     }
                   14410:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14411:     if ($numitems) {
                   14412:         for (my $i=1; $i<=$numitems; $i++) {
                   14413:             my $path = $env{'form.archive_content_'.$i};
                   14414:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14415:                 my $item = $1;
                   14416:                 $toplevelitems{$item} = $i;
                   14417:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14418:                     $is_dir{$item} = 1;
                   14419:                 }
                   14420:             }
                   14421:         }
                   14422:     }
1.1067    raeburn  14423:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14424:     if (keys(%toplevelitems) > 0) {
                   14425:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14426:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14427:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14428:     }
1.1066    raeburn  14429:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14430:     if ($numitems) {
                   14431:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14432:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14433:             my $path = $env{'form.archive_content_'.$i};
                   14434:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14435:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14436:                     if ($prefix ne '' && $path ne '') {
                   14437:                         if (-e $prefix.$path) {
1.1066    raeburn  14438:                             if ((@archdirs > 0) && 
                   14439:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14440:                                 $todeletedir{$prefix.$path} = 1;
                   14441:                             } else {
                   14442:                                 $todelete{$prefix.$path} = 1;
                   14443:                             }
1.1055    raeburn  14444:                         }
                   14445:                     }
                   14446:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14447:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14448:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14449:                     $docstitle = $env{'form.archive_title_'.$i};
                   14450:                     if ($docstitle eq '') {
                   14451:                         $docstitle = $title;
                   14452:                     }
1.1055    raeburn  14453:                     $outer = 0;
1.1056    raeburn  14454:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14455:                         if (@{$dirorder{$i}} > 0) {
                   14456:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14457:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14458:                                     $outer = $item;
                   14459:                                     last;
                   14460:                                 }
                   14461:                             }
                   14462:                         }
                   14463:                     }
                   14464:                     my ($errtext,$fatal) = 
                   14465:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14466:                                                '/'.$folders{$outer}.'.'.
                   14467:                                                $containers{$outer});
                   14468:                     next if ($fatal);
                   14469:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14470:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14471:                             $mapinner{$i} = time;
1.1055    raeburn  14472:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14473:                             $containers{$i} = 'sequence';
                   14474:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14475:                                       $folders{$i}.'.'.$containers{$i};
                   14476:                             my $newidx = &LONCAPA::map::getresidx();
                   14477:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14478:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14479:                             push(@LONCAPA::map::order,$newidx);
                   14480:                             my ($outtext,$errtext) =
                   14481:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14482:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14483:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14484:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14485:                             unless ($errtext) {
1.1294    raeburn  14486:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14487:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14488:                                             '</li>'."\n";
1.1067    raeburn  14489:                             }
1.1055    raeburn  14490:                         }
                   14491:                     } else {
                   14492:                         if ($context eq 'coursedocs') {
                   14493:                             my $newidx=&LONCAPA::map::getresidx();
                   14494:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14495:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14496:                                       $title;
1.1392    raeburn  14497:                             if (($outer !~ /\D/) &&
                   14498:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14499:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14500:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14501:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14502:                                 }
                   14503:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14504:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14505:                                 }
                   14506:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14507:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14508:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14509:                                         unless ($ishome) {
                   14510:                                             my $fetch = "$newdest{$i}/$title";
                   14511:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14512:                                             $prompttofetch{$fetch} = 1;
                   14513:                                         }
1.1292    raeburn  14514:                                     }
1.1067    raeburn  14515:                                 }
1.1294    raeburn  14516:                                 $LONCAPA::map::resources[$newidx]=
                   14517:                                     $docstitle.':'.$url.':false:normal:res';
                   14518:                                 push(@LONCAPA::map::order, $newidx);
                   14519:                                 my ($outtext,$errtext)=
                   14520:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14521:                                                             $docuname.'/'.$folders{$outer}.
                   14522:                                                             '.'.$containers{$outer},1,1);
                   14523:                                 unless ($errtext) {
                   14524:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14525:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14526:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14527:                                                    '</li>'."\n";
                   14528:                                     }
1.1067    raeburn  14529:                                 }
1.1294    raeburn  14530:                             } else {
                   14531:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14532:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14533:                             }
1.1055    raeburn  14534:                         }
                   14535:                     }
1.1086    raeburn  14536:                 }
                   14537:             } else {
1.1294    raeburn  14538:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14539:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14540:             }
                   14541:         }
                   14542:         for (my $i=1; $i<=$numitems; $i++) {
                   14543:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14544:             my $path = $env{'form.archive_content_'.$i};
                   14545:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14546:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14547:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14548:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14549:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14550:                         my ($itemidx,$fullpath,$relpath);
                   14551:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14552:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14553:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14554:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14555:                                     $itemidx = $j;
1.1056    raeburn  14556:                                 }
                   14557:                             }
1.1086    raeburn  14558:                         }
                   14559:                         if ($itemidx eq '') {
                   14560:                             $itemidx =  0;
                   14561:                         } 
                   14562:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14563:                             if ($mapinner{$referrer{$i}}) {
                   14564:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14565:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14566:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14567:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14568:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14569:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14570:                                             if (!-e $fullpath) {
                   14571:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14572:                                             }
                   14573:                                         }
1.1086    raeburn  14574:                                     } else {
                   14575:                                         last;
1.1056    raeburn  14576:                                     }
1.1086    raeburn  14577:                                 }
                   14578:                             }
                   14579:                         } elsif ($newdest{$referrer{$i}}) {
                   14580:                             $fullpath = $newdest{$referrer{$i}};
                   14581:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14582:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14583:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14584:                                     last;
                   14585:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14586:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14587:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14588:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14589:                                         if (!-e $fullpath) {
                   14590:                                             mkdir($fullpath,0755);
1.1056    raeburn  14591:                                         }
                   14592:                                     }
1.1086    raeburn  14593:                                 } else {
                   14594:                                     last;
1.1056    raeburn  14595:                                 }
1.1055    raeburn  14596:                             }
                   14597:                         }
1.1086    raeburn  14598:                         if ($fullpath ne '') {
                   14599:                             if (-e "$prefix$path") {
1.1292    raeburn  14600:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14601:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14602:                                 }
1.1086    raeburn  14603:                             }
                   14604:                             if (-e "$fullpath/$title") {
                   14605:                                 my $showpath;
                   14606:                                 if ($relpath ne '') {
                   14607:                                     $showpath = "$relpath/$title";
                   14608:                                 } else {
                   14609:                                     $showpath = "/$title";
                   14610:                                 } 
1.1294    raeburn  14611:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14612:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14613:                                            '</li>'."\n";
1.1292    raeburn  14614:                                 unless ($ishome) {
                   14615:                                     my $fetch = "$fullpath/$title";
                   14616:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14617:                                     $prompttofetch{$fetch} = 1;
                   14618:                                 }
1.1086    raeburn  14619:                             }
                   14620:                         }
1.1055    raeburn  14621:                     }
1.1086    raeburn  14622:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14623:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14624:                                     &HTML::Entities::encode($path,'<>&"'),
                   14625:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14626:                                 '<br />';
1.1055    raeburn  14627:                 }
                   14628:             } else {
1.1294    raeburn  14629:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14630:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14631:             }
                   14632:         }
                   14633:         if (keys(%todelete)) {
                   14634:             foreach my $key (keys(%todelete)) {
                   14635:                 unlink($key);
1.1066    raeburn  14636:             }
                   14637:         }
                   14638:         if (keys(%todeletedir)) {
                   14639:             foreach my $key (keys(%todeletedir)) {
                   14640:                 rmdir($key);
                   14641:             }
                   14642:         }
                   14643:         foreach my $dir (sort(keys(%is_dir))) {
                   14644:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14645:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14646:             }
                   14647:         }
1.1067    raeburn  14648:         if ($result ne '') {
                   14649:             $output .= '<ul>'."\n".
                   14650:                        $result."\n".
                   14651:                        '</ul>';
                   14652:         }
                   14653:         unless ($ishome) {
                   14654:             my $replicationfail;
                   14655:             foreach my $item (keys(%prompttofetch)) {
                   14656:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14657:                 unless ($fetchresult eq 'ok') {
                   14658:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14659:                 }
                   14660:             }
                   14661:             if ($replicationfail) {
                   14662:                 $output .= '<p class="LC_error">'.
                   14663:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14664:                            $replicationfail.
                   14665:                            '</ul></p>';
                   14666:             }
                   14667:         }
1.1055    raeburn  14668:     } else {
                   14669:         $warning = &mt('No items found in archive.');
                   14670:     }
                   14671:     if ($error) {
                   14672:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14673:                    $error.'</p>'."\n";
                   14674:     }
                   14675:     if ($warning) {
                   14676:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14677:     }
                   14678:     return $output;
                   14679: }
                   14680: 
1.1066    raeburn  14681: sub cleanup_empty_dirs {
                   14682:     my ($path) = @_;
                   14683:     if (($path ne '') && (-d $path)) {
                   14684:         if (opendir(my $dirh,$path)) {
                   14685:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14686:             my $numitems = 0;
                   14687:             foreach my $item (@dircontents) {
                   14688:                 if (-d "$path/$item") {
1.1111    raeburn  14689:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14690:                     if (-e "$path/$item") {
                   14691:                         $numitems ++;
                   14692:                     }
                   14693:                 } else {
                   14694:                     $numitems ++;
                   14695:                 }
                   14696:             }
                   14697:             if ($numitems == 0) {
                   14698:                 rmdir($path);
                   14699:             }
                   14700:             closedir($dirh);
                   14701:         }
                   14702:     }
                   14703:     return;
                   14704: }
                   14705: 
1.41      ng       14706: =pod
1.45      matthew  14707: 
1.1162    raeburn  14708: =item * &get_folder_hierarchy()
1.1068    raeburn  14709: 
                   14710: Provides hierarchy of names of folders/sub-folders containing the current
                   14711: item,
                   14712: 
                   14713: Inputs: 3
                   14714:      - $navmap - navmaps object
                   14715: 
                   14716:      - $map - url for map (either the trigger itself, or map containing
                   14717:                            the resource, which is the trigger).
                   14718: 
                   14719:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14720: 
                   14721: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14722: 
                   14723: =cut
                   14724: 
                   14725: sub get_folder_hierarchy {
                   14726:     my ($navmap,$map,$showitem) = @_;
                   14727:     my @pathitems;
                   14728:     if (ref($navmap)) {
                   14729:         my $mapres = $navmap->getResourceByUrl($map);
                   14730:         if (ref($mapres)) {
                   14731:             my $pcslist = $mapres->map_hierarchy();
                   14732:             if ($pcslist ne '') {
                   14733:                 my @pcs = split(/,/,$pcslist);
                   14734:                 foreach my $pc (@pcs) {
                   14735:                     if ($pc == 1) {
1.1129    raeburn  14736:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14737:                     } else {
                   14738:                         my $res = $navmap->getByMapPc($pc);
                   14739:                         if (ref($res)) {
                   14740:                             my $title = $res->compTitle();
                   14741:                             $title =~ s/\W+/_/g;
                   14742:                             if ($title ne '') {
                   14743:                                 push(@pathitems,$title);
                   14744:                             }
                   14745:                         }
                   14746:                     }
                   14747:                 }
                   14748:             }
1.1071    raeburn  14749:             if ($showitem) {
                   14750:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14751:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14752:                 } else {
                   14753:                     my $maptitle = $mapres->compTitle();
                   14754:                     $maptitle =~ s/\W+/_/g;
                   14755:                     if ($maptitle ne '') {
                   14756:                         push(@pathitems,$maptitle);
                   14757:                     }
1.1068    raeburn  14758:                 }
                   14759:             }
                   14760:         }
                   14761:     }
                   14762:     return @pathitems;
                   14763: }
                   14764: 
                   14765: =pod
                   14766: 
1.1015    raeburn  14767: =item * &get_turnedin_filepath()
                   14768: 
                   14769: Determines path in a user's portfolio file for storage of files uploaded
                   14770: to a specific essayresponse or dropbox item.
                   14771: 
                   14772: Inputs: 3 required + 1 optional.
                   14773: $symb is symb for resource, $uname and $udom are for current user (required).
                   14774: $caller is optional (can be "submission", if routine is called when storing
                   14775: an upoaded file when "Submit Answer" button was pressed).
                   14776: 
                   14777: Returns array containing $path and $multiresp. 
                   14778: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14779: than one file upload item.  Callers of routine should append partid as a 
                   14780: subdirectory to $path in cases where $multiresp is 1.
                   14781: 
                   14782: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14783: 
                   14784: =cut
                   14785: 
                   14786: sub get_turnedin_filepath {
                   14787:     my ($symb,$uname,$udom,$caller) = @_;
                   14788:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14789:     my $turnindir;
                   14790:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14791:     $turnindir = $userhash{'turnindir'};
                   14792:     my ($path,$multiresp);
                   14793:     if ($turnindir eq '') {
                   14794:         if ($caller eq 'submission') {
                   14795:             $turnindir = &mt('turned in');
                   14796:             $turnindir =~ s/\W+/_/g;
                   14797:             my %newhash = (
                   14798:                             'turnindir' => $turnindir,
                   14799:                           );
                   14800:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14801:         }
                   14802:     }
                   14803:     if ($turnindir ne '') {
                   14804:         $path = '/'.$turnindir.'/';
                   14805:         my ($multipart,$turnin,@pathitems);
                   14806:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14807:         if (defined($navmap)) {
                   14808:             my $mapres = $navmap->getResourceByUrl($map);
                   14809:             if (ref($mapres)) {
                   14810:                 my $pcslist = $mapres->map_hierarchy();
                   14811:                 if ($pcslist ne '') {
                   14812:                     foreach my $pc (split(/,/,$pcslist)) {
                   14813:                         my $res = $navmap->getByMapPc($pc);
                   14814:                         if (ref($res)) {
                   14815:                             my $title = $res->compTitle();
                   14816:                             $title =~ s/\W+/_/g;
                   14817:                             if ($title ne '') {
1.1149    raeburn  14818:                                 if (($pc > 1) && (length($title) > 12)) {
                   14819:                                     $title = substr($title,0,12);
                   14820:                                 }
1.1015    raeburn  14821:                                 push(@pathitems,$title);
                   14822:                             }
                   14823:                         }
                   14824:                     }
                   14825:                 }
                   14826:                 my $maptitle = $mapres->compTitle();
                   14827:                 $maptitle =~ s/\W+/_/g;
                   14828:                 if ($maptitle ne '') {
1.1149    raeburn  14829:                     if (length($maptitle) > 12) {
                   14830:                         $maptitle = substr($maptitle,0,12);
                   14831:                     }
1.1015    raeburn  14832:                     push(@pathitems,$maptitle);
                   14833:                 }
                   14834:                 unless ($env{'request.state'} eq 'construct') {
                   14835:                     my $res = $navmap->getBySymb($symb);
                   14836:                     if (ref($res)) {
                   14837:                         my $partlist = $res->parts();
                   14838:                         my $totaluploads = 0;
                   14839:                         if (ref($partlist) eq 'ARRAY') {
                   14840:                             foreach my $part (@{$partlist}) {
                   14841:                                 my @types = $res->responseType($part);
                   14842:                                 my @ids = $res->responseIds($part);
                   14843:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14844:                                     if ($types[$i] eq 'essay') {
                   14845:                                         my $partid = $part.'_'.$ids[$i];
                   14846:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14847:                                             $totaluploads ++;
                   14848:                                         }
                   14849:                                     }
                   14850:                                 }
                   14851:                             }
                   14852:                             if ($totaluploads > 1) {
                   14853:                                 $multiresp = 1;
                   14854:                             }
                   14855:                         }
                   14856:                     }
                   14857:                 }
                   14858:             } else {
                   14859:                 return;
                   14860:             }
                   14861:         } else {
                   14862:             return;
                   14863:         }
                   14864:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14865:         $restitle =~ s/\W+/_/g;
                   14866:         if ($restitle eq '') {
                   14867:             $restitle = ($resurl =~ m{/[^/]+$});
                   14868:             if ($restitle eq '') {
                   14869:                 $restitle = time;
                   14870:             }
                   14871:         }
1.1149    raeburn  14872:         if (length($restitle) > 12) {
                   14873:             $restitle = substr($restitle,0,12);
                   14874:         }
1.1015    raeburn  14875:         push(@pathitems,$restitle);
                   14876:         $path .= join('/',@pathitems);
                   14877:     }
                   14878:     return ($path,$multiresp);
                   14879: }
                   14880: 
                   14881: =pod
                   14882: 
1.464     albertel 14883: =back
1.41      ng       14884: 
1.112     bowersj2 14885: =head1 CSV Upload/Handling functions
1.38      albertel 14886: 
1.41      ng       14887: =over 4
                   14888: 
1.648     raeburn  14889: =item * &upfile_store($r)
1.41      ng       14890: 
                   14891: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14892: needs $env{'form.upfile'}
1.41      ng       14893: returns $datatoken to be put into hidden field
                   14894: 
                   14895: =cut
1.31      albertel 14896: 
                   14897: sub upfile_store {
                   14898:     my $r=shift;
1.258     albertel 14899:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14900:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14901:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14902:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14903: 
1.1299    raeburn  14904:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14905:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14906:                                      time.'_'.$$);
                   14907:     return if ($datatoken eq '');
                   14908: 
1.31      albertel 14909:     {
1.158     raeburn  14910:         my $datafile = $r->dir_config('lonDaemons').
                   14911:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14912:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14913:             print $fh $env{'form.upfile'};
1.158     raeburn  14914:             close($fh);
                   14915:         }
1.31      albertel 14916:     }
                   14917:     return $datatoken;
                   14918: }
                   14919: 
1.56      matthew  14920: =pod
                   14921: 
1.1290    raeburn  14922: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14923: 
                   14924: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14925: $datatoken is the name to assign to the temporary file.
1.258     albertel 14926: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14927: 
                   14928: =cut
1.31      albertel 14929: 
                   14930: sub load_tmp_file {
1.1290    raeburn  14931:     my ($r,$datatoken) = @_;
                   14932:     return if ($datatoken eq '');
1.31      albertel 14933:     my @studentdata=();
                   14934:     {
1.158     raeburn  14935:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14936:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14937:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14938:             @studentdata=<$fh>;
                   14939:             close($fh);
                   14940:         }
1.31      albertel 14941:     }
1.258     albertel 14942:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14943: }
                   14944: 
1.1290    raeburn  14945: sub valid_datatoken {
                   14946:     my ($datatoken) = @_;
1.1325    raeburn  14947:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14948:         return $datatoken;
                   14949:     }
                   14950:     return;
                   14951: }
                   14952: 
1.56      matthew  14953: =pod
                   14954: 
1.648     raeburn  14955: =item * &upfile_record_sep()
1.41      ng       14956: 
                   14957: Separate uploaded file into records
                   14958: returns array of records,
1.258     albertel 14959: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14960: 
                   14961: =cut
1.31      albertel 14962: 
                   14963: sub upfile_record_sep {
1.258     albertel 14964:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14965:     } else {
1.248     albertel 14966: 	my @records;
1.258     albertel 14967: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14968: 	    if ($line=~/^\s*$/) { next; }
                   14969: 	    push(@records,$line);
                   14970: 	}
                   14971: 	return @records;
1.31      albertel 14972:     }
                   14973: }
                   14974: 
1.56      matthew  14975: =pod
                   14976: 
1.648     raeburn  14977: =item * &record_sep($record)
1.41      ng       14978: 
1.258     albertel 14979: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14980: 
                   14981: =cut
                   14982: 
1.263     www      14983: sub takeleft {
                   14984:     my $index=shift;
                   14985:     return substr('0000'.$index,-4,4);
                   14986: }
                   14987: 
1.31      albertel 14988: sub record_sep {
                   14989:     my $record=shift;
                   14990:     my %components=();
1.258     albertel 14991:     if ($env{'form.upfiletype'} eq 'xml') {
                   14992:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14993:         my $i=0;
1.356     albertel 14994:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14995:             $field=~s/^(\"|\')//;
                   14996:             $field=~s/(\"|\')$//;
1.263     www      14997:             $components{&takeleft($i)}=$field;
1.31      albertel 14998:             $i++;
                   14999:         }
1.258     albertel 15000:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15001:         my $i=0;
1.356     albertel 15002:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15003:             $field=~s/^(\"|\')//;
                   15004:             $field=~s/(\"|\')$//;
1.263     www      15005:             $components{&takeleft($i)}=$field;
1.31      albertel 15006:             $i++;
                   15007:         }
                   15008:     } else {
1.561     www      15009:         my $separator=',';
1.480     banghart 15010:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15011:             $separator=';';
1.480     banghart 15012:         }
1.31      albertel 15013:         my $i=0;
1.561     www      15014: # the character we are looking for to indicate the end of a quote or a record 
                   15015:         my $looking_for=$separator;
                   15016: # do not add the characters to the fields
                   15017:         my $ignore=0;
                   15018: # we just encountered a separator (or the beginning of the record)
                   15019:         my $just_found_separator=1;
                   15020: # store the field we are working on here
                   15021:         my $field='';
                   15022: # work our way through all characters in record
                   15023:         foreach my $character ($record=~/(.)/g) {
                   15024:             if ($character eq $looking_for) {
                   15025:                if ($character ne $separator) {
                   15026: # Found the end of a quote, again looking for separator
                   15027:                   $looking_for=$separator;
                   15028:                   $ignore=1;
                   15029:                } else {
                   15030: # Found a separator, store away what we got
                   15031:                   $components{&takeleft($i)}=$field;
                   15032: 	          $i++;
                   15033:                   $just_found_separator=1;
                   15034:                   $ignore=0;
                   15035:                   $field='';
                   15036:                }
                   15037:                next;
                   15038:             }
                   15039: # single or double quotation marks after a separator indicate beginning of a quote
                   15040: # we are now looking for the end of the quote and need to ignore separators
                   15041:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15042:                $looking_for=$character;
                   15043:                next;
                   15044:             }
                   15045: # ignore would be true after we reached the end of a quote
                   15046:             if ($ignore) { next; }
                   15047:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15048:             $field.=$character;
                   15049:             $just_found_separator=0; 
1.31      albertel 15050:         }
1.561     www      15051: # catch the very last entry, since we never encountered the separator
                   15052:         $components{&takeleft($i)}=$field;
1.31      albertel 15053:     }
                   15054:     return %components;
                   15055: }
                   15056: 
1.144     matthew  15057: ######################################################
                   15058: ######################################################
                   15059: 
1.56      matthew  15060: =pod
                   15061: 
1.648     raeburn  15062: =item * &upfile_select_html()
1.41      ng       15063: 
1.144     matthew  15064: Return HTML code to select a file from the users machine and specify 
                   15065: the file type.
1.41      ng       15066: 
                   15067: =cut
                   15068: 
1.144     matthew  15069: ######################################################
                   15070: ######################################################
1.31      albertel 15071: sub upfile_select_html {
1.144     matthew  15072:     my %Types = (
                   15073:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15074:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15075:                  space => &mt('Space separated'),
                   15076:                  tab   => &mt('Tabulator separated'),
                   15077: #                 xml   => &mt('HTML/XML'),
                   15078:                  );
                   15079:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15080:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15081:     foreach my $type (sort(keys(%Types))) {
                   15082:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15083:     }
                   15084:     $Str .= "</select>\n";
                   15085:     return $Str;
1.31      albertel 15086: }
                   15087: 
1.301     albertel 15088: sub get_samples {
                   15089:     my ($records,$toget) = @_;
                   15090:     my @samples=({});
                   15091:     my $got=0;
                   15092:     foreach my $rec (@$records) {
                   15093: 	my %temp = &record_sep($rec);
                   15094: 	if (! grep(/\S/, values(%temp))) { next; }
                   15095: 	if (%temp) {
                   15096: 	    $samples[$got]=\%temp;
                   15097: 	    $got++;
                   15098: 	    if ($got == $toget) { last; }
                   15099: 	}
                   15100:     }
                   15101:     return \@samples;
                   15102: }
                   15103: 
1.144     matthew  15104: ######################################################
                   15105: ######################################################
                   15106: 
1.56      matthew  15107: =pod
                   15108: 
1.648     raeburn  15109: =item * &csv_print_samples($r,$records)
1.41      ng       15110: 
                   15111: Prints a table of sample values from each column uploaded $r is an
                   15112: Apache Request ref, $records is an arrayref from
                   15113: &Apache::loncommon::upfile_record_sep
                   15114: 
                   15115: =cut
                   15116: 
1.144     matthew  15117: ######################################################
                   15118: ######################################################
1.31      albertel 15119: sub csv_print_samples {
                   15120:     my ($r,$records) = @_;
1.662     bisitz   15121:     my $samples = &get_samples($records,5);
1.301     albertel 15122: 
1.594     raeburn  15123:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15124:               &start_data_table_header_row());
1.356     albertel 15125:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15126:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15127:     $r->print(&end_data_table_header_row());
1.301     albertel 15128:     foreach my $hash (@$samples) {
1.594     raeburn  15129: 	$r->print(&start_data_table_row());
1.356     albertel 15130: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15131: 	    $r->print('<td>');
1.356     albertel 15132: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15133: 	    $r->print('</td>');
                   15134: 	}
1.594     raeburn  15135: 	$r->print(&end_data_table_row());
1.31      albertel 15136:     }
1.594     raeburn  15137:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15138: }
                   15139: 
1.144     matthew  15140: ######################################################
                   15141: ######################################################
                   15142: 
1.56      matthew  15143: =pod
                   15144: 
1.648     raeburn  15145: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15146: 
                   15147: Prints a table to create associations between values and table columns.
1.144     matthew  15148: 
1.41      ng       15149: $r is an Apache Request ref,
                   15150: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15151: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15152: 
                   15153: =cut
                   15154: 
1.144     matthew  15155: ######################################################
                   15156: ######################################################
1.31      albertel 15157: sub csv_print_select_table {
                   15158:     my ($r,$records,$d) = @_;
1.301     albertel 15159:     my $i=0;
                   15160:     my $samples = &get_samples($records,1);
1.144     matthew  15161:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15162: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15163:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15164:               '<th>'.&mt('Column').'</th>'.
                   15165:               &end_data_table_header_row()."\n");
1.356     albertel 15166:     foreach my $array_ref (@$d) {
                   15167: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15168: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15169: 
1.875     bisitz   15170: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15171: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15172: 	$r->print('<option value="none"></option>');
1.356     albertel 15173: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15174: 	    $r->print('<option value="'.$sample.'"'.
                   15175:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15176:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15177: 	}
1.594     raeburn  15178: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15179: 	$i++;
                   15180:     }
1.594     raeburn  15181:     $r->print(&end_data_table());
1.31      albertel 15182:     $i--;
                   15183:     return $i;
                   15184: }
1.56      matthew  15185: 
1.144     matthew  15186: ######################################################
                   15187: ######################################################
                   15188: 
1.56      matthew  15189: =pod
1.31      albertel 15190: 
1.648     raeburn  15191: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15192: 
                   15193: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15194: 
                   15195: $r is an Apache Request ref,
                   15196: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15197: $d is an array of 2 element arrays (internal name, displayed name)
                   15198: 
                   15199: =cut
                   15200: 
1.144     matthew  15201: ######################################################
                   15202: ######################################################
1.31      albertel 15203: sub csv_samples_select_table {
                   15204:     my ($r,$records,$d) = @_;
                   15205:     my $i=0;
1.144     matthew  15206:     #
1.662     bisitz   15207:     my $max_samples = 5;
                   15208:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15209:     $r->print(&start_data_table().
                   15210:               &start_data_table_header_row().'<th>'.
                   15211:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15212:               &end_data_table_header_row());
1.301     albertel 15213: 
                   15214:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15215: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15216: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15217: 	foreach my $option (@$d) {
                   15218: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15219: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15220:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15221:                       $display.'</option>');
1.31      albertel 15222: 	}
                   15223: 	$r->print('</select></td><td>');
1.662     bisitz   15224: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15225: 	    if (defined($samples->[$line]{$key})) { 
                   15226: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15227: 	    }
                   15228: 	}
1.594     raeburn  15229: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15230: 	$i++;
                   15231:     }
1.594     raeburn  15232:     $r->print(&end_data_table());
1.31      albertel 15233:     $i--;
                   15234:     return($i);
1.115     matthew  15235: }
                   15236: 
1.144     matthew  15237: ######################################################
                   15238: ######################################################
                   15239: 
1.115     matthew  15240: =pod
                   15241: 
1.648     raeburn  15242: =item * &clean_excel_name($name)
1.115     matthew  15243: 
                   15244: Returns a replacement for $name which does not contain any illegal characters.
                   15245: 
                   15246: =cut
                   15247: 
1.144     matthew  15248: ######################################################
                   15249: ######################################################
1.115     matthew  15250: sub clean_excel_name {
                   15251:     my ($name) = @_;
                   15252:     $name =~ s/[:\*\?\/\\]//g;
                   15253:     if (length($name) > 31) {
                   15254:         $name = substr($name,0,31);
                   15255:     }
                   15256:     return $name;
1.25      albertel 15257: }
1.84      albertel 15258: 
1.85      albertel 15259: =pod
                   15260: 
1.648     raeburn  15261: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15262: 
                   15263: Returns either 1 or undef
                   15264: 
                   15265: 1 if the part is to be hidden, undef if it is to be shown
                   15266: 
                   15267: Arguments are:
                   15268: 
                   15269: $id the id of the part to be checked
                   15270: $symb, optional the symb of the resource to check
                   15271: $udom, optional the domain of the user to check for
                   15272: $uname, optional the username of the user to check for
                   15273: 
                   15274: =cut
1.84      albertel 15275: 
                   15276: sub check_if_partid_hidden {
                   15277:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15278:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15279: 					 $symb,$udom,$uname);
1.141     albertel 15280:     my $truth=1;
                   15281:     #if the string starts with !, then the list is the list to show not hide
                   15282:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15283:     my @hiddenlist=split(/,/,$hiddenparts);
                   15284:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15285: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15286:     }
1.141     albertel 15287:     return !$truth;
1.84      albertel 15288: }
1.127     matthew  15289: 
1.138     matthew  15290: 
                   15291: ############################################################
                   15292: ############################################################
                   15293: 
                   15294: =pod
                   15295: 
1.157     matthew  15296: =back 
                   15297: 
1.138     matthew  15298: =head1 cgi-bin script and graphing routines
                   15299: 
1.157     matthew  15300: =over 4
                   15301: 
1.648     raeburn  15302: =item * &get_cgi_id()
1.138     matthew  15303: 
                   15304: Inputs: none
                   15305: 
                   15306: Returns an id which can be used to pass environment variables
                   15307: to various cgi-bin scripts.  These environment variables will
                   15308: be removed from the users environment after a given time by
                   15309: the routine &Apache::lonnet::transfer_profile_to_env.
                   15310: 
                   15311: =cut
                   15312: 
                   15313: ############################################################
                   15314: ############################################################
1.152     albertel 15315: my $uniq=0;
1.136     matthew  15316: sub get_cgi_id {
1.154     albertel 15317:     $uniq=($uniq+1)%100000;
1.280     albertel 15318:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15319: }
                   15320: 
1.127     matthew  15321: ############################################################
                   15322: ############################################################
                   15323: 
                   15324: =pod
                   15325: 
1.648     raeburn  15326: =item * &DrawBarGraph()
1.127     matthew  15327: 
1.138     matthew  15328: Facilitates the plotting of data in a (stacked) bar graph.
                   15329: Puts plot definition data into the users environment in order for 
                   15330: graph.png to plot it.  Returns an <img> tag for the plot.
                   15331: The bars on the plot are labeled '1','2',...,'n'.
                   15332: 
                   15333: Inputs:
                   15334: 
                   15335: =over 4
                   15336: 
                   15337: =item $Title: string, the title of the plot
                   15338: 
                   15339: =item $xlabel: string, text describing the X-axis of the plot
                   15340: 
                   15341: =item $ylabel: string, text describing the Y-axis of the plot
                   15342: 
                   15343: =item $Max: scalar, the maximum Y value to use in the plot
                   15344: If $Max is < any data point, the graph will not be rendered.
                   15345: 
1.140     matthew  15346: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15347: they are plotted.  If undefined, default values will be used.
                   15348: 
1.178     matthew  15349: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15350: 
1.138     matthew  15351: =item @Values: An array of array references.  Each array reference holds data
                   15352: to be plotted in a stacked bar chart.
                   15353: 
1.239     matthew  15354: =item If the final element of @Values is a hash reference the key/value
                   15355: pairs will be added to the graph definition.
                   15356: 
1.138     matthew  15357: =back
                   15358: 
                   15359: Returns:
                   15360: 
                   15361: An <img> tag which references graph.png and the appropriate identifying
                   15362: information for the plot.
                   15363: 
1.127     matthew  15364: =cut
                   15365: 
                   15366: ############################################################
                   15367: ############################################################
1.134     matthew  15368: sub DrawBarGraph {
1.178     matthew  15369:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15370:     #
                   15371:     if (! defined($colors)) {
                   15372:         $colors = ['#33ff00', 
                   15373:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15374:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15375:                   ]; 
                   15376:     }
1.228     matthew  15377:     my $extra_settings = {};
                   15378:     if (ref($Values[-1]) eq 'HASH') {
                   15379:         $extra_settings = pop(@Values);
                   15380:     }
1.127     matthew  15381:     #
1.136     matthew  15382:     my $identifier = &get_cgi_id();
                   15383:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15384:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15385:         return '';
                   15386:     }
1.225     matthew  15387:     #
                   15388:     my @Labels;
                   15389:     if (defined($labels)) {
                   15390:         @Labels = @$labels;
                   15391:     } else {
                   15392:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15393:             push(@Labels,$i+1);
1.225     matthew  15394:         }
                   15395:     }
                   15396:     #
1.129     matthew  15397:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15398:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15399:     my %ValuesHash;
                   15400:     my $NumSets=1;
                   15401:     foreach my $array (@Values) {
                   15402:         next if (! ref($array));
1.136     matthew  15403:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15404:             join(',',@$array);
1.129     matthew  15405:     }
1.127     matthew  15406:     #
1.136     matthew  15407:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15408:     if ($NumBars < 3) {
                   15409:         $width = 120+$NumBars*32;
1.220     matthew  15410:         $xskip = 1;
1.225     matthew  15411:         $bar_width = 30;
                   15412:     } elsif ($NumBars < 5) {
                   15413:         $width = 120+$NumBars*20;
                   15414:         $xskip = 1;
                   15415:         $bar_width = 20;
1.220     matthew  15416:     } elsif ($NumBars < 10) {
1.136     matthew  15417:         $width = 120+$NumBars*15;
                   15418:         $xskip = 1;
                   15419:         $bar_width = 15;
                   15420:     } elsif ($NumBars <= 25) {
                   15421:         $width = 120+$NumBars*11;
                   15422:         $xskip = 5;
                   15423:         $bar_width = 8;
                   15424:     } elsif ($NumBars <= 50) {
                   15425:         $width = 120+$NumBars*8;
                   15426:         $xskip = 5;
                   15427:         $bar_width = 4;
                   15428:     } else {
                   15429:         $width = 120+$NumBars*8;
                   15430:         $xskip = 5;
                   15431:         $bar_width = 4;
                   15432:     }
                   15433:     #
1.137     matthew  15434:     $Max = 1 if ($Max < 1);
                   15435:     if ( int($Max) < $Max ) {
                   15436:         $Max++;
                   15437:         $Max = int($Max);
                   15438:     }
1.127     matthew  15439:     $Title  = '' if (! defined($Title));
                   15440:     $xlabel = '' if (! defined($xlabel));
                   15441:     $ylabel = '' if (! defined($ylabel));
1.369     www      15442:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15443:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15444:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15445:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15446:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15447:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15448:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15449:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15450:     $ValuesHash{$id.'.height'}   = $height;
                   15451:     $ValuesHash{$id.'.width'}    = $width;
                   15452:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15453:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15454:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15455:     #
1.228     matthew  15456:     # Deal with other parameters
                   15457:     while (my ($key,$value) = each(%$extra_settings)) {
                   15458:         $ValuesHash{$id.'.'.$key} = $value;
                   15459:     }
                   15460:     #
1.646     raeburn  15461:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15462:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15463: }
                   15464: 
                   15465: ############################################################
                   15466: ############################################################
                   15467: 
                   15468: =pod
                   15469: 
1.648     raeburn  15470: =item * &DrawXYGraph()
1.137     matthew  15471: 
1.138     matthew  15472: Facilitates the plotting of data in an XY graph.
                   15473: Puts plot definition data into the users environment in order for 
                   15474: graph.png to plot it.  Returns an <img> tag for the plot.
                   15475: 
                   15476: Inputs:
                   15477: 
                   15478: =over 4
                   15479: 
                   15480: =item $Title: string, the title of the plot
                   15481: 
                   15482: =item $xlabel: string, text describing the X-axis of the plot
                   15483: 
                   15484: =item $ylabel: string, text describing the Y-axis of the plot
                   15485: 
                   15486: =item $Max: scalar, the maximum Y value to use in the plot
                   15487: If $Max is < any data point, the graph will not be rendered.
                   15488: 
                   15489: =item $colors: Array ref containing the hex color codes for the data to be 
                   15490: plotted in.  If undefined, default values will be used.
                   15491: 
                   15492: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15493: 
                   15494: =item $Ydata: Array ref containing Array refs.  
1.185     www      15495: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15496: 
                   15497: =item %Values: hash indicating or overriding any default values which are 
                   15498: passed to graph.png.  
                   15499: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15500: 
                   15501: =back
                   15502: 
                   15503: Returns:
                   15504: 
                   15505: An <img> tag which references graph.png and the appropriate identifying
                   15506: information for the plot.
                   15507: 
1.137     matthew  15508: =cut
                   15509: 
                   15510: ############################################################
                   15511: ############################################################
                   15512: sub DrawXYGraph {
                   15513:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15514:     #
                   15515:     # Create the identifier for the graph
                   15516:     my $identifier = &get_cgi_id();
                   15517:     my $id = 'cgi.'.$identifier;
                   15518:     #
                   15519:     $Title  = '' if (! defined($Title));
                   15520:     $xlabel = '' if (! defined($xlabel));
                   15521:     $ylabel = '' if (! defined($ylabel));
                   15522:     my %ValuesHash = 
                   15523:         (
1.369     www      15524:          $id.'.title'  => &escape($Title),
                   15525:          $id.'.xlabel' => &escape($xlabel),
                   15526:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15527:          $id.'.y_max_value'=> $Max,
                   15528:          $id.'.labels'     => join(',',@$Xlabels),
                   15529:          $id.'.PlotType'   => 'XY',
                   15530:          );
                   15531:     #
                   15532:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15533:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15534:     }
                   15535:     #
                   15536:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15537:         return '';
                   15538:     }
                   15539:     my $NumSets=1;
1.138     matthew  15540:     foreach my $array (@{$Ydata}){
1.137     matthew  15541:         next if (! ref($array));
                   15542:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15543:     }
1.138     matthew  15544:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15545:     #
                   15546:     # Deal with other parameters
                   15547:     while (my ($key,$value) = each(%Values)) {
                   15548:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15549:     }
                   15550:     #
1.646     raeburn  15551:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15552:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15553: }
                   15554: 
                   15555: ############################################################
                   15556: ############################################################
                   15557: 
                   15558: =pod
                   15559: 
1.648     raeburn  15560: =item * &DrawXYYGraph()
1.138     matthew  15561: 
                   15562: Facilitates the plotting of data in an XY graph with two Y axes.
                   15563: Puts plot definition data into the users environment in order for 
                   15564: graph.png to plot it.  Returns an <img> tag for the plot.
                   15565: 
                   15566: Inputs:
                   15567: 
                   15568: =over 4
                   15569: 
                   15570: =item $Title: string, the title of the plot
                   15571: 
                   15572: =item $xlabel: string, text describing the X-axis of the plot
                   15573: 
                   15574: =item $ylabel: string, text describing the Y-axis of the plot
                   15575: 
                   15576: =item $colors: Array ref containing the hex color codes for the data to be 
                   15577: plotted in.  If undefined, default values will be used.
                   15578: 
                   15579: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15580: 
                   15581: =item $Ydata1: The first data set
                   15582: 
                   15583: =item $Min1: The minimum value of the left Y-axis
                   15584: 
                   15585: =item $Max1: The maximum value of the left Y-axis
                   15586: 
                   15587: =item $Ydata2: The second data set
                   15588: 
                   15589: =item $Min2: The minimum value of the right Y-axis
                   15590: 
                   15591: =item $Max2: The maximum value of the left Y-axis
                   15592: 
                   15593: =item %Values: hash indicating or overriding any default values which are 
                   15594: passed to graph.png.  
                   15595: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15596: 
                   15597: =back
                   15598: 
                   15599: Returns:
                   15600: 
                   15601: An <img> tag which references graph.png and the appropriate identifying
                   15602: information for the plot.
1.136     matthew  15603: 
                   15604: =cut
                   15605: 
                   15606: ############################################################
                   15607: ############################################################
1.137     matthew  15608: sub DrawXYYGraph {
                   15609:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15610:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15611:     #
                   15612:     # Create the identifier for the graph
                   15613:     my $identifier = &get_cgi_id();
                   15614:     my $id = 'cgi.'.$identifier;
                   15615:     #
                   15616:     $Title  = '' if (! defined($Title));
                   15617:     $xlabel = '' if (! defined($xlabel));
                   15618:     $ylabel = '' if (! defined($ylabel));
                   15619:     my %ValuesHash = 
                   15620:         (
1.369     www      15621:          $id.'.title'  => &escape($Title),
                   15622:          $id.'.xlabel' => &escape($xlabel),
                   15623:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15624:          $id.'.labels' => join(',',@$Xlabels),
                   15625:          $id.'.PlotType' => 'XY',
                   15626:          $id.'.NumSets' => 2,
1.137     matthew  15627:          $id.'.two_axes' => 1,
                   15628:          $id.'.y1_max_value' => $Max1,
                   15629:          $id.'.y1_min_value' => $Min1,
                   15630:          $id.'.y2_max_value' => $Max2,
                   15631:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15632:          );
                   15633:     #
1.137     matthew  15634:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15635:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15636:     }
                   15637:     #
                   15638:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15639:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15640:         return '';
                   15641:     }
                   15642:     my $NumSets=1;
1.137     matthew  15643:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15644:         next if (! ref($array));
                   15645:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15646:     }
                   15647:     #
                   15648:     # Deal with other parameters
                   15649:     while (my ($key,$value) = each(%Values)) {
                   15650:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15651:     }
                   15652:     #
1.646     raeburn  15653:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15654:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15655: }
                   15656: 
                   15657: ############################################################
                   15658: ############################################################
                   15659: 
                   15660: =pod
                   15661: 
1.157     matthew  15662: =back 
                   15663: 
1.139     matthew  15664: =head1 Statistics helper routines?  
                   15665: 
                   15666: Bad place for them but what the hell.
                   15667: 
1.157     matthew  15668: =over 4
                   15669: 
1.648     raeburn  15670: =item * &chartlink()
1.139     matthew  15671: 
                   15672: Returns a link to the chart for a specific student.  
                   15673: 
                   15674: Inputs:
                   15675: 
                   15676: =over 4
                   15677: 
                   15678: =item $linktext: The text of the link
                   15679: 
                   15680: =item $sname: The students username
                   15681: 
                   15682: =item $sdomain: The students domain
                   15683: 
                   15684: =back
                   15685: 
1.157     matthew  15686: =back
                   15687: 
1.139     matthew  15688: =cut
                   15689: 
                   15690: ############################################################
                   15691: ############################################################
                   15692: sub chartlink {
                   15693:     my ($linktext, $sname, $sdomain) = @_;
                   15694:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15695:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15696:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15697:        '">'.$linktext.'</a>';
1.153     matthew  15698: }
                   15699: 
                   15700: #######################################################
                   15701: #######################################################
                   15702: 
                   15703: =pod
                   15704: 
                   15705: =head1 Course Environment Routines
1.157     matthew  15706: 
                   15707: =over 4
1.153     matthew  15708: 
1.648     raeburn  15709: =item * &restore_course_settings()
1.153     matthew  15710: 
1.648     raeburn  15711: =item * &store_course_settings()
1.153     matthew  15712: 
                   15713: Restores/Store indicated form parameters from the course environment.
                   15714: Will not overwrite existing values of the form parameters.
                   15715: 
                   15716: Inputs: 
                   15717: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15718: 
                   15719: a hash ref describing the data to be stored.  For example:
                   15720:    
                   15721: %Save_Parameters = ('Status' => 'scalar',
                   15722:     'chartoutputmode' => 'scalar',
                   15723:     'chartoutputdata' => 'scalar',
                   15724:     'Section' => 'array',
1.373     raeburn  15725:     'Group' => 'array',
1.153     matthew  15726:     'StudentData' => 'array',
                   15727:     'Maps' => 'array');
                   15728: 
                   15729: Returns: both routines return nothing
                   15730: 
1.631     raeburn  15731: =back
                   15732: 
1.153     matthew  15733: =cut
                   15734: 
                   15735: #######################################################
                   15736: #######################################################
                   15737: sub store_course_settings {
1.496     albertel 15738:     return &store_settings($env{'request.course.id'},@_);
                   15739: }
                   15740: 
                   15741: sub store_settings {
1.153     matthew  15742:     # save to the environment
                   15743:     # appenv the same items, just to be safe
1.300     albertel 15744:     my $udom  = $env{'user.domain'};
                   15745:     my $uname = $env{'user.name'};
1.496     albertel 15746:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15747:     my %SaveHash;
                   15748:     my %AppHash;
                   15749:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15750:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15751:         my $envname = 'environment.'.$basename;
1.258     albertel 15752:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15753:             # Save this value away
                   15754:             if ($type eq 'scalar' &&
1.258     albertel 15755:                 (! exists($env{$envname}) || 
                   15756:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15757:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15758:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15759:             } elsif ($type eq 'array') {
                   15760:                 my $stored_form;
1.258     albertel 15761:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15762:                     $stored_form = join(',',
                   15763:                                         map {
1.369     www      15764:                                             &escape($_);
1.258     albertel 15765:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15766:                 } else {
                   15767:                     $stored_form = 
1.369     www      15768:                         &escape($env{'form.'.$setting});
1.153     matthew  15769:                 }
                   15770:                 # Determine if the array contents are the same.
1.258     albertel 15771:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15772:                     $SaveHash{$basename} = $stored_form;
                   15773:                     $AppHash{$envname}   = $stored_form;
                   15774:                 }
                   15775:             }
                   15776:         }
                   15777:     }
                   15778:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15779:                                           $udom,$uname);
1.153     matthew  15780:     if ($put_result !~ /^(ok|delayed)/) {
                   15781:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15782:                                  'got error:'.$put_result);
                   15783:     }
                   15784:     # Make sure these settings stick around in this session, too
1.646     raeburn  15785:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15786:     return;
                   15787: }
                   15788: 
                   15789: sub restore_course_settings {
1.499     albertel 15790:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15791: }
                   15792: 
                   15793: sub restore_settings {
                   15794:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15795:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15796:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15797:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15798:             '.'.$setting;
1.258     albertel 15799:         if (exists($env{$envname})) {
1.153     matthew  15800:             if ($type eq 'scalar') {
1.258     albertel 15801:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15802:             } elsif ($type eq 'array') {
1.258     albertel 15803:                 $env{'form.'.$setting} = [ 
1.153     matthew  15804:                                            map { 
1.369     www      15805:                                                &unescape($_); 
1.258     albertel 15806:                                            } split(',',$env{$envname})
1.153     matthew  15807:                                            ];
                   15808:             }
                   15809:         }
                   15810:     }
1.127     matthew  15811: }
                   15812: 
1.618     raeburn  15813: #######################################################
                   15814: #######################################################
                   15815: 
                   15816: =pod
                   15817: 
                   15818: =head1 Domain E-mail Routines  
                   15819: 
                   15820: =over 4
                   15821: 
1.648     raeburn  15822: =item * &build_recipient_list()
1.618     raeburn  15823: 
1.1144    raeburn  15824: Build recipient lists for following types of e-mail:
1.766     raeburn  15825: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15826: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15827: module change checking, student/employee ID conflict checks, as
                   15828: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15829: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15830: 
                   15831: Inputs:
1.619     raeburn  15832: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15833: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15834: requestsmail, updatesmail, or idconflictsmail).
                   15835: 
1.619     raeburn  15836: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15837: 
1.619     raeburn  15838: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15839: i.e., predates configuration by DC via domainprefs.pm
                   15840: 
                   15841: $requname username of requester (if mailing type is helpdeskmail)
                   15842: 
                   15843: $requdom domain of requester (if mailing type is helpdeskmail)
                   15844: 
                   15845: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15846: 
1.618     raeburn  15847: 
1.655     raeburn  15848: Returns: comma separated list of addresses to which to send e-mail.
                   15849: 
                   15850: =back
1.618     raeburn  15851: 
                   15852: =cut
                   15853: 
                   15854: ############################################################
                   15855: ############################################################
                   15856: sub build_recipient_list {
1.1297    raeburn  15857:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15858:     my @recipients;
1.1270    raeburn  15859:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15860:     my %domconfig =
1.1270    raeburn  15861:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15862:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15863:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15864:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15865:                 my @contacts = ('adminemail','supportemail');
                   15866:                 foreach my $item (@contacts) {
                   15867:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15868:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15869:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15870:                             push(@recipients,$addr);
                   15871:                         }
1.619     raeburn  15872:                     }
1.1270    raeburn  15873:                 }
                   15874:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15875:                 if ($mailing eq 'helpdeskmail') {
                   15876:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15877:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15878:                         my @ok_bccs;
                   15879:                         foreach my $bcc (@bccs) {
                   15880:                             $bcc =~ s/^\s+//g;
                   15881:                             $bcc =~ s/\s+$//g;
                   15882:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15883:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15884:                                     push(@ok_bccs,$bcc);
                   15885:                                 }
                   15886:                             }
                   15887:                         }
                   15888:                         if (@ok_bccs > 0) {
                   15889:                             $allbcc = join(', ',@ok_bccs);
                   15890:                         }
                   15891:                     }
                   15892:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15893:                 }
                   15894:             }
1.766     raeburn  15895:         } elsif ($origmail ne '') {
1.1270    raeburn  15896:             $lastresort = $origmail;
1.618     raeburn  15897:         }
1.1297    raeburn  15898:         if ($mailing eq 'helpdeskmail') {
                   15899:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15900:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15901:                 my ($inststatus,$inststatus_checked);
                   15902:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15903:                     ($env{'user.domain'} ne 'public')) {
                   15904:                     $inststatus_checked = 1;
                   15905:                     $inststatus = $env{'environment.inststatus'};
                   15906:                 }
                   15907:                 unless ($inststatus_checked) {
                   15908:                     if (($requname ne '') && ($requdom ne '')) {
                   15909:                         if (($requname =~ /^$match_username$/) &&
                   15910:                             ($requdom =~ /^$match_domain$/) &&
                   15911:                             (&Apache::lonnet::domain($requdom))) {
                   15912:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15913:                                                                       $requdom);
                   15914:                             unless ($requhome eq 'no_host') {
                   15915:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15916:                                 $inststatus = $userenv{'inststatus'};
                   15917:                                 $inststatus_checked = 1;
                   15918:                             }
                   15919:                         }
                   15920:                     }
                   15921:                 }
                   15922:                 unless ($inststatus_checked) {
                   15923:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15924:                         my %srch = (srchby     => 'email',
                   15925:                                     srchdomain => $defdom,
                   15926:                                     srchterm   => $reqemail,
                   15927:                                     srchtype   => 'exact');
                   15928:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15929:                         foreach my $uname (keys(%srch_results)) {
                   15930:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15931:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15932:                                 $inststatus_checked = 1;
                   15933:                                 last;
                   15934:                             }
                   15935:                         }
                   15936:                         unless ($inststatus_checked) {
                   15937:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15938:                             if ($dirsrchres eq 'ok') {
                   15939:                                 foreach my $uname (keys(%srch_results)) {
                   15940:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15941:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15942:                                         $inststatus_checked = 1;
                   15943:                                         last;
                   15944:                                     }
                   15945:                                 }
                   15946:                             }
                   15947:                         }
                   15948:                     }
                   15949:                 }
                   15950:                 if ($inststatus ne '') {
                   15951:                     foreach my $status (split(/\:/,$inststatus)) {
                   15952:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15953:                             my @contacts = ('adminemail','supportemail');
                   15954:                             foreach my $item (@contacts) {
                   15955:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15956:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15957:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15958:                                         push(@recipients,$addr);
                   15959:                                     }
                   15960:                                 }
                   15961:                             }
                   15962:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15963:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15964:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15965:                                 my @ok_bccs;
                   15966:                                 foreach my $bcc (@bccs) {
                   15967:                                     $bcc =~ s/^\s+//g;
                   15968:                                     $bcc =~ s/\s+$//g;
                   15969:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15970:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15971:                                             push(@ok_bccs,$bcc);
                   15972:                                         }
                   15973:                                     }
                   15974:                                 }
                   15975:                                 if (@ok_bccs > 0) {
                   15976:                                     $allbcc = join(', ',@ok_bccs);
                   15977:                                 }
                   15978:                             }
                   15979:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15980:                             last;
                   15981:                         }
                   15982:                     }
                   15983:                 }
                   15984:             }
                   15985:         }
1.619     raeburn  15986:     } elsif ($origmail ne '') {
1.1270    raeburn  15987:         $lastresort = $origmail;
                   15988:     }
1.1297    raeburn  15989:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15990:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15991:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15992:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15993:             my %what = (
                   15994:                           perlvar => 1,
                   15995:                        );
                   15996:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15997:             if ($primary) {
                   15998:                 my $gotaddr;
                   15999:                 my ($result,$returnhash) =
                   16000:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16001:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16002:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16003:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16004:                         $gotaddr = 1;
                   16005:                     }
                   16006:                 }
                   16007:                 unless ($gotaddr) {
                   16008:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16009:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16010:                     unless ($uintdom eq $intdom) {
                   16011:                         my %domconfig =
                   16012:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16013:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16014:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16015:                                 my @contacts = ('adminemail','supportemail');
                   16016:                                 foreach my $item (@contacts) {
                   16017:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16018:                                         my $addr = $domconfig{'contacts'}{$item};
                   16019:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16020:                                             push(@recipients,$addr);
                   16021:                                         }
                   16022:                                     }
                   16023:                                 }
                   16024:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16025:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16026:                                 }
                   16027:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16028:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16029:                                     my @ok_bccs;
                   16030:                                     foreach my $bcc (@bccs) {
                   16031:                                         $bcc =~ s/^\s+//g;
                   16032:                                         $bcc =~ s/\s+$//g;
                   16033:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16034:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16035:                                                 push(@ok_bccs,$bcc);
                   16036:                                             }
                   16037:                                         }
                   16038:                                     }
                   16039:                                     if (@ok_bccs > 0) {
                   16040:                                         $allbcc = join(', ',@ok_bccs);
                   16041:                                     }
                   16042:                                 }
                   16043:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16044:                             }
                   16045:                         }
                   16046:                     }
                   16047:                 }
                   16048:             }
                   16049:         }
1.618     raeburn  16050:     }
1.688     raeburn  16051:     if (defined($defmail)) {
                   16052:         if ($defmail ne '') {
                   16053:             push(@recipients,$defmail);
                   16054:         }
1.618     raeburn  16055:     }
                   16056:     if ($otheremails) {
1.619     raeburn  16057:         my @others;
                   16058:         if ($otheremails =~ /,/) {
                   16059:             @others = split(/,/,$otheremails);
1.618     raeburn  16060:         } else {
1.619     raeburn  16061:             push(@others,$otheremails);
                   16062:         }
                   16063:         foreach my $addr (@others) {
                   16064:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16065:                 push(@recipients,$addr);
                   16066:             }
1.618     raeburn  16067:         }
                   16068:     }
1.1298    raeburn  16069:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16070:         if ((!@recipients) && ($lastresort ne '')) {
                   16071:             push(@recipients,$lastresort);
                   16072:         }
                   16073:     } elsif ($lastresort ne '') {
                   16074:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16075:             push(@recipients,$lastresort);
                   16076:         }
                   16077:     }
1.1271    raeburn  16078:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16079:     if (wantarray) {
                   16080:         return ($recipientlist,$allbcc,$addtext);
                   16081:     } else {
                   16082:         return $recipientlist;
                   16083:     }
1.618     raeburn  16084: }
                   16085: 
1.127     matthew  16086: ############################################################
                   16087: ############################################################
1.154     albertel 16088: 
1.655     raeburn  16089: =pod
                   16090: 
1.1224    musolffc 16091: =over 4
                   16092: 
1.1223    musolffc 16093: =item * &mime_email()
                   16094: 
                   16095: Sends an email with a possible attachment
                   16096: 
                   16097: Inputs:
                   16098: 
                   16099: =over 4
                   16100: 
                   16101: from -              Sender's email address
                   16102: 
1.1343    raeburn  16103: replyto -           Reply-To email address
                   16104: 
1.1223    musolffc 16105: to -                Email address of recipient
                   16106: 
                   16107: subject -           Subject of email
                   16108: 
                   16109: body -              Body of email
                   16110: 
                   16111: cc_string -         Carbon copy email address
                   16112: 
                   16113: bcc -               Blind carbon copy email address
                   16114: 
                   16115: attachment_path -   Path of file to be attached
                   16116: 
                   16117: file_name -         Name of file to be attached
                   16118: 
                   16119: attachment_text -   The body of an attachment of type "TEXT"
                   16120: 
                   16121: =back
                   16122: 
                   16123: =back
                   16124: 
                   16125: =cut
                   16126: 
                   16127: ############################################################
                   16128: ############################################################
                   16129: 
                   16130: sub mime_email {
1.1343    raeburn  16131:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16132:         $file_name,$attachment_text) = @_;
                   16133:  
1.1223    musolffc 16134:     my $msg = MIME::Lite->new(
                   16135:              From    => $from,
                   16136:              To      => $to,
                   16137:              Subject => $subject,
                   16138:              Type    =>'TEXT',
                   16139:              Data    => $body,
                   16140:              );
1.1343    raeburn  16141:     if ($replyto ne '') {
                   16142:         $msg->add("Reply-To" => $replyto);
                   16143:     }
1.1223    musolffc 16144:     if ($cc_string ne '') {
                   16145:         $msg->add("Cc" => $cc_string);
                   16146:     }
                   16147:     if ($bcc ne '') {
                   16148:         $msg->add("Bcc" => $bcc);
                   16149:     }
                   16150:     $msg->attr("content-type"         => "text/plain");
                   16151:     $msg->attr("content-type.charset" => "UTF-8");
                   16152:     # Attach file if given
                   16153:     if ($attachment_path) {
                   16154:         unless ($file_name) {
                   16155:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16156:         }
                   16157:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16158:         $msg->attach(Type     => $type,
                   16159:                      Path     => $attachment_path,
                   16160:                      Filename => $file_name
                   16161:                      );
                   16162:     # Otherwise attach text if given
                   16163:     } elsif ($attachment_text) {
                   16164:         $msg->attach(Type => 'TEXT',
                   16165:                      Data => $attachment_text);
                   16166:     }
                   16167:     # Send it
                   16168:     $msg->send('sendmail');
                   16169: }
                   16170: 
                   16171: ############################################################
                   16172: ############################################################
                   16173: 
                   16174: =pod
                   16175: 
1.655     raeburn  16176: =head1 Course Catalog Routines
                   16177: 
                   16178: =over 4
                   16179: 
                   16180: =item * &gather_categories()
                   16181: 
                   16182: Converts category definitions - keys of categories hash stored in  
                   16183: coursecategories in configuration.db on the primary library server in a 
                   16184: domain - to an array.  Also generates javascript and idx hash used to 
                   16185: generate Domain Coordinator interface for editing Course Categories.
                   16186: 
                   16187: Inputs:
1.663     raeburn  16188: 
1.655     raeburn  16189: categories (reference to hash of category definitions).
1.663     raeburn  16190: 
1.655     raeburn  16191: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16192:       categories and subcategories).
1.663     raeburn  16193: 
1.655     raeburn  16194: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16195:       editing Course Categories).
1.663     raeburn  16196: 
1.655     raeburn  16197: jsarray (reference to array of categories used to create Javascript arrays for
                   16198:          Domain Coordinator interface for editing Course Categories).
                   16199: 
                   16200: Returns: nothing
                   16201: 
                   16202: Side effects: populates cats, idx and jsarray. 
                   16203: 
                   16204: =cut
                   16205: 
                   16206: sub gather_categories {
                   16207:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16208:     my %counters;
                   16209:     my $num = 0;
                   16210:     foreach my $item (keys(%{$categories})) {
                   16211:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16212:         if ($container eq '' && $depth == 0) {
                   16213:             $cats->[$depth][$categories->{$item}] = $cat;
                   16214:         } else {
                   16215:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16216:         }
                   16217:         my ($escitem,$tail) = split(/:/,$item,2);
                   16218:         if ($counters{$tail} eq '') {
                   16219:             $counters{$tail} = $num;
                   16220:             $num ++;
                   16221:         }
                   16222:         if (ref($idx) eq 'HASH') {
                   16223:             $idx->{$item} = $counters{$tail};
                   16224:         }
                   16225:         if (ref($jsarray) eq 'ARRAY') {
                   16226:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16227:         }
                   16228:     }
                   16229:     return;
                   16230: }
                   16231: 
                   16232: =pod
                   16233: 
                   16234: =item * &extract_categories()
                   16235: 
                   16236: Used to generate breadcrumb trails for course categories.
                   16237: 
                   16238: Inputs:
1.663     raeburn  16239: 
1.655     raeburn  16240: categories (reference to hash of category definitions).
1.663     raeburn  16241: 
1.655     raeburn  16242: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16243:       categories and subcategories).
1.663     raeburn  16244: 
1.655     raeburn  16245: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16246: 
1.655     raeburn  16247: allitems (reference to hash - key is category key 
                   16248:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16249: 
1.655     raeburn  16250: idx (reference to hash of counters used in Domain Coordinator interface for
                   16251:       editing Course Categories).
1.663     raeburn  16252: 
1.655     raeburn  16253: jsarray (reference to array of categories used to create Javascript arrays for
                   16254:          Domain Coordinator interface for editing Course Categories).
                   16255: 
1.665     raeburn  16256: subcats (reference to hash of arrays containing all subcategories within each 
                   16257:          category, -recursive)
                   16258: 
1.1321    raeburn  16259: maxd (reference to hash used to hold max depth for all top-level categories).
                   16260: 
1.655     raeburn  16261: Returns: nothing
                   16262: 
                   16263: Side effects: populates trails and allitems hash references.
                   16264: 
                   16265: =cut
                   16266: 
                   16267: sub extract_categories {
1.1321    raeburn  16268:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16269:     if (ref($categories) eq 'HASH') {
                   16270:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16271:         if (ref($cats->[0]) eq 'ARRAY') {
                   16272:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16273:                 my $name = $cats->[0][$i];
                   16274:                 my $item = &escape($name).'::0';
                   16275:                 my $trailstr;
                   16276:                 if ($name eq 'instcode') {
                   16277:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16278:                 } elsif ($name eq 'communities') {
                   16279:                     $trailstr = &mt('Communities');
1.1239    raeburn  16280:                 } elsif ($name eq 'placement') {
                   16281:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16282:                 } else {
                   16283:                     $trailstr = $name;
                   16284:                 }
                   16285:                 if ($allitems->{$item} eq '') {
                   16286:                     push(@{$trails},$trailstr);
                   16287:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16288:                 }
                   16289:                 my @parents = ($name);
                   16290:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16291:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16292:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16293:                         if (ref($subcats) eq 'HASH') {
                   16294:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16295:                         }
1.1321    raeburn  16296:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16297:                     }
                   16298:                 } else {
                   16299:                     if (ref($subcats) eq 'HASH') {
                   16300:                         $subcats->{$item} = [];
1.655     raeburn  16301:                     }
1.1321    raeburn  16302:                     if (ref($maxd) eq 'HASH') {
                   16303:                         $maxd->{$name} = 1;
                   16304:                     }
1.655     raeburn  16305:                 }
                   16306:             }
                   16307:         }
                   16308:     }
                   16309:     return;
                   16310: }
                   16311: 
                   16312: =pod
                   16313: 
1.1162    raeburn  16314: =item * &recurse_categories()
1.655     raeburn  16315: 
                   16316: Recursively used to generate breadcrumb trails for course categories.
                   16317: 
                   16318: Inputs:
1.663     raeburn  16319: 
1.655     raeburn  16320: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16321:       categories and subcategories).
1.663     raeburn  16322: 
1.655     raeburn  16323: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16324: 
                   16325: category (current course category, for which breadcrumb trail is being generated).
                   16326: 
                   16327: trails (reference to array of breadcrumb trails for each category).
                   16328: 
1.655     raeburn  16329: allitems (reference to hash - key is category key
                   16330:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16331: 
1.655     raeburn  16332: parents (array containing containers directories for current category, 
                   16333:          back to top level). 
                   16334: 
                   16335: Returns: nothing
                   16336: 
                   16337: Side effects: populates trails and allitems hash references
                   16338: 
                   16339: =cut
                   16340: 
                   16341: sub recurse_categories {
1.1321    raeburn  16342:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16343:     my $shallower = $depth - 1;
                   16344:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16345:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16346:             my $name = $cats->[$depth]{$category}[$k];
                   16347:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16348:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16349:             if ($allitems->{$item} eq '') {
                   16350:                 push(@{$trails},$trailstr);
                   16351:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16352:             }
                   16353:             my $deeper = $depth+1;
                   16354:             push(@{$parents},$category);
1.665     raeburn  16355:             if (ref($subcats) eq 'HASH') {
                   16356:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16357:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16358:                     my $higher;
                   16359:                     if ($j > 0) {
                   16360:                         $higher = &escape($parents->[$j]).':'.
                   16361:                                   &escape($parents->[$j-1]).':'.$j;
                   16362:                     } else {
                   16363:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16364:                     }
                   16365:                     push(@{$subcats->{$higher}},$subcat);
                   16366:                 }
                   16367:             }
                   16368:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16369:                                 $subcats,$maxd);
1.655     raeburn  16370:             pop(@{$parents});
                   16371:         }
                   16372:     } else {
                   16373:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16374:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16375:         if ($allitems->{$item} eq '') {
                   16376:             push(@{$trails},$trailstr);
                   16377:             $allitems->{$item} = scalar(@{$trails})-1;
                   16378:         }
1.1321    raeburn  16379:         if (ref($maxd) eq 'HASH') {
                   16380:             if ($depth > $maxd->{$parents->[0]}) {
                   16381:                 $maxd->{$parents->[0]} = $depth;
                   16382:             }
                   16383:         }
1.655     raeburn  16384:     }
                   16385:     return;
                   16386: }
                   16387: 
1.663     raeburn  16388: =pod
                   16389: 
1.1162    raeburn  16390: =item * &assign_categories_table()
1.663     raeburn  16391: 
                   16392: Create a datatable for display of hierarchical categories in a domain,
                   16393: with checkboxes to allow a course to be categorized. 
                   16394: 
                   16395: Inputs:
                   16396: 
                   16397: cathash - reference to hash of categories defined for the domain (from
                   16398:           configuration.db)
                   16399: 
                   16400: currcat - scalar with an & separated list of categories assigned to a course. 
                   16401: 
1.919     raeburn  16402: type    - scalar contains course type (Course or Community).
                   16403: 
1.1260    raeburn  16404: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16405:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16406: 
1.663     raeburn  16407: Returns: $output (markup to be displayed) 
                   16408: 
                   16409: =cut
                   16410: 
                   16411: sub assign_categories_table {
1.1259    raeburn  16412:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16413:     my $output;
                   16414:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16415:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16416:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16417:         $maxdepth = scalar(@cats);
                   16418:         if (@cats > 0) {
                   16419:             my $itemcount = 0;
                   16420:             if (ref($cats[0]) eq 'ARRAY') {
                   16421:                 my @currcategories;
                   16422:                 if ($currcat ne '') {
                   16423:                     @currcategories = split('&',$currcat);
                   16424:                 }
1.919     raeburn  16425:                 my $table;
1.663     raeburn  16426:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16427:                     my $parent = $cats[0][$i];
1.919     raeburn  16428:                     next if ($parent eq 'instcode');
                   16429:                     if ($type eq 'Community') {
                   16430:                         next unless ($parent eq 'communities');
1.1239    raeburn  16431:                     } elsif ($type eq 'Placement') {
                   16432:                         next unless ($parent eq 'placement');
1.919     raeburn  16433:                     } else {
1.1239    raeburn  16434:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16435:                     }
1.663     raeburn  16436:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16437:                     my $item = &escape($parent).'::0';
                   16438:                     my $checked = '';
                   16439:                     if (@currcategories > 0) {
                   16440:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16441:                             $checked = ' checked="checked"';
1.663     raeburn  16442:                         }
                   16443:                     }
1.919     raeburn  16444:                     my $parent_title = $parent;
                   16445:                     if ($parent eq 'communities') {
                   16446:                         $parent_title = &mt('Communities');
1.1239    raeburn  16447:                     } elsif ($parent eq 'placement') {
                   16448:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16449:                     }
                   16450:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16451:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16452:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16453:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16454:                     my $depth = 1;
                   16455:                     push(@path,$parent);
1.1259    raeburn  16456:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16457:                     pop(@path);
1.919     raeburn  16458:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16459:                     $itemcount ++;
                   16460:                 }
1.919     raeburn  16461:                 if ($itemcount) {
                   16462:                     $output = &Apache::loncommon::start_data_table().
                   16463:                               $table.
                   16464:                               &Apache::loncommon::end_data_table();
                   16465:                 }
1.663     raeburn  16466:             }
                   16467:         }
                   16468:     }
                   16469:     return $output;
                   16470: }
                   16471: 
                   16472: =pod
                   16473: 
1.1162    raeburn  16474: =item * &assign_category_rows()
1.663     raeburn  16475: 
                   16476: Create a datatable row for display of nested categories in a domain,
                   16477: with checkboxes to allow a course to be categorized,called recursively.
                   16478: 
                   16479: Inputs:
                   16480: 
                   16481: itemcount - track row number for alternating colors
                   16482: 
                   16483: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16484:       categories and subcategories.
                   16485: 
                   16486: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16487: 
                   16488: parent - parent of current category item
                   16489: 
                   16490: path - Array containing all categories back up through the hierarchy from the
                   16491:        current category to the top level.
                   16492: 
                   16493: currcategories - reference to array of current categories assigned to the course
                   16494: 
1.1260    raeburn  16495: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16496:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16497: 
1.663     raeburn  16498: Returns: $output (markup to be displayed).
                   16499: 
                   16500: =cut
                   16501: 
                   16502: sub assign_category_rows {
1.1259    raeburn  16503:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16504:     my ($text,$name,$item,$chgstr);
                   16505:     if (ref($cats) eq 'ARRAY') {
                   16506:         my $maxdepth = scalar(@{$cats});
                   16507:         if (ref($cats->[$depth]) eq 'HASH') {
                   16508:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16509:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16510:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16511:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16512:                 for (my $j=0; $j<$numchildren; $j++) {
                   16513:                     $name = $cats->[$depth]{$parent}[$j];
                   16514:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16515:                     my $deeper = $depth+1;
                   16516:                     my $checked = '';
                   16517:                     if (ref($currcategories) eq 'ARRAY') {
                   16518:                         if (@{$currcategories} > 0) {
                   16519:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16520:                                 $checked = ' checked="checked"';
1.663     raeburn  16521:                             }
                   16522:                         }
                   16523:                     }
1.664     raeburn  16524:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16525:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16526:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16527:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16528:                              '</td><td>';
1.663     raeburn  16529:                     if (ref($path) eq 'ARRAY') {
                   16530:                         push(@{$path},$name);
1.1259    raeburn  16531:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16532:                         pop(@{$path});
                   16533:                     }
                   16534:                     $text .= '</td></tr>';
                   16535:                 }
                   16536:                 $text .= '</table></td>';
                   16537:             }
                   16538:         }
                   16539:     }
                   16540:     return $text;
                   16541: }
                   16542: 
1.1181    raeburn  16543: =pod
                   16544: 
                   16545: =back
                   16546: 
                   16547: =cut
                   16548: 
1.655     raeburn  16549: ############################################################
                   16550: ############################################################
                   16551: 
                   16552: 
1.443     albertel 16553: sub commit_customrole {
1.1408    raeburn  16554:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16555:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16556:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16557:                      $context,$othdomby,$requester);
1.630     raeburn  16558:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16559:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16560:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16561:     if (wantarray) {
                   16562:         return ($output,$result);
                   16563:     } else {
                   16564:         return $output;
                   16565:     }
1.443     albertel 16566: }
                   16567: 
                   16568: sub commit_standardrole {
1.1408    raeburn  16569:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   16570:         $othdomby,$requester) = @_;
1.1399    raeburn  16571:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  16572:     if ($context eq 'auto') {
                   16573:         $linefeed = "\n";
                   16574:     } else {
                   16575:         $linefeed = "<br />\n";
                   16576:     }  
1.443     albertel 16577:     if ($three eq 'st') {
1.1399    raeburn  16578:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  16579:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   16580:                                       $requester);
1.541     raeburn  16581:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16582:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16583:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16584:         } else {
1.541     raeburn  16585:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16586:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16587:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16588:             if ($context eq 'auto') {
                   16589:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16590:             } else {
                   16591:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16592:                &mt('Add to classlist').': <b>ok</b>';
                   16593:             }
                   16594:             $output .= $linefeed;
1.443     albertel 16595:         }
                   16596:     } else {
                   16597:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16598:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16599:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  16600:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   16601:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  16602:         if ($context eq 'auto') {
                   16603:             $output .= $result.$linefeed;
                   16604:         } else {
                   16605:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16606:         }
1.443     albertel 16607:     }
1.1399    raeburn  16608:     if (wantarray) {
                   16609:         return ($output,$result);
                   16610:     } else {
                   16611:         return $output;
                   16612:     }
1.443     albertel 16613: }
                   16614: 
                   16615: sub commit_studentrole {
1.1116    raeburn  16616:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  16617:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  16618:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16619:     if ($context eq 'auto') {
                   16620:         $linefeed = "\n";
                   16621:     } else {
                   16622:         $linefeed = '<br />'."\n";
                   16623:     }
1.443     albertel 16624:     if (defined($one) && defined($two)) {
                   16625:         my $cid=$one.'_'.$two;
                   16626:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16627:         my $secchange = 0;
                   16628:         my $expire_role_result;
                   16629:         my $modify_section_result;
1.628     raeburn  16630:         if ($oldsec ne '-1') { 
                   16631:             if ($oldsec ne $sec) {
1.443     albertel 16632:                 $secchange = 1;
1.628     raeburn  16633:                 my $now = time;
1.443     albertel 16634:                 my $uurl='/'.$cid;
                   16635:                 $uurl=~s/\_/\//g;
                   16636:                 if ($oldsec) {
                   16637:                     $uurl.='/'.$oldsec;
                   16638:                 }
1.626     raeburn  16639:                 $oldsecurl = $uurl;
1.628     raeburn  16640:                 $expire_role_result = 
1.1408    raeburn  16641:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   16642:                                                 '','','',$context,$othdomby,$requester);
                   16643:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  16644:                     if ($expire_role_result eq 'refused') {
                   16645:                         my @roles = ('st');
                   16646:                         my @statuses = ('previous');
                   16647:                         my @roledoms = ($one);
                   16648:                         my $withsec = 1;
                   16649:                         my %roleshash = 
                   16650:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16651:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16652:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16653:                             my ($oldstart,$oldend) = 
                   16654:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16655:                             if ($oldend > 0 && $oldend <= $now) {
                   16656:                                 $expire_role_result = 'ok';
                   16657:                             }
                   16658:                         }
                   16659:                     }
                   16660:                 }
1.443     albertel 16661:                 $result = $expire_role_result;
                   16662:             }
                   16663:         }
                   16664:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16665:             $modify_section_result = 
                   16666:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16667:                                                            undef,undef,undef,$sec,
                   16668:                                                            $end,$start,'','',$cid,
1.1408    raeburn  16669:                                                            '',$context,$credits,'',
                   16670:                                                            $othdomby,$requester);
1.443     albertel 16671:             if ($modify_section_result =~ /^ok/) {
                   16672:                 if ($secchange == 1) {
1.628     raeburn  16673:                     if ($sec eq '') {
                   16674:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16675:                     } else {
                   16676:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16677:                     }
1.443     albertel 16678:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16679:                     if ($sec eq '') {
                   16680:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16681:                     } else {
                   16682:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16683:                     }
1.443     albertel 16684:                 } else {
1.628     raeburn  16685:                     if ($sec eq '') {
                   16686:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16687:                     } else {
                   16688:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16689:                     }
1.443     albertel 16690:                 }
                   16691:             } else {
1.1115    raeburn  16692:                 if ($secchange) { 
1.628     raeburn  16693:                     $$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;
                   16694:                 } else {
                   16695:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16696:                 }
1.443     albertel 16697:             }
                   16698:             $result = $modify_section_result;
                   16699:         } elsif ($secchange == 1) {
1.628     raeburn  16700:             if ($oldsec eq '') {
1.1103    raeburn  16701:                 $$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  16702:             } else {
                   16703:                 $$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;
                   16704:             }
1.626     raeburn  16705:             if ($expire_role_result eq 'refused') {
                   16706:                 my $newsecurl = '/'.$cid;
                   16707:                 $newsecurl =~ s/\_/\//g;
                   16708:                 if ($sec ne '') {
                   16709:                     $newsecurl.='/'.$sec;
                   16710:                 }
                   16711:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16712:                     if ($sec eq '') {
                   16713:                         $$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;
                   16714:                     } else {
                   16715:                         $$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;
                   16716:                     }
                   16717:                 }
                   16718:             }
1.443     albertel 16719:         }
                   16720:     } else {
1.626     raeburn  16721:         $$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 16722:         $result = "error: incomplete course id\n";
                   16723:     }
                   16724:     return $result;
                   16725: }
                   16726: 
1.1108    raeburn  16727: sub show_role_extent {
                   16728:     my ($scope,$context,$role) = @_;
                   16729:     $scope =~ s{^/}{};
                   16730:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16731:     push(@courseroles,'co');
                   16732:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16733:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16734:         $scope =~ s{/}{_};
                   16735:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16736:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16737:         my ($audom,$auname) = split(/\//,$scope);
                   16738:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16739:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16740:     } else {
                   16741:         $scope =~ s{/$}{};
                   16742:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16743:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16744:     }
                   16745: }
                   16746: 
1.443     albertel 16747: ############################################################
                   16748: ############################################################
                   16749: 
1.566     albertel 16750: sub check_clone {
1.578     raeburn  16751:     my ($args,$linefeed) = @_;
1.566     albertel 16752:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16753:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16754:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16755:     my $clonetitle;
                   16756:     my @clonemsg;
1.566     albertel 16757:     my $can_clone = 0;
1.944     raeburn  16758:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16759:     if ($lctype ne 'community') {
                   16760:         $lctype = 'course';
                   16761:     }
1.566     albertel 16762:     if ($clonehome eq 'no_host') {
1.944     raeburn  16763:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16764:             push(@clonemsg,({
                   16765:                               mt => 'No new community created.',
                   16766:                               args => [],
                   16767:                             },
                   16768:                             {
                   16769:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16770:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16771:                             }));
1.908     raeburn  16772:         } else {
1.1344    raeburn  16773:             push(@clonemsg,({
                   16774:                               mt => 'No new course created.',
                   16775:                               args => [],
                   16776:                             },
                   16777:                             {
                   16778:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16779:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16780:                             }));
                   16781:         }
1.566     albertel 16782:     } else {
                   16783: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16784:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16785:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16786:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16787:                 push(@clonemsg,({
                   16788:                                   mt => 'No new community created.',
                   16789:                                   args => [],
                   16790:                                 },
                   16791:                                 {
                   16792:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16793:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16794:                                 }));
                   16795:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16796:             }
                   16797:         }
1.1262    raeburn  16798: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16799:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16800: 	    $can_clone = 1;
                   16801: 	} else {
1.1221    raeburn  16802: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16803: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16804:             if ($clonehash{'cloners'} eq '') {
                   16805:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16806:                 if ($domdefs{'canclone'}) {
                   16807:                     unless ($domdefs{'canclone'} eq 'none') {
                   16808:                         if ($domdefs{'canclone'} eq 'domain') {
                   16809:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16810:                                 $can_clone = 1;
                   16811:                             }
                   16812:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16813:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16814:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16815:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16816:                                 $can_clone = 1;
                   16817:                             }
                   16818:                         }
                   16819:                     }
                   16820:                 }
1.578     raeburn  16821:             } else {
1.1221    raeburn  16822: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16823:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16824:                     $can_clone = 1;
1.1221    raeburn  16825:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16826:                     $can_clone = 1;
1.1225    raeburn  16827:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16828:                     $can_clone = 1;
1.1221    raeburn  16829:                 }
                   16830:                 unless ($can_clone) {
1.1225    raeburn  16831:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16832:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16833:                         my (%gotdomdefaults,%gotcodedefaults);
                   16834:                         foreach my $cloner (@cloners) {
                   16835:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16836:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16837:                                 my (%codedefaults,@code_order);
                   16838:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16839:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16840:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16841:                                     }
                   16842:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16843:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16844:                                     }
                   16845:                                 } else {
                   16846:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16847:                                                                             \%codedefaults,
                   16848:                                                                             \@code_order);
                   16849:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16850:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16851:                                 }
                   16852:                                 if (@code_order > 0) {
                   16853:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16854:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16855:                                                                                 $args->{'crscode'})) {
                   16856:                                         $can_clone = 1;
                   16857:                                         last;
                   16858:                                     }
                   16859:                                 }
                   16860:                             }
                   16861:                         }
                   16862:                     }
1.1225    raeburn  16863:                 }
                   16864:             }
                   16865:             unless ($can_clone) {
                   16866:                 my $ccrole = 'cc';
                   16867:                 if ($args->{'crstype'} eq 'Community') {
                   16868:                     $ccrole = 'co';
                   16869:                 }
                   16870: 	        my %roleshash =
                   16871: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16872: 					          $args->{'ccdomain'},
                   16873:                                                   'userroles',['active'],[$ccrole],
                   16874: 					          [$args->{'clonedomain'}]);
                   16875: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16876:                     $can_clone = 1;
                   16877:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16878:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16879:                     $can_clone = 1;
1.1221    raeburn  16880:                 }
                   16881:             }
                   16882:             unless ($can_clone) {
                   16883:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16884:                     push(@clonemsg,({
                   16885:                                       mt => 'No new community created.',
                   16886:                                       args => [],
                   16887:                                     },
                   16888:                                     {
                   16889:                                       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]).',
                   16890:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16891:                                     }));
1.942     raeburn  16892:                 } else {
1.1344    raeburn  16893:                     push(@clonemsg,({
                   16894:                                       mt => 'No new course created.',
                   16895:                                       args => [],
                   16896:                                     },
                   16897:                                     {
                   16898:                                       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]).',
                   16899:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16900:                                     }));
1.1221    raeburn  16901:                 }
1.566     albertel 16902: 	    }
1.578     raeburn  16903:         }
1.566     albertel 16904:     }
1.1344    raeburn  16905:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16906: }
                   16907: 
1.444     albertel 16908: sub construct_course {
1.1262    raeburn  16909:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16910:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16911:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16912:     my $linefeed =  '<br />'."\n";
                   16913:     if ($context eq 'auto') {
                   16914:         $linefeed = "\n";
                   16915:     }
1.566     albertel 16916: 
                   16917: #
                   16918: # Are we cloning?
                   16919: #
1.1344    raeburn  16920:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16921:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16922: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16923:         if (!$can_clone) {
1.1344    raeburn  16924: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16925: 	}
                   16926:     }
                   16927: 
1.444     albertel 16928: #
                   16929: # Open course
                   16930: #
1.1239    raeburn  16931:     my $showncrstype;
                   16932:     if ($args->{'crstype'} eq 'Placement') {
                   16933:         $showncrstype = 'placement test'; 
                   16934:     } else {  
                   16935:         $showncrstype = lc($args->{'crstype'});
                   16936:     }
1.444     albertel 16937:     my %cenv=();
                   16938:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16939:                                              $args->{'cdescr'},
                   16940:                                              $args->{'curl'},
                   16941:                                              $args->{'course_home'},
                   16942:                                              $args->{'nonstandard'},
                   16943:                                              $args->{'crscode'},
                   16944:                                              $args->{'ccuname'}.':'.
                   16945:                                              $args->{'ccdomain'},
1.882     raeburn  16946:                                              $args->{'crstype'},
1.1344    raeburn  16947:                                              $cnum,$context,$category,
                   16948:                                              $callercontext);
1.444     albertel 16949: 
                   16950:     # Note: The testing routines depend on this being output; see 
                   16951:     # Utils::Course. This needs to at least be output as a comment
                   16952:     # if anyone ever decides to not show this, and Utils::Course::new
                   16953:     # will need to be suitably modified.
1.1344    raeburn  16954:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16955:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16956:     } else {
                   16957:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16958:     }
1.943     raeburn  16959:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16960:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16961:     }
                   16962: 
1.444     albertel 16963: #
                   16964: # Check if created correctly
                   16965: #
1.479     albertel 16966:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16967:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16968:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16969:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16970:             $outcome .= &mt_user($user_lh,
                   16971:                             'Course creation failed, unrecognized course home server.');
                   16972:         } else {
                   16973:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16974:         }
                   16975:         $outcome .= $linefeed;
                   16976:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16977:     }
1.541     raeburn  16978:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16979: 
1.444     albertel 16980: #
1.566     albertel 16981: # Do the cloning
                   16982: #   
1.1344    raeburn  16983:     my @clonemsg;
1.566     albertel 16984:     if ($can_clone && $cloneid) {
1.1344    raeburn  16985:         push(@clonemsg,
                   16986:                       {
                   16987:                           mt => 'Created [_1] by cloning from [_2]',
                   16988:                           args => [$showncrstype,$clonetitle],
                   16989:                       });
1.566     albertel 16990: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16991: # Copy all files
1.1344    raeburn  16992:         my @info =
                   16993: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16994: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16995:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16996:                                                      $args->{'tinyurls'});
                   16997:         if (@info) {
                   16998:             push(@clonemsg,@info);
                   16999:         }
1.444     albertel 17000: # Restore URL
1.566     albertel 17001: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17002: # Restore title
1.566     albertel 17003: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17004: # Restore creation date, creator and creation context.
                   17005:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17006:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17007:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17008: # Mark as cloned
1.566     albertel 17009: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17010: # Need to clone grading mode
                   17011:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17012:         $cenv{'grading'}=$newenv{'grading'};
                   17013: # Do not clone these environment entries
                   17014:         &Apache::lonnet::del('environment',
                   17015:                   ['default_enrollment_start_date',
                   17016:                    'default_enrollment_end_date',
                   17017:                    'question.email',
                   17018:                    'policy.email',
                   17019:                    'comment.email',
                   17020:                    'pch.users.denied',
1.725     raeburn  17021:                    'plc.users.denied',
                   17022:                    'hidefromcat',
1.1121    raeburn  17023:                    'checkforpriv',
1.1355    raeburn  17024:                    'categories'],
1.638     www      17025:                    $$crsudom,$$crsunum);
1.1170    raeburn  17026:         if ($args->{'textbook'}) {
                   17027:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17028:         }
1.444     albertel 17029:     }
1.566     albertel 17030: 
1.444     albertel 17031: #
                   17032: # Set environment (will override cloned, if existing)
                   17033: #
                   17034:     my @sections = ();
                   17035:     my @xlists = ();
                   17036:     if ($args->{'crstype'}) {
                   17037:         $cenv{'type'}=$args->{'crstype'};
                   17038:     }
1.1371    raeburn  17039:     if ($args->{'lti'}) {
                   17040:         $cenv{'internal.lti'}=$args->{'lti'};
                   17041:     }
1.444     albertel 17042:     if ($args->{'crsid'}) {
                   17043:         $cenv{'courseid'}=$args->{'crsid'};
                   17044:     }
                   17045:     if ($args->{'crscode'}) {
                   17046:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17047:     }
                   17048:     if ($args->{'crsquota'} ne '') {
                   17049:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17050:     } else {
                   17051:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17052:     }
                   17053:     if ($args->{'ccuname'}) {
                   17054:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17055:                                         ':'.$args->{'ccdomain'};
                   17056:     } else {
                   17057:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17058:     }
1.1116    raeburn  17059:     if ($args->{'defaultcredits'}) {
                   17060:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17061:     }
1.444     albertel 17062:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17063:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17064:     if ($args->{'crssections'}) {
                   17065:         $cenv{'internal.sectionnums'} = '';
                   17066:         if ($args->{'crssections'} =~ m/,/) {
                   17067:             @sections = split/,/,$args->{'crssections'};
                   17068:         } else {
                   17069:             $sections[0] = $args->{'crssections'};
                   17070:         }
                   17071:         if (@sections > 0) {
                   17072:             foreach my $item (@sections) {
                   17073:                 my ($sec,$gp) = split/:/,$item;
                   17074:                 my $class = $args->{'crscode'}.$sec;
                   17075:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17076:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17077:                 if ($addcheck eq 'ok') {
                   17078:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17079:                         push(@oklcsecs,$gp);
                   17080:                     }
                   17081:                 } else {
1.1263    raeburn  17082:                     push(@badclasses,$class);
1.444     albertel 17083:                 }
                   17084:             }
                   17085:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17086:         }
                   17087:     }
                   17088: # do not hide course coordinator from staff listing, 
                   17089: # even if privileged
                   17090:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17091: # add course coordinator's domain to domains to check for privileged users
                   17092: # if different to course domain
                   17093:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17094:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17095:     }
1.444     albertel 17096: # add crosslistings
                   17097:     if ($args->{'crsxlist'}) {
                   17098:         $cenv{'internal.crosslistings'}='';
                   17099:         if ($args->{'crsxlist'} =~ m/,/) {
                   17100:             @xlists = split/,/,$args->{'crsxlist'};
                   17101:         } else {
                   17102:             $xlists[0] = $args->{'crsxlist'};
                   17103:         }
                   17104:         if (@xlists > 0) {
                   17105:             foreach my $item (@xlists) {
                   17106:                 my ($xl,$gp) = split/:/,$item;
                   17107:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17108:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17109:                 if ($addcheck eq 'ok') {
                   17110:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17111:                         push(@oklcsecs,$gp);
                   17112:                     }
                   17113:                 } else {
1.1263    raeburn  17114:                     push(@badclasses,$xl);
1.444     albertel 17115:                 }
                   17116:             }
                   17117:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17118:         }
                   17119:     }
                   17120:     if ($args->{'autoadds'}) {
                   17121:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17122:     }
                   17123:     if ($args->{'autodrops'}) {
                   17124:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17125:     }
                   17126: # check for notification of enrollment changes
                   17127:     my @notified = ();
                   17128:     if ($args->{'notify_owner'}) {
                   17129:         if ($args->{'ccuname'} ne '') {
                   17130:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17131:         }
                   17132:     }
                   17133:     if ($args->{'notify_dc'}) {
                   17134:         if ($uname ne '') { 
1.630     raeburn  17135:             push(@notified,$uname.':'.$udom);
1.444     albertel 17136:         }
                   17137:     }
                   17138:     if (@notified > 0) {
                   17139:         my $notifylist;
                   17140:         if (@notified > 1) {
                   17141:             $notifylist = join(',',@notified);
                   17142:         } else {
                   17143:             $notifylist = $notified[0];
                   17144:         }
                   17145:         $cenv{'internal.notifylist'} = $notifylist;
                   17146:     }
                   17147:     if (@badclasses > 0) {
                   17148:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17149:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17150:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17151:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17152:         );
1.1264    raeburn  17153:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17154:                            &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  17155:         if ($context eq 'auto') {
                   17156:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17157:         } else {
1.566     albertel 17158:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17159:         }
                   17160:         foreach my $item (@badclasses) {
1.541     raeburn  17161:             if ($context eq 'auto') {
1.1261    raeburn  17162:                 $outcome .= " - $item\n";
1.541     raeburn  17163:             } else {
1.1261    raeburn  17164:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17165:             }
1.1261    raeburn  17166:         }
                   17167:         if ($context eq 'auto') {
                   17168:             $outcome .= $linefeed;
                   17169:         } else {
                   17170:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17171:         } 
1.444     albertel 17172:     }
                   17173:     if ($args->{'no_end_date'}) {
                   17174:         $args->{'endaccess'} = 0;
                   17175:     }
1.1412    raeburn  17176: #  If an official course with institutional sections is created by cloning 
                   17177: #  an existing course, section-specific hiding of course totals in student's
                   17178: #  view of grades as copied from cloned course, will be checked for valid 
                   17179: #  sections.
                   17180:     if (($can_clone && $cloneid) &&
                   17181:         ($cenv{'internal.coursecode'} ne '') &&
                   17182:         ($cenv{'grading'} eq 'standard') &&
                   17183:         ($cenv{'hidetotals'} ne '') &&
                   17184:         ($cenv{'hidetotals'} ne 'all')) {
                   17185:         my @hidesecs;
                   17186:         my $deletehidetotals;
                   17187:         if (@oklcsecs) {
                   17188:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17189:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17190:                     push(@hidesecs,$sec);
                   17191:                 }
                   17192:             }
                   17193:             if (@hidesecs) {
                   17194:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17195:             } else {
                   17196:                 $deletehidetotals = 1;
                   17197:             }
                   17198:         } else {
                   17199:             $deletehidetotals = 1;
                   17200:         }
                   17201:         if ($deletehidetotals) {
                   17202:             delete($cenv{'hidetotals'});
                   17203:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17204:         }
                   17205:     }
1.444     albertel 17206:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17207:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17208:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17209:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17210:     if ($args->{'showphotos'}) {
                   17211:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17212:     }
                   17213:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17214:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17215:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17216:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17217:             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'); 
                   17218:             if ($context eq 'auto') {
                   17219:                 $outcome .= $krb_msg;
                   17220:             } else {
1.566     albertel 17221:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17222:             }
                   17223:             $outcome .= $linefeed;
1.444     albertel 17224:         }
                   17225:     }
                   17226:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17227:        if ($args->{'setpolicy'}) {
                   17228:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17229:        }
                   17230:        if ($args->{'setcontent'}) {
                   17231:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17232:        }
1.1251    raeburn  17233:        if ($args->{'setcomment'}) {
                   17234:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17235:        }
1.444     albertel 17236:     }
                   17237:     if ($args->{'reshome'}) {
                   17238: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17239: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17240:     }
                   17241: #
                   17242: # course has keyed access
                   17243: #
                   17244:     if ($args->{'setkeys'}) {
                   17245:        $cenv{'keyaccess'}='yes';
                   17246:     }
                   17247: # if specified, key authority is not course, but user
                   17248: # only active if keyaccess is yes
                   17249:     if ($args->{'keyauth'}) {
1.487     albertel 17250: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17251: 	$user = &LONCAPA::clean_username($user);
                   17252: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17253: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17254: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17255: 	}
                   17256:     }
                   17257: 
1.1166    raeburn  17258: #
1.1167    raeburn  17259: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17260: #
                   17261:     if ($args->{'uniquecode'}) {
                   17262:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17263:         if ($code) {
                   17264:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17265:             my %crsinfo =
                   17266:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17267:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17268:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17269:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17270:             } 
1.1166    raeburn  17271:             if (ref($coderef)) {
                   17272:                 $$coderef = $code;
                   17273:             }
                   17274:         }
                   17275:     }
                   17276: 
1.444     albertel 17277:     if ($args->{'disresdis'}) {
                   17278:         $cenv{'pch.roles.denied'}='st';
                   17279:     }
                   17280:     if ($args->{'disablechat'}) {
                   17281:         $cenv{'plc.roles.denied'}='st';
                   17282:     }
                   17283: 
                   17284:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17285:     # course
                   17286:     $cenv{'course.helper.not.run'} = 1;
                   17287:     #
                   17288:     # Use new Randomseed
                   17289:     #
                   17290:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17291:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17292:     #
                   17293:     # The encryption code and receipt prefix for this course
                   17294:     #
                   17295:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17296:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17297:     #
                   17298:     # By default, use standard grading
                   17299:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17300: 
1.541     raeburn  17301:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17302:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17303: #
                   17304: # Open all assignments
                   17305: #
                   17306:     if ($args->{'openall'}) {
1.1341    raeburn  17307:        my $opendate = time;
                   17308:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17309:            $opendate = $args->{'openallfrom'};
                   17310:        }
1.444     albertel 17311:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17312:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17313:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17314:        $outcome .= &mt('All assignments open starting [_1]',
                   17315:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17316:                    &Apache::lonnet::cput
                   17317:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17318:    }
                   17319: #
                   17320: # Set first page
                   17321: #
                   17322:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17323: 	    || ($cloneid)) {
                   17324: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17325: 
                   17326: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17327:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17328: 
1.444     albertel 17329:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17330:         my $title; my $url;
                   17331:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17332: 	    $title=&mt('Syllabus');
1.444     albertel 17333:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17334:         } else {
1.963     raeburn  17335:             $title=&mt('Table of Contents');
1.444     albertel 17336:             $url='/adm/navmaps';
                   17337:         }
1.445     albertel 17338: 
                   17339:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17340: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17341: 
                   17342: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17343:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17344:     }
1.566     albertel 17345: 
1.1237    raeburn  17346: # 
                   17347: # Set params for Placement Tests
                   17348: #
1.1239    raeburn  17349:     if ($args->{'crstype'} eq 'Placement') {
                   17350:        my %storecontent; 
                   17351:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17352:        my %defaults = (
                   17353:                         buttonshide   => { value => 'yes',
                   17354:                                            type => 'string_yesno',},
                   17355:                         type          => { value => 'randomizetry',
                   17356:                                            type  => 'string_questiontype',},
                   17357:                         maxtries      => { value => 1,
                   17358:                                            type => 'int_pos',},
                   17359:                         problemstatus => { value => 'no',
                   17360:                                            type  => 'string_problemstatus',},
                   17361:                       );
                   17362:        foreach my $key (keys(%defaults)) {
                   17363:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17364:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17365:        }
1.1237    raeburn  17366:        &Apache::lonnet::cput
                   17367:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17368:     }
                   17369: 
1.1344    raeburn  17370:     return (1,$outcome,\@clonemsg);
1.444     albertel 17371: }
                   17372: 
1.1166    raeburn  17373: sub make_unique_code {
                   17374:     my ($cdom,$cnum) = @_;
                   17375:     # get lock on uniquecodes db
                   17376:     my $lockhash = {
                   17377:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17378:                                                   ':'.$env{'user.domain'},
                   17379:                    };
                   17380:     my $tries = 0;
                   17381:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17382:     my ($code,$error);
                   17383:   
                   17384:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17385:         $tries ++;
                   17386:         sleep 1;
                   17387:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17388:     }
                   17389:     if ($gotlock eq 'ok') {
                   17390:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17391:         my $gotcode;
                   17392:         my $attempts = 0;
                   17393:         while ((!$gotcode) && ($attempts < 100)) {
                   17394:             $code = &generate_code();
                   17395:             if (!exists($currcodes{$code})) {
                   17396:                 $gotcode = 1;
                   17397:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17398:                     $error = 'nostore';
                   17399:                 }
                   17400:             }
                   17401:             $attempts ++;
                   17402:         }
                   17403:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17404:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17405:     } else {
                   17406:         $error = 'nolock';
                   17407:     }
                   17408:     return ($code,$error);
                   17409: }
                   17410: 
                   17411: sub generate_code {
                   17412:     my $code;
                   17413:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17414:     for (my $i=0; $i<6; $i++) {
                   17415:         my $lettnum = int (rand 2);
                   17416:         my $item = '';
                   17417:         if ($lettnum) {
                   17418:             $item = $letts[int( rand(18) )];
                   17419:         } else {
                   17420:             $item = 1+int( rand(8) );
                   17421:         }
                   17422:         $code .= $item;
                   17423:     }
                   17424:     return $code;
                   17425: }
                   17426: 
1.444     albertel 17427: ############################################################
                   17428: ############################################################
                   17429: 
1.1237    raeburn  17430: # Community, Course and Placement Test
1.378     raeburn  17431: sub course_type {
                   17432:     my ($cid) = @_;
                   17433:     if (!defined($cid)) {
                   17434:         $cid = $env{'request.course.id'};
                   17435:     }
1.404     albertel 17436:     if (defined($env{'course.'.$cid.'.type'})) {
                   17437:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17438:     } else {
                   17439:         return 'Course';
1.377     raeburn  17440:     }
                   17441: }
1.156     albertel 17442: 
1.406     raeburn  17443: sub group_term {
                   17444:     my $crstype = &course_type();
                   17445:     my %names = (
                   17446:                   'Course' => 'group',
1.865     raeburn  17447:                   'Community' => 'group',
1.1237    raeburn  17448:                   'Placement' => 'group',
1.406     raeburn  17449:                 );
                   17450:     return $names{$crstype};
                   17451: }
                   17452: 
1.902     raeburn  17453: sub course_types {
1.1310    raeburn  17454:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17455:     my %typename = (
                   17456:                          official   => 'Official course',
                   17457:                          unofficial => 'Unofficial course',
                   17458:                          community  => 'Community',
1.1165    raeburn  17459:                          textbook   => 'Textbook course',
1.1237    raeburn  17460:                          placement  => 'Placement test',
1.1310    raeburn  17461:                          lti        => 'LTI provider',
1.902     raeburn  17462:                    );
                   17463:     return (\@types,\%typename);
                   17464: }
                   17465: 
1.156     albertel 17466: sub icon {
                   17467:     my ($file)=@_;
1.505     albertel 17468:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17469:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17470:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17471:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17472: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17473: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17474: 	            $curfext.".gif") {
                   17475: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17476: 		$curfext.".gif";
                   17477: 	}
                   17478:     }
1.249     albertel 17479:     return &lonhttpdurl($iconname);
1.154     albertel 17480: } 
1.84      albertel 17481: 
1.575     albertel 17482: sub lonhttpdurl {
1.692     www      17483: #
                   17484: # Had been used for "small fry" static images on separate port 8080.
                   17485: # Modify here if lightweight http functionality desired again.
                   17486: # Currently eliminated due to increasing firewall issues.
                   17487: #
1.575     albertel 17488:     my ($url)=@_;
1.692     www      17489:     return $url;
1.215     albertel 17490: }
                   17491: 
1.213     albertel 17492: sub connection_aborted {
                   17493:     my ($r)=@_;
                   17494:     $r->print(" ");$r->rflush();
                   17495:     my $c = $r->connection;
                   17496:     return $c->aborted();
                   17497: }
                   17498: 
1.221     foxr     17499: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17500: #    strings as 'strings'.
                   17501: sub escape_single {
1.221     foxr     17502:     my ($input) = @_;
1.223     albertel 17503:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17504:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17505:     return $input;
                   17506: }
1.223     albertel 17507: 
1.222     foxr     17508: #  Same as escape_single, but escape's "'s  This 
                   17509: #  can be used for  "strings"
                   17510: sub escape_double {
                   17511:     my ($input) = @_;
                   17512:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17513:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17514:     return $input;
                   17515: }
1.223     albertel 17516:  
1.222     foxr     17517: #   Escapes the last element of a full URL.
                   17518: sub escape_url {
                   17519:     my ($url)   = @_;
1.238     raeburn  17520:     my @urlslices = split(/\//, $url,-1);
1.369     www      17521:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17522:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17523: }
1.462     albertel 17524: 
1.820     raeburn  17525: sub compare_arrays {
                   17526:     my ($arrayref1,$arrayref2) = @_;
                   17527:     my (@difference,%count);
                   17528:     @difference = ();
                   17529:     %count = ();
                   17530:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17531:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17532:         foreach my $element (keys(%count)) {
                   17533:             if ($count{$element} == 1) {
                   17534:                 push(@difference,$element);
                   17535:             }
                   17536:         }
                   17537:     }
                   17538:     return @difference;
                   17539: }
                   17540: 
1.1322    raeburn  17541: sub lon_status_items {
                   17542:     my %defaults = (
                   17543:                      E         => 100,
                   17544:                      W         => 4,
                   17545:                      N         => 1,
1.1324    raeburn  17546:                      U         => 5,
1.1322    raeburn  17547:                      threshold => 200,
                   17548:                      sysmail   => 2500,
                   17549:                    );
                   17550:     my %names = (
                   17551:                    E => 'Errors',
                   17552:                    W => 'Warnings',
                   17553:                    N => 'Notices',
1.1324    raeburn  17554:                    U => 'Unsent',
1.1322    raeburn  17555:                 );
                   17556:     return (\%defaults,\%names);
                   17557: }
                   17558: 
1.817     bisitz   17559: # -------------------------------------------------------- Initialize user login
1.462     albertel 17560: sub init_user_environment {
1.463     albertel 17561:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17562:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17563: 
                   17564:     my $public=($username eq 'public' && $domain eq 'public');
                   17565: 
1.1062    raeburn  17566:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17567:     my $now=time;
                   17568: 
                   17569:     if ($public) {
                   17570: 	my $max_public=100;
                   17571: 	my $oldest;
                   17572: 	my $oldest_time=0;
                   17573: 	for(my $next=1;$next<=$max_public;$next++) {
                   17574: 	    if (-e $lonids."/publicuser_$next.id") {
                   17575: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17576: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17577: 		    $oldest_time=$mtime;
                   17578: 		    $oldest=$next;
                   17579: 		}
                   17580: 	    } else {
                   17581: 		$cookie="publicuser_$next";
                   17582: 		last;
                   17583: 	    }
                   17584: 	}
                   17585: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17586:     } else {
1.1275    raeburn  17587: 	# See if old ID present, if so, remove if this isn't a robot,
                   17588: 	# killing any existing non-robot sessions
1.463     albertel 17589: 	if (!$args->{'robot'}) {
                   17590: 	    opendir(DIR,$lonids);
                   17591: 	    while ($filename=readdir(DIR)) {
                   17592: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17593:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17594:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17595:                         my $linkedfile;
1.1320    raeburn  17596:                         if (exists($oldenv{'user.linkedenv'})) {
                   17597:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17598:                         }
1.1320    raeburn  17599:                         untie(%oldenv);
                   17600:                         if (unlink("$lonids/$filename")) {
                   17601:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17602:                                 if (-l "$lonids/$linkedfile.id") {
                   17603:                                     unlink("$lonids/$linkedfile.id");
                   17604:                                 }
1.1295    raeburn  17605:                             }
                   17606:                         }
                   17607:                     } else {
                   17608:                         unlink($lonids.'/'.$filename);
                   17609:                     }
1.463     albertel 17610: 		}
1.462     albertel 17611: 	    }
1.463     albertel 17612: 	    closedir(DIR);
1.1204    raeburn  17613: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17614:             my $namespace = 'nohist_courseeditor';
                   17615:             my $lockingkey = 'paste'."\0".'locked_num';
                   17616:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17617:                                                 $domain,$username);
                   17618:             if (exists($lockhash{$lockingkey})) {
                   17619:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17620:                 unless ($delresult eq 'ok') {
                   17621:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17622:                 }
                   17623:             }
1.462     albertel 17624: 	}
                   17625: # Give them a new cookie
1.463     albertel 17626: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17627: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17628: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17629:     
                   17630: # Initialize roles
                   17631: 
1.1414  ! raeburn  17632: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17633:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17634:     }
                   17635: # ------------------------------------ Check browser type and MathML capability
                   17636: 
1.1194    raeburn  17637:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17638:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17639: 
                   17640: # ------------------------------------------------------------- Get environment
                   17641: 
                   17642:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17643:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17644:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17645: 	undef(%userenv);
                   17646:     }
                   17647:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17648: 	$form->{'interface'}=$userenv{'interface'};
                   17649:     }
                   17650:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17651: 
                   17652: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17653:     foreach my $option ('interface','localpath','localres') {
                   17654:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17655:     }
                   17656: # --------------------------------------------------------- Write first profile
                   17657: 
                   17658:     {
1.1350    raeburn  17659:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17660: 	my %initial_env = 
                   17661: 	    ("user.name"          => $username,
                   17662: 	     "user.domain"        => $domain,
                   17663: 	     "user.home"          => $authhost,
                   17664: 	     "browser.type"       => $clientbrowser,
                   17665: 	     "browser.version"    => $clientversion,
                   17666: 	     "browser.mathml"     => $clientmathml,
                   17667: 	     "browser.unicode"    => $clientunicode,
                   17668: 	     "browser.os"         => $clientos,
1.1137    raeburn  17669:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17670:              "browser.info"       => $clientinfo,
1.1194    raeburn  17671:              "browser.osversion"  => $clientosversion,
1.462     albertel 17672: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17673: 	     "request.course.fn"  => '',
                   17674: 	     "request.course.uri" => '',
                   17675: 	     "request.course.sec" => '',
                   17676: 	     "request.role"       => 'cm',
                   17677: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17678: 	     "request.host"       => $ip,);
1.462     albertel 17679: 
                   17680:         if ($form->{'localpath'}) {
                   17681: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17682: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17683:         }
                   17684: 	
                   17685: 	if ($form->{'interface'}) {
                   17686: 	    $form->{'interface'}=~s/\W//gs;
                   17687: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17688: 	    $env{'browser.interface'}=$form->{'interface'};
                   17689: 	}
                   17690: 
1.1157    raeburn  17691:         if ($form->{'iptoken'}) {
                   17692:             my $lonhost = $r->dir_config('lonHostID');
                   17693:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17694:             $env{'user.noloadbalance'} = $lonhost;
                   17695:         }
                   17696: 
1.1268    raeburn  17697:         if ($form->{'noloadbalance'}) {
                   17698:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17699:             my $hosthere = $form->{'noloadbalance'};
                   17700:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17701:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17702:                 $env{'user.noloadbalance'} = $hosthere;
                   17703:             }
                   17704:         }
                   17705: 
1.1016    raeburn  17706:         unless ($domain eq 'public') {
1.1273    raeburn  17707:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17708:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17709: 
1.1414  ! raeburn  17710:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
        !          17711:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  17712:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17713:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17714:             }
1.980     raeburn  17715: 
1.1311    raeburn  17716:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17717:                 $userenv{'canrequest.'.$crstype} =
                   17718:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17719:                                                       'reload','requestcourses',
                   17720:                                                       \%userenv,\%domdef,\%is_adv);
                   17721:             }
1.724     raeburn  17722: 
1.1273    raeburn  17723:             $userenv{'canrequest.author'} =
                   17724:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17725:                                                   'reload','requestauthor',
1.980     raeburn  17726:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17727:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17728:                                                  $domain,$username);
                   17729:             my $reqstatus = $reqauthor{'author_status'};
                   17730:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17731:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17732:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17733:                                                       $reqauthor{'author'}{'timestamp'};
                   17734:                 }
1.1092    raeburn  17735:             }
1.1287    raeburn  17736:             my ($types,$typename) = &course_types();
                   17737:             if (ref($types) eq 'ARRAY') {
                   17738:                 my @options = ('approval','validate','autolimit');
                   17739:                 my $optregex = join('|',@options);
                   17740:                 my (%willtrust,%trustchecked);
                   17741:                 foreach my $type (@{$types}) {
                   17742:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17743:                     if ($dom_str ne '') {
                   17744:                         my $updatedstr = '';
                   17745:                         my @possdomains = split(',',$dom_str);
                   17746:                         foreach my $entry (@possdomains) {
                   17747:                             my ($extdom,$extopt) = split(':',$entry);
                   17748:                             unless ($trustchecked{$extdom}) {
                   17749:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17750:                                 $trustchecked{$extdom} = 1;
                   17751:                             }
                   17752:                             if ($willtrust{$extdom}) {
                   17753:                                 $updatedstr .= $entry.',';
                   17754:                             }
                   17755:                         }
                   17756:                         $updatedstr =~ s/,$//;
                   17757:                         if ($updatedstr) {
                   17758:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17759:                         } else {
                   17760:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17761:                         }
                   17762:                     }
                   17763:                 }
                   17764:             }
1.1092    raeburn  17765:         }
1.462     albertel 17766: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17767: 
1.462     albertel 17768: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17769: 		 &GDBM_WRCREAT(),0640)) {
                   17770: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17771: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17772: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17773:             if (ref($firstaccenv) eq 'HASH') {
                   17774:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17775:             }
                   17776:             if (ref($timerintenv) eq 'HASH') {
                   17777:                 &_add_to_env(\%disk_env,$timerintenv);
                   17778:             }
1.1414  ! raeburn  17779:             if (ref($coauthorenv) eq 'HASH') {
        !          17780:                 if (keys(%{$coauthorenv})) {
        !          17781:                     &_add_to_env(\%disk_env,$coauthorenv);
        !          17782:                 }
        !          17783:             }
1.463     albertel 17784: 	    if (ref($args->{'extra_env'})) {
                   17785: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17786: 	    }
1.462     albertel 17787: 	    untie(%disk_env);
                   17788: 	} else {
1.705     tempelho 17789: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17790: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17791: 	    return 'error: '.$!;
                   17792: 	}
                   17793:     }
                   17794:     $env{'request.role'}='cm';
                   17795:     $env{'request.role.adv'}=$env{'user.adv'};
                   17796:     $env{'browser.type'}=$clientbrowser;
                   17797: 
                   17798:     return $cookie;
                   17799: 
                   17800: }
                   17801: 
                   17802: sub _add_to_env {
                   17803:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17804:     if (ref($env_data) eq 'HASH') {
                   17805:         while (my ($key,$value) = each(%$env_data)) {
                   17806: 	    $idf->{$prefix.$key} = $value;
                   17807: 	    $env{$prefix.$key}   = $value;
                   17808:         }
1.462     albertel 17809:     }
                   17810: }
                   17811: 
1.685     tempelho 17812: # --- Get the symbolic name of a problem and the url
                   17813: sub get_symb {
                   17814:     my ($request,$silent) = @_;
1.726     raeburn  17815:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17816:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17817:     if ($symb eq '') {
                   17818:         if (!$silent) {
1.1071    raeburn  17819:             if (ref($request)) { 
                   17820:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17821:             }
1.685     tempelho 17822:             return ();
                   17823:         }
                   17824:     }
                   17825:     &Apache::lonenc::check_decrypt(\$symb);
                   17826:     return ($symb);
                   17827: }
                   17828: 
                   17829: # --------------------------------------------------------------Get annotation
                   17830: 
                   17831: sub get_annotation {
                   17832:     my ($symb,$enc) = @_;
                   17833: 
                   17834:     my $key = $symb;
                   17835:     if (!$enc) {
                   17836:         $key =
                   17837:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17838:     }
                   17839:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17840:     return $annotation{$key};
                   17841: }
                   17842: 
                   17843: sub clean_symb {
1.731     raeburn  17844:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17845: 
                   17846:     &Apache::lonenc::check_decrypt(\$symb);
                   17847:     my $enc = $env{'request.enc'};
1.731     raeburn  17848:     if ($delete_enc) {
1.730     raeburn  17849:         delete($env{'request.enc'});
                   17850:     }
1.685     tempelho 17851: 
                   17852:     return ($symb,$enc);
                   17853: }
1.462     albertel 17854: 
1.1181    raeburn  17855: ############################################################
                   17856: ############################################################
                   17857: 
                   17858: =pod
                   17859: 
                   17860: =head1 Routines for building display used to search for courses
                   17861: 
                   17862: 
                   17863: =over 4
                   17864: 
                   17865: =item * &build_filters()
                   17866: 
                   17867: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17868: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17869: and quotacheck.pl
                   17870: 
1.1181    raeburn  17871: 
                   17872: Inputs:
                   17873: 
                   17874: filterlist - anonymous array of fields to include as potential filters 
                   17875: 
                   17876: crstype - course type
                   17877: 
                   17878: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17879:               to pop-open a course selector (will contain "extra element"). 
                   17880: 
                   17881: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17882: 
                   17883: filter - anonymous hash of criteria and their values
                   17884: 
                   17885: action - form action
                   17886: 
                   17887: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17888: 
1.1182    raeburn  17889: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17890: 
                   17891: cloneruname - username of owner of new course who wants to clone
                   17892: 
                   17893: clonerudom - domain of owner of new course who wants to clone
                   17894: 
                   17895: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17896: 
                   17897: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17898: 
                   17899: codedom - domain
                   17900: 
                   17901: formname - value of form element named "form". 
                   17902: 
                   17903: fixeddom - domain, if fixed.
                   17904: 
                   17905: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17906: 
                   17907: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17908: 
                   17909: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17910: 
                   17911: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17912: 
                   17913: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17914: 
                   17915: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17916: 
                   17917: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17918: 
1.1182    raeburn  17919: 
1.1181    raeburn  17920: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17921: 
1.1182    raeburn  17922: 
1.1181    raeburn  17923: Side Effects: None
                   17924: 
                   17925: =cut
                   17926: 
                   17927: # ---------------------------------------------- search for courses based on last activity etc.
                   17928: 
                   17929: sub build_filters {
                   17930:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17931:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17932:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17933:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17934:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17935:     my ($list,$jscript);
1.1181    raeburn  17936:     my $onchange = 'javascript:updateFilters(this)';
                   17937:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17938:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17939:         $typeselectform,$instcodetitle);
                   17940:     if ($formname eq '') {
                   17941:         $formname = $caller;
                   17942:     }
                   17943:     foreach my $item (@{$filterlist}) {
                   17944:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17945:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17946:             if ($item eq 'domainfilter') {
                   17947:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17948:             } elsif ($item eq 'coursefilter') {
                   17949:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17950:             } elsif ($item eq 'ownerfilter') {
                   17951:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17952:             } elsif ($item eq 'ownerdomfilter') {
                   17953:                 $filter->{'ownerdomfilter'} =
                   17954:                     &LONCAPA::clean_domain($filter->{$item});
                   17955:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17956:                                                        'ownerdomfilter',1);
                   17957:             } elsif ($item eq 'personfilter') {
                   17958:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17959:             } elsif ($item eq 'persondomfilter') {
                   17960:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17961:                                                         'persondomfilter',1);
                   17962:             } else {
                   17963:                 $filter->{$item} =~ s/\W//g;
                   17964:             }
                   17965:             if (!$filter->{$item}) {
                   17966:                 $filter->{$item} = '';
                   17967:             }
                   17968:         }
                   17969:         if ($item eq 'domainfilter') {
                   17970:             my $allow_blank = 1;
                   17971:             if ($formname eq 'portform') {
                   17972:                 $allow_blank=0;
                   17973:             } elsif ($formname eq 'studentform') {
                   17974:                 $allow_blank=0;
                   17975:             }
                   17976:             if ($fixeddom) {
                   17977:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17978:                                     ' value="'.$codedom.'" />'.
                   17979:                                     &Apache::lonnet::domain($codedom,'description');
                   17980:             } else {
                   17981:                 $domainselectform = &select_dom_form($filter->{$item},
                   17982:                                                      'domainfilter',
                   17983:                                                       $allow_blank,'',$onchange);
                   17984:             }
                   17985:         } else {
                   17986:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17987:         }
                   17988:     }
                   17989: 
                   17990:     # last course activity filter and selection
                   17991:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17992: 
                   17993:     # course created filter and selection
                   17994:     if (exists($filter->{'createdfilter'})) {
                   17995:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17996:     }
                   17997: 
1.1239    raeburn  17998:     my $prefix = $crstype;
                   17999:     if ($crstype eq 'Placement') {
                   18000:         $prefix = 'Placement Test'
                   18001:     }
1.1181    raeburn  18002:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18003:                 'cac' => "$prefix Activity",
                   18004:                 'ccr' => "$prefix Created",
                   18005:                 'cde' => "$prefix Title",
                   18006:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18007:                 'ins' => 'Institutional Code',
                   18008:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18009:                 'cow' => "$prefix Owner/Co-owner",
                   18010:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18011:                 'cog' => 'Type',
                   18012:              );
                   18013: 
                   18014:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18015:         my $typeval = 'Course';
                   18016:         if ($crstype eq 'Community') {
                   18017:             $typeval = 'Community';
1.1239    raeburn  18018:         } elsif ($crstype eq 'Placement') {
                   18019:             $typeval = 'Placement';
1.1181    raeburn  18020:         }
                   18021:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18022:     } else {
                   18023:         $typeselectform =  '<select name="type" size="1"';
                   18024:         if ($onchange) {
                   18025:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18026:         }
                   18027:         $typeselectform .= '>'."\n";
1.1237    raeburn  18028:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18029:             my $shown;
                   18030:             if ($posstype eq 'Placement') {
                   18031:                 $shown = &mt('Placement Test');
                   18032:             } else {
                   18033:                 $shown = &mt($posstype);
                   18034:             }
1.1181    raeburn  18035:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18036:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18037:         }
                   18038:         $typeselectform.="</select>";
                   18039:     }
                   18040: 
                   18041:     my ($cloneableonlyform,$cloneabletitle);
                   18042:     if (exists($filter->{'cloneableonly'})) {
                   18043:         my $cloneableon = '';
                   18044:         my $cloneableoff = ' checked="checked"';
                   18045:         if ($filter->{'cloneableonly'}) {
                   18046:             $cloneableon = $cloneableoff;
                   18047:             $cloneableoff = '';
                   18048:         }
                   18049:         $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>';
                   18050:         if ($formname eq 'ccrs') {
1.1187    bisitz   18051:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18052:         } else {
                   18053:             $cloneabletitle = &mt('Cloneable by you');
                   18054:         }
                   18055:     }
                   18056:     my $officialjs;
                   18057:     if ($crstype eq 'Course') {
                   18058:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18059: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18060: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18061:             if ($codedom) { 
1.1181    raeburn  18062:                 $officialjs = 1;
                   18063:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18064:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18065:                                                                   $officialjs,$codetitlesref);
                   18066:                 if ($jscript) {
1.1182    raeburn  18067:                     $jscript = '<script type="text/javascript">'."\n".
                   18068:                                '// <![CDATA['."\n".
                   18069:                                $jscript."\n".
                   18070:                                '// ]]>'."\n".
                   18071:                                '</script>'."\n";
1.1181    raeburn  18072:                 }
                   18073:             }
                   18074:             if ($instcodeform eq '') {
                   18075:                 $instcodeform =
                   18076:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18077:                     $list->{'instcodefilter'}.'" />';
                   18078:                 $instcodetitle = $lt{'ins'};
                   18079:             } else {
                   18080:                 $instcodetitle = $lt{'inc'};
                   18081:             }
                   18082:             if ($fixeddom) {
                   18083:                 $instcodetitle .= '<br />('.$codedom.')';
                   18084:             }
                   18085:         }
                   18086:     }
                   18087:     my $output = qq|
                   18088: <form method="post" name="filterpicker" action="$action">
                   18089: <input type="hidden" name="form" value="$formname" />
                   18090: |;
                   18091:     if ($formname eq 'modifycourse') {
                   18092:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18093:                    '<input type="hidden" name="prevphase" value="'.
                   18094:                    $prevphase.'" />'."\n";
1.1198    musolffc 18095:     } elsif ($formname eq 'quotacheck') {
                   18096:         $output .= qq|
                   18097: <input type="hidden" name="sortby" value="" />
                   18098: <input type="hidden" name="sortorder" value="" />
                   18099: |;
                   18100:     } else {
1.1181    raeburn  18101:         my $name_input;
                   18102:         if ($cnameelement ne '') {
                   18103:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18104:                           $cnameelement.'" />';
                   18105:         }
                   18106:         $output .= qq|
1.1182    raeburn  18107: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18108: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18109: $name_input
                   18110: $roleelement
                   18111: $multelement
                   18112: $typeelement
                   18113: |;
                   18114:         if ($formname eq 'portform') {
                   18115:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18116:         }
                   18117:     }
                   18118:     if ($fixeddom) {
                   18119:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18120:     }
                   18121:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18122:     if ($sincefilterform) {
                   18123:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18124:                   .$sincefilterform
                   18125:                   .&Apache::lonhtmlcommon::row_closure();
                   18126:     }
                   18127:     if ($createdfilterform) {
                   18128:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18129:                   .$createdfilterform
                   18130:                   .&Apache::lonhtmlcommon::row_closure();
                   18131:     }
                   18132:     if ($domainselectform) {
                   18133:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18134:                   .$domainselectform
                   18135:                   .&Apache::lonhtmlcommon::row_closure();
                   18136:     }
                   18137:     if ($typeselectform) {
                   18138:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18139:             $output .= $typeselectform;
                   18140:         } else {
                   18141:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18142:                       .$typeselectform
                   18143:                       .&Apache::lonhtmlcommon::row_closure();
                   18144:         }
                   18145:     }
                   18146:     if ($instcodeform) {
                   18147:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18148:                   .$instcodeform
                   18149:                   .&Apache::lonhtmlcommon::row_closure();
                   18150:     }
                   18151:     if (exists($filter->{'ownerfilter'})) {
                   18152:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18153:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18154:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18155:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18156:                    $ownerdomselectform.'</td></tr></table>'.
                   18157:                    &Apache::lonhtmlcommon::row_closure();
                   18158:     }
                   18159:     if (exists($filter->{'personfilter'})) {
                   18160:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18161:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18162:                    '<input type="text" name="personfilter" size="20" value="'.
                   18163:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18164:                    $persondomselectform.'</td></tr></table>'.
                   18165:                    &Apache::lonhtmlcommon::row_closure();
                   18166:     }
                   18167:     if (exists($filter->{'coursefilter'})) {
                   18168:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18169:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18170:                   .$list->{'coursefilter'}.'" />'
                   18171:                   .&Apache::lonhtmlcommon::row_closure();
                   18172:     }
                   18173:     if ($cloneableonlyform) {
                   18174:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18175:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18176:     }
                   18177:     if (exists($filter->{'descriptfilter'})) {
                   18178:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18179:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18180:                   .$list->{'descriptfilter'}.'" />'
                   18181:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18182:     }
                   18183:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18184:                '<input type="hidden" name="updater" value="" />'."\n".
                   18185:                '<input type="submit" name="gosearch" value="'.
                   18186:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18187:     return $jscript.$clonewarning.$output;
                   18188: }
                   18189: 
                   18190: =pod 
                   18191: 
                   18192: =item * &timebased_select_form()
                   18193: 
1.1182    raeburn  18194: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18195: filter e.g., Course Activity, Course Created, when searching for courses
                   18196: or communities
                   18197: 
                   18198: Inputs:
                   18199: 
                   18200: item - name of form element (sincefilter or createdfilter)
                   18201: 
                   18202: filter - anonymous hash of criteria and their values
                   18203: 
                   18204: Returns: HTML for a select box contained a blank, then six time selections,
                   18205:          with value set in incoming form variables currently selected. 
                   18206: 
                   18207: Side Effects: None
                   18208: 
                   18209: =cut
                   18210: 
                   18211: sub timebased_select_form {
                   18212:     my ($item,$filter) = @_;
                   18213:     if (ref($filter) eq 'HASH') {
                   18214:         $filter->{$item} =~ s/[^\d-]//g;
                   18215:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18216:         return &select_form(
                   18217:                             $filter->{$item},
                   18218:                             $item,
                   18219:                             {      '-1' => '',
                   18220:                                 '86400' => &mt('today'),
                   18221:                                '604800' => &mt('last week'),
                   18222:                               '2592000' => &mt('last month'),
                   18223:                               '7776000' => &mt('last three months'),
                   18224:                              '15552000' => &mt('last six months'),
                   18225:                              '31104000' => &mt('last year'),
                   18226:                     'select_form_order' =>
                   18227:                            ['-1','86400','604800','2592000','7776000',
                   18228:                             '15552000','31104000']});
                   18229:     }
                   18230: }
                   18231: 
                   18232: =pod
                   18233: 
                   18234: =item * &js_changer()
                   18235: 
                   18236: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18237: when course type or domain is changed, and also to hide 'Searching ...' on
                   18238: page load completion for page showing search result.
1.1181    raeburn  18239: 
                   18240: Inputs: None
                   18241: 
1.1183    raeburn  18242: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18243: 
                   18244: Side Effects: None
                   18245: 
                   18246: =cut
                   18247: 
                   18248: sub js_changer {
                   18249:     return <<ENDJS;
                   18250: <script type="text/javascript">
                   18251: // <![CDATA[
                   18252: function updateFilters(caller) {
                   18253:     if (typeof(caller) != "undefined") {
                   18254:         document.filterpicker.updater.value = caller.name;
                   18255:     }
                   18256:     document.filterpicker.submit();
                   18257: }
1.1183    raeburn  18258: 
                   18259: function hideSearching() {
                   18260:     if (document.getElementById('searching')) {
                   18261:         document.getElementById('searching').style.display = 'none';
                   18262:     }
                   18263:     return;
                   18264: }
                   18265: 
1.1181    raeburn  18266: // ]]>
                   18267: </script>
                   18268: 
                   18269: ENDJS
                   18270: }
                   18271: 
                   18272: =pod
                   18273: 
1.1182    raeburn  18274: =item * &search_courses()
                   18275: 
                   18276: Process selected filters form course search form and pass to lonnet::courseiddump
                   18277: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18278: 
                   18279: Inputs:
                   18280: 
                   18281: dom - domain being searched 
                   18282: 
                   18283: type - course type ('Course' or 'Community' or '.' if any).
                   18284: 
                   18285: filter - anonymous hash of criteria and their values
                   18286: 
                   18287: numtitles - for institutional codes - number of categories
                   18288: 
                   18289: cloneruname - optional username of new course owner
                   18290: 
                   18291: clonerudom - optional domain of new course owner
                   18292: 
1.1221    raeburn  18293: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18294:             (used when DC is using course creation form)
                   18295: 
                   18296: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18297: 
1.1221    raeburn  18298: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18299:            (and so can clone automatically)
                   18300: 
                   18301: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18302: 
                   18303: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18304:               courses to clone 
1.1182    raeburn  18305: 
                   18306: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18307: 
                   18308: 
                   18309: Side Effects: None
                   18310: 
                   18311: =cut
                   18312: 
                   18313: 
                   18314: sub search_courses {
1.1221    raeburn  18315:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18316:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18317:     my (%courses,%showcourses,$cloner);
                   18318:     if (($filter->{'ownerfilter'} ne '') ||
                   18319:         ($filter->{'ownerdomfilter'} ne '')) {
                   18320:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18321:                                        $filter->{'ownerdomfilter'};
                   18322:     }
                   18323:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18324:         if (!$filter->{$item}) {
                   18325:             $filter->{$item}='.';
                   18326:         }
                   18327:     }
                   18328:     my $now = time;
                   18329:     my $timefilter =
                   18330:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18331:     my ($createdbefore,$createdafter);
                   18332:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18333:         $createdbefore = $now;
                   18334:         $createdafter = $now-$filter->{'createdfilter'};
                   18335:     }
                   18336:     my ($instcodefilter,$regexpok);
                   18337:     if ($numtitles) {
                   18338:         if ($env{'form.official'} eq 'on') {
                   18339:             $instcodefilter =
                   18340:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18341:             $regexpok = 1;
                   18342:         } elsif ($env{'form.official'} eq 'off') {
                   18343:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18344:             unless ($instcodefilter eq '') {
                   18345:                 $regexpok = -1;
                   18346:             }
                   18347:         }
                   18348:     } else {
                   18349:         $instcodefilter = $filter->{'instcodefilter'};
                   18350:     }
                   18351:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18352:     if ($type eq '') { $type = '.'; }
                   18353: 
                   18354:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18355:         $cloner = $cloneruname.':'.$clonerudom;
                   18356:     }
                   18357:     %courses = &Apache::lonnet::courseiddump($dom,
                   18358:                                              $filter->{'descriptfilter'},
                   18359:                                              $timefilter,
                   18360:                                              $instcodefilter,
                   18361:                                              $filter->{'combownerfilter'},
                   18362:                                              $filter->{'coursefilter'},
                   18363:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18364:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18365:                                              $filter->{'cloneableonly'},
                   18366:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18367:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18368:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18369:         my $ccrole;
                   18370:         if ($type eq 'Community') {
                   18371:             $ccrole = 'co';
                   18372:         } else {
                   18373:             $ccrole = 'cc';
                   18374:         }
                   18375:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18376:                                                      $filter->{'persondomfilter'},
                   18377:                                                      'userroles',undef,
                   18378:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18379:                                                      $dom);
                   18380:         foreach my $role (keys(%rolehash)) {
                   18381:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18382:             my $cid = $cdom.'_'.$cnum;
                   18383:             if (exists($courses{$cid})) {
                   18384:                 if (ref($courses{$cid}) eq 'HASH') {
                   18385:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18386:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18387:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18388:                         }
                   18389:                     } else {
                   18390:                         $courses{$cid}{roles} = [$courserole];
                   18391:                     }
                   18392:                     $showcourses{$cid} = $courses{$cid};
                   18393:                 }
                   18394:             }
                   18395:         }
                   18396:         %courses = %showcourses;
                   18397:     }
                   18398:     return %courses;
                   18399: }
                   18400: 
                   18401: =pod
                   18402: 
1.1181    raeburn  18403: =back
                   18404: 
1.1207    raeburn  18405: =head1 Routines for version requirements for current course.
                   18406: 
                   18407: =over 4
                   18408: 
                   18409: =item * &check_release_required()
                   18410: 
                   18411: Compares required LON-CAPA version with version on server, and
                   18412: if required version is newer looks for a server with the required version.
                   18413: 
                   18414: Looks first at servers in user's owen domain; if none suitable, looks at
                   18415: servers in course's domain are permitted to host sessions for user's domain.
                   18416: 
                   18417: Inputs:
                   18418: 
                   18419: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18420: 
                   18421: $courseid - Course ID of current course
                   18422: 
                   18423: $rolecode - User's current role in course (for switchserver query string).
                   18424: 
                   18425: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18426: 
                   18427: 
                   18428: Returns:
                   18429: 
                   18430: $switchserver - query string tp append to /adm/switchserver call (if 
                   18431:                 current server's LON-CAPA version is too old. 
                   18432: 
                   18433: $warning - Message is displayed if no suitable server could be found.
                   18434: 
                   18435: =cut
                   18436: 
                   18437: sub check_release_required {
                   18438:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18439:     my ($switchserver,$warning);
                   18440:     if ($required ne '') {
                   18441:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18442:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18443:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18444:             my $otherserver;
                   18445:             if (($major eq '' && $minor eq '') ||
                   18446:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18447:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18448:                 my $switchlcrev =
                   18449:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18450:                                                            $userdomserver);
                   18451:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18452:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18453:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18454:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18455:                     if ($cdom ne $env{'user.domain'}) {
                   18456:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18457:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18458:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18459:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18460:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18461:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18462:                         my $canhost =
                   18463:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18464:                                                               $coursedomserver,
                   18465:                                                               $remoterev,
                   18466:                                                               $udomdefaults{'remotesessions'},
                   18467:                                                               $defdomdefaults{'hostedsessions'});
                   18468: 
                   18469:                         if ($canhost) {
                   18470:                             $otherserver = $coursedomserver;
                   18471:                         } else {
                   18472:                             $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.");
                   18473:                         }
                   18474:                     } else {
                   18475:                         $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).");
                   18476:                     }
                   18477:                 } else {
                   18478:                     $otherserver = $userdomserver;
                   18479:                 }
                   18480:             }
                   18481:             if ($otherserver ne '') {
                   18482:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18483:             }
                   18484:         }
                   18485:     }
                   18486:     return ($switchserver,$warning);
                   18487: }
                   18488: 
                   18489: =pod
                   18490: 
                   18491: =item * &check_release_result()
                   18492: 
                   18493: Inputs:
                   18494: 
                   18495: $switchwarning - Warning message if no suitable server found to host session.
                   18496: 
                   18497: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18498:                 and current role.
                   18499: 
                   18500: Returns: HTML to display with information about requirement to switch server.
                   18501:          Either displaying warning with link to Roles/Courses screen or
                   18502:          display link to switchserver.
                   18503: 
1.1181    raeburn  18504: =cut
                   18505: 
1.1207    raeburn  18506: sub check_release_result {
                   18507:     my ($switchwarning,$switchserver) = @_;
                   18508:     my $output = &start_page('Selected course unavailable on this server').
                   18509:                  '<p class="LC_warning">';
                   18510:     if ($switchwarning) {
                   18511:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18512:         if (&show_course()) {
                   18513:             $output .= &mt('Display courses');
                   18514:         } else {
                   18515:             $output .= &mt('Display roles');
                   18516:         }
                   18517:         $output .= '</a>';
                   18518:     } elsif ($switchserver) {
                   18519:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18520:                    '<br />'.
                   18521:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18522:                    &mt('Switch Server').
                   18523:                    '</a>';
                   18524:     }
                   18525:     $output .= '</p>'.&end_page();
                   18526:     return $output;
                   18527: }
                   18528: 
                   18529: =pod
                   18530: 
                   18531: =item * &needs_coursereinit()
                   18532: 
                   18533: Determine if course contents stored for user's session needs to be
                   18534: refreshed, because content has changed since "Big Hash" last tied.
                   18535: 
                   18536: Check for change is made if time last checked is more than 10 minutes ago
                   18537: (by default).
                   18538: 
                   18539: Inputs:
                   18540: 
                   18541: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18542: 
                   18543: $interval (optional) - Time which may elapse (in s) between last check for content
                   18544:                        change in current course. (default: 600 s).  
                   18545: 
                   18546: Returns: an array; first element is:
                   18547: 
                   18548: =over 4
                   18549: 
                   18550: 'switch' - if content updates mean user's session
                   18551:            needs to be switched to a server running a newer LON-CAPA version
                   18552:  
                   18553: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18554:            on current server hosting user's session                
                   18555: 
                   18556: ''       - if no action required.
                   18557: 
                   18558: =back
                   18559: 
                   18560: If first item element is 'switch':
                   18561: 
                   18562: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18563: 
                   18564: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18565:                               and current role. 
                   18566: 
                   18567: otherwise: no other elements returned.
                   18568: 
                   18569: =back
                   18570: 
                   18571: =cut
                   18572: 
                   18573: sub needs_coursereinit {
                   18574:     my ($loncaparev,$interval) = @_;
                   18575:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18576:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18577:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18578:     my $now = time;
                   18579:     if ($interval eq '') {
                   18580:         $interval = 600;
                   18581:     }
                   18582:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18583:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18584:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18585:         if ($blocked) {
                   18586:             return ();
                   18587:         }
1.1391    raeburn  18588:         my $update;
                   18589:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18590:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18591:         if ($lastmainchange > $env{'request.course.tied'}) {
                   18592:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18593:             if ($needswitch) {
                   18594:                 return ('switch',$switchwarning,$switchserver);
                   18595:             }
                   18596:             $update = 'main';
                   18597:         }
                   18598:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18599:             if ($update) {
                   18600:                 $update = 'both';
                   18601:             } else {
                   18602:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18603:                 if ($needswitch) {
                   18604:                     return ('switch',$switchwarning,$switchserver);
                   18605:                 } else {
                   18606:                     $update = 'supp';
1.1207    raeburn  18607:                 }
                   18608:             }
1.1391    raeburn  18609:             return ($update);
                   18610:         }
                   18611:     }
                   18612:     return ();
                   18613: }
                   18614: 
                   18615: sub switch_for_update {
                   18616:     my ($loncaparev,$cdom,$cnum) = @_;
                   18617:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18618:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18619:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18620:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18621:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18622:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18623:             my ($switchserver,$switchwarning) =
                   18624:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18625:                                         $curr_reqd_hash{'internal.releaserequired'});
                   18626:             if ($switchwarning ne '' || $switchserver ne '') {
                   18627:                 return ('switch',$switchwarning,$switchserver);
                   18628:             }
1.1207    raeburn  18629:         }
                   18630:     }
                   18631:     return ();
                   18632: }
1.1181    raeburn  18633: 
1.1083    raeburn  18634: sub update_content_constraints {
1.1395    raeburn  18635:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  18636:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18637:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18638:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18639:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18640:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18641:         if ($item eq 'resourcetag') {
                   18642:             if ($name eq 'responsetype') {
                   18643:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18644:             }
1.1307    raeburn  18645:         } elsif ($item eq 'course') {
                   18646:             if ($name eq 'courserestype') {
                   18647:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18648:             }
1.1083    raeburn  18649:         }
                   18650:     }
                   18651:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18652:     if (defined($navmap)) {
1.1307    raeburn  18653:         my (%allresponses,%allcrsrestypes);
                   18654:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18655:             if ($res->is_tool()) {
                   18656:                 if ($allcrsrestypes{'exttool'}) {
                   18657:                     $allcrsrestypes{'exttool'} ++;
                   18658:                 } else {
                   18659:                     $allcrsrestypes{'exttool'} = 1;
                   18660:                 }
                   18661:                 next;
                   18662:             }
1.1083    raeburn  18663:             my %responses = $res->responseTypes();
                   18664:             foreach my $key (keys(%responses)) {
                   18665:                 next unless(exists($checkresponsetypes{$key}));
                   18666:                 $allresponses{$key} += $responses{$key};
                   18667:             }
                   18668:         }
                   18669:         foreach my $key (keys(%allresponses)) {
                   18670:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18671:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18672:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18673:             }
                   18674:         }
1.1307    raeburn  18675:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18676:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18677:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18678:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18679:             }
                   18680:         }
1.1083    raeburn  18681:         undef($navmap);
                   18682:     }
1.1391    raeburn  18683:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  18684:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18685:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18686:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18687:         }
                   18688:     }
1.1083    raeburn  18689:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18690:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18691:     }
                   18692:     return;
                   18693: }
                   18694: 
1.1110    raeburn  18695: sub allmaps_incourse {
                   18696:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18697:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18698:         $cid = $env{'request.course.id'};
                   18699:         $cdom = $env{'course.'.$cid.'.domain'};
                   18700:         $cnum = $env{'course.'.$cid.'.num'};
                   18701:         $chome = $env{'course.'.$cid.'.home'};
                   18702:     }
                   18703:     my %allmaps = ();
                   18704:     my $lastchange =
                   18705:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18706:     if ($lastchange > $env{'request.course.tied'}) {
                   18707:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18708:         unless ($ferr) {
1.1395    raeburn  18709:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  18710:         }
                   18711:     }
                   18712:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18713:     if (defined($navmap)) {
                   18714:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18715:             $allmaps{$res->src()} = 1;
                   18716:         }
                   18717:     }
                   18718:     return \%allmaps;
                   18719: }
                   18720: 
1.1083    raeburn  18721: sub parse_supplemental_title {
                   18722:     my ($title) = @_;
                   18723: 
                   18724:     my ($foldertitle,$renametitle);
                   18725:     if ($title =~ /&amp;&amp;&amp;/) {
                   18726:         $title = &HTML::Entites::decode($title);
                   18727:     }
                   18728:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18729:         $renametitle=$4;
                   18730:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18731:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18732:         my $name =  &plainname($uname,$udom);
                   18733:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18734:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  18735:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  18736:         if ($foldertitle ne '') {
1.1401    raeburn  18737:             $title .= ': <br />'.$foldertitle;
                   18738:         }
1.1083    raeburn  18739:     }
                   18740:     if (wantarray) {
                   18741:         return ($title,$foldertitle,$renametitle);
                   18742:     }
                   18743:     return $title;
                   18744: }
                   18745: 
1.1395    raeburn  18746: sub get_supplemental {
                   18747:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18748:     my $hashid=$cnum.':'.$cdom;
                   18749:     my ($supplemental,$cached,$set_httprefs);
                   18750:     unless ($ignorecache) {
                   18751:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18752:     }
                   18753:     unless (defined($cached)) {
                   18754:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18755:         unless ($chome eq 'no_host') {
                   18756:             my @order = @LONCAPA::map::order;
                   18757:             my @resources = @LONCAPA::map::resources;
                   18758:             my @resparms = @LONCAPA::map::resparms;
                   18759:             my @zombies = @LONCAPA::map::zombies;
                   18760:             my ($errors,%ids,%hidden);
                   18761:             $errors =
                   18762:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   18763:                                       $errors,$possdel,\%ids,\%hidden);
                   18764:             @LONCAPA::map::order = @order;
                   18765:             @LONCAPA::map::resources = @resources;
                   18766:             @LONCAPA::map::resparms = @resparms;
                   18767:             @LONCAPA::map::zombies = @zombies;
                   18768:             $set_httprefs = 1;
                   18769:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18770:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18771:             }
                   18772:             $supplemental = {
                   18773:                                ids => \%ids,
                   18774:                                hidden => \%hidden,
                   18775:                             };
                   18776:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   18777:         }
                   18778:     }
                   18779:     return ($supplemental,$set_httprefs);
                   18780: }
                   18781: 
1.1143    raeburn  18782: sub recurse_supplemental {
1.1391    raeburn  18783:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18784:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18785:         my $mapnum;
                   18786:         if ($suppmap eq 'supplemental.sequence') {
                   18787:             $mapnum = 0;
                   18788:         } else {
                   18789:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18790:         }
1.1143    raeburn  18791:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18792:         if ($fatal) {
                   18793:             $errors ++;
                   18794:         } else {
1.1389    raeburn  18795:             my @order = @LONCAPA::map::order;
                   18796:             if (@order > 0) {
                   18797:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  18798:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  18799:                 foreach my $idx (@order) {
                   18800:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  18801:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  18802:                         my $id = $mapnum.':'.$idx;
                   18803:                         push(@{$suppids->{$src}},$id);
                   18804:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18805:                             $hiddensupp->{$id} = 1;
                   18806:                         }
1.1146    raeburn  18807:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  18808:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18809:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  18810:                         } else {
1.1391    raeburn  18811:                             my $allowed;
                   18812:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18813:                                 $allowed = 1;
                   18814:                             } elsif ($possdel) {
                   18815:                                 foreach my $item (@{$suppids->{$src}}) {
                   18816:                                     next if ($item eq $id);
                   18817:                                     unless ($hiddensupp->{$item}) {
                   18818:                                        $allowed = 1;
                   18819:                                        last;
                   18820:                                     }
                   18821:                                 }
                   18822:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18823:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18824:                                 }
                   18825:                             }
                   18826:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18827:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  18828:                             }
1.1143    raeburn  18829:                         }
                   18830:                     }
                   18831:                 }
                   18832:             }
                   18833:         }
                   18834:     }
1.1391    raeburn  18835:     return $errors;
                   18836: }
                   18837: 
                   18838: sub set_supp_httprefs {
                   18839:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18840:     if (ref($supplemental) eq 'HASH') {
                   18841:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18842:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18843:                 next if ($src =~ /\.sequence$/);
                   18844:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18845:                     my $allowed;
                   18846:                     if ($env{'request.role.adv'}) {
                   18847:                         $allowed = 1;
                   18848:                     } else {
                   18849:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18850:                             unless ($supplemental->{'hidden'}->{$id}) {
                   18851:                                 $allowed = 1;
                   18852:                                 last;
                   18853:                             }
                   18854:                         }
                   18855:                     }
                   18856:                     if (exists($env{'httpref.'.$src})) {
                   18857:                         if ($possdel) {
                   18858:                             unless ($allowed) {
                   18859:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18860:                             }
                   18861:                         }
                   18862:                     } elsif ($allowed) {
                   18863:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18864:                     }
                   18865:                 }
                   18866:             }
                   18867:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18868:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18869:             }
                   18870:         }
                   18871:     }
                   18872: }
                   18873: 
                   18874: sub get_supp_parameter {
                   18875:     my ($resparm,$name)=@_;
                   18876:     return if ($resparm eq '');
                   18877:     my $value=undef;
                   18878:     my $ptype=undef;
                   18879:     foreach (split('&&&',$resparm)) {
                   18880:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18881:         if ($thisname eq $name) {
                   18882:             $value=$thisvalue;
                   18883:             $ptype=$thistype;
                   18884:         }
                   18885:     }
                   18886:     return $value;
1.1143    raeburn  18887: }
                   18888: 
1.1101    raeburn  18889: sub symb_to_docspath {
1.1267    raeburn  18890:     my ($symb,$navmapref) = @_;
                   18891:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18892:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18893:     if ($resurl=~/\.(sequence|page)$/) {
                   18894:         $mapurl=$resurl;
                   18895:     } elsif ($resurl eq 'adm/navmaps') {
                   18896:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18897:     }
                   18898:     my $mapresobj;
1.1267    raeburn  18899:     unless (ref($$navmapref)) {
                   18900:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18901:     }
                   18902:     if (ref($$navmapref)) {
                   18903:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18904:     }
                   18905:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18906:     my $type=$2;
                   18907:     my $path;
                   18908:     if (ref($mapresobj)) {
                   18909:         my $pcslist = $mapresobj->map_hierarchy();
                   18910:         if ($pcslist ne '') {
                   18911:             foreach my $pc (split(/,/,$pcslist)) {
                   18912:                 next if ($pc <= 1);
1.1267    raeburn  18913:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18914:                 if (ref($res)) {
                   18915:                     my $thisurl = $res->src();
                   18916:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18917:                     my $thistitle = $res->title();
                   18918:                     $path .= '&'.
                   18919:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18920:                              &escape($thistitle).
1.1101    raeburn  18921:                              ':'.$res->randompick().
                   18922:                              ':'.$res->randomout().
                   18923:                              ':'.$res->encrypted().
                   18924:                              ':'.$res->randomorder().
                   18925:                              ':'.$res->is_page();
                   18926:                 }
                   18927:             }
                   18928:         }
                   18929:         $path =~ s/^\&//;
                   18930:         my $maptitle = $mapresobj->title();
                   18931:         if ($mapurl eq 'default') {
1.1129    raeburn  18932:             $maptitle = 'Main Content';
1.1101    raeburn  18933:         }
                   18934:         $path .= (($path ne '')? '&' : '').
                   18935:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18936:                  &escape($maptitle).
1.1101    raeburn  18937:                  ':'.$mapresobj->randompick().
                   18938:                  ':'.$mapresobj->randomout().
                   18939:                  ':'.$mapresobj->encrypted().
                   18940:                  ':'.$mapresobj->randomorder().
                   18941:                  ':'.$mapresobj->is_page();
                   18942:     } else {
                   18943:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18944:         my $ispage = (($type eq 'page')? 1 : '');
                   18945:         if ($mapurl eq 'default') {
1.1129    raeburn  18946:             $maptitle = 'Main Content';
1.1101    raeburn  18947:         }
                   18948:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18949:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18950:     }
                   18951:     unless ($mapurl eq 'default') {
                   18952:         $path = 'default&'.
1.1146    raeburn  18953:                 &escape('Main Content').
1.1101    raeburn  18954:                 ':::::&'.$path;
                   18955:     }
                   18956:     return $path;
                   18957: }
                   18958: 
1.1393    raeburn  18959: sub validate_folderpath {
                   18960:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18961:     if ($env{'form.folderpath'} ne '') {
                   18962:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  18963:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  18964:         for (my $i=0; $i<@items; $i++) {
                   18965:             my $odd = $i%2;
                   18966:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18967:                 $badpath = 1;
1.1394    raeburn  18968:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  18969:                 my $idx = $i-1;
1.1394    raeburn  18970:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18971:                     my $esc_name = $1;
                   18972:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18973:                         $supppath .= '&'.$esc_name;
                   18974:                         $changed = 1;
                   18975:                     } else {
                   18976:                         $supppath .= '&'.$items[$i];
                   18977:                     }
                   18978:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18979:                     $changed = 1;
1.1393    raeburn  18980:                     my $is_hidden;
                   18981:                     unless ($got_supp) {
1.1395    raeburn  18982:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  18983:                         if (ref($supplemental) eq 'HASH') {
                   18984:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18985:                                 %supphidden = %{$supplemental->{'hidden'}};
                   18986:                             }
                   18987:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18988:                                 %suppids = %{$supplemental->{'ids'}};
                   18989:                             }
                   18990:                         }
                   18991:                         $got_supp = 1;
                   18992:                     }
                   18993:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18994:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18995:                         if ($supphidden{$mapid}) {
                   18996:                             $is_hidden = 1;
                   18997:                         }
                   18998:                     }
1.1394    raeburn  18999:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19000:                 } else {
                   19001:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19002:                 }
                   19003:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19004:                 $badpath = 1;
1.1394    raeburn  19005:             } elsif ($supplementalflag) {
1.1393    raeburn  19006:                 $supppath .= '&'.$items[$i];
                   19007:             }
                   19008:             last if ($badpath);
                   19009:         }
                   19010:         if ($badpath) {
                   19011:             delete($env{'form.folderpath'});
1.1394    raeburn  19012:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19013:             $supppath =~ s/^\&//;
                   19014:             $env{'form.folderpath'} = $supppath;
                   19015:         }
                   19016:     }
                   19017:     return;
                   19018: }
                   19019: 
1.1094    raeburn  19020: sub captcha_display {
1.1327    raeburn  19021:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19022:     my ($output,$error);
1.1234    raeburn  19023:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19024:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19025:     if ($captcha eq 'original') {
1.1094    raeburn  19026:         $output = &create_captcha();
                   19027:         unless ($output) {
1.1172    raeburn  19028:             $error = 'captcha';
1.1094    raeburn  19029:         }
                   19030:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19031:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19032:         unless ($output) {
1.1172    raeburn  19033:             $error = 'recaptcha';
1.1094    raeburn  19034:         }
                   19035:     }
1.1234    raeburn  19036:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19037: }
                   19038: 
                   19039: sub captcha_response {
1.1327    raeburn  19040:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19041:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19042:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19043:     if ($captcha eq 'original') {
1.1094    raeburn  19044:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19045:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19046:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19047:     } else {
                   19048:         $captcha_chk = 1;
                   19049:     }
                   19050:     return ($captcha_chk,$captcha_error);
                   19051: }
                   19052: 
                   19053: sub get_captcha_config {
1.1327    raeburn  19054:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19055:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19056:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19057:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19058:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19059:     if ($context eq 'usercreation') {
                   19060:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19061:         if (ref($domconfig{$context}) eq 'HASH') {
                   19062:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19063:             if (ref($hashtocheck) eq 'HASH') {
                   19064:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19065:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19066:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19067:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19068:                     }
                   19069:                     if ($privkey && $pubkey) {
                   19070:                         $captcha = 'recaptcha';
1.1234    raeburn  19071:                         $version = $hashtocheck->{'recaptchaversion'};
                   19072:                         if ($version ne '2') {
                   19073:                             $version = 1;
                   19074:                         }
1.1095    raeburn  19075:                     } else {
                   19076:                         $captcha = 'original';
                   19077:                     }
                   19078:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19079:                     $captcha = 'original';
                   19080:                 }
1.1094    raeburn  19081:             }
1.1095    raeburn  19082:         } else {
                   19083:             $captcha = 'captcha';
                   19084:         }
                   19085:     } elsif ($context eq 'login') {
                   19086:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19087:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19088:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19089:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19090:             if ($privkey && $pubkey) {
                   19091:                 $captcha = 'recaptcha';
1.1234    raeburn  19092:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19093:                 if ($version ne '2') {
                   19094:                     $version = 1; 
                   19095:                 }
1.1095    raeburn  19096:             } else {
                   19097:                 $captcha = 'original';
1.1094    raeburn  19098:             }
1.1095    raeburn  19099:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19100:             $captcha = 'original';
1.1094    raeburn  19101:         }
1.1327    raeburn  19102:     } elsif ($context eq 'passwords') {
                   19103:         if ($dom_in_effect) {
                   19104:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19105:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19106:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19107:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19108:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19109:                 }
                   19110:                 if ($privkey && $pubkey) {
                   19111:                     $captcha = 'recaptcha';
                   19112:                     $version = $passwdconf{'recaptchaversion'};
                   19113:                     if ($version ne '2') {
                   19114:                         $version = 1;
                   19115:                     }
                   19116:                 } else {
                   19117:                     $captcha = 'original';
                   19118:                 }
                   19119:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19120:                 $captcha = 'original';
                   19121:             }
                   19122:         }
                   19123:     } 
1.1234    raeburn  19124:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19125: }
                   19126: 
                   19127: sub create_captcha {
                   19128:     my %captcha_params = &captcha_settings();
                   19129:     my ($output,$maxtries,$tries) = ('',10,0);
                   19130:     while ($tries < $maxtries) {
                   19131:         $tries ++;
                   19132:         my $captcha = Authen::Captcha->new (
                   19133:                                            output_folder => $captcha_params{'output_dir'},
                   19134:                                            data_folder   => $captcha_params{'db_dir'},
                   19135:                                           );
                   19136:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19137: 
                   19138:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19139:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19140:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19141:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19142:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19143:                       '</span><br />'.
1.1176    raeburn  19144:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19145:             last;
                   19146:         }
                   19147:     }
1.1323    raeburn  19148:     if ($output eq '') {
                   19149:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19150:     }
1.1094    raeburn  19151:     return $output;
                   19152: }
                   19153: 
                   19154: sub captcha_settings {
                   19155:     my %captcha_params = (
                   19156:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19157:                            www_output_dir => "/captchaspool",
                   19158:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19159:                            numchars       => '5',
                   19160:                          );
                   19161:     return %captcha_params;
                   19162: }
                   19163: 
                   19164: sub check_captcha {
                   19165:     my ($captcha_chk,$captcha_error);
                   19166:     my $code = $env{'form.code'};
                   19167:     my $md5sum = $env{'form.crypt'};
                   19168:     my %captcha_params = &captcha_settings();
                   19169:     my $captcha = Authen::Captcha->new(
                   19170:                       output_folder => $captcha_params{'output_dir'},
                   19171:                       data_folder   => $captcha_params{'db_dir'},
                   19172:                   );
1.1109    raeburn  19173:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19174:     my %captcha_hash = (
                   19175:                         0       => 'Code not checked (file error)',
                   19176:                        -1      => 'Failed: code expired',
                   19177:                        -2      => 'Failed: invalid code (not in database)',
                   19178:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19179:     );
                   19180:     if ($captcha_chk != 1) {
                   19181:         $captcha_error = $captcha_hash{$captcha_chk}
                   19182:     }
                   19183:     return ($captcha_chk,$captcha_error);
                   19184: }
                   19185: 
                   19186: sub create_recaptcha {
1.1234    raeburn  19187:     my ($pubkey,$version) = @_;
                   19188:     if ($version >= 2) {
1.1367    raeburn  19189:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19190:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19191:     } else {
                   19192:         my $use_ssl;
                   19193:         if ($ENV{'SERVER_PORT'} == 443) {
                   19194:             $use_ssl = 1;
                   19195:         }
                   19196:         my $captcha = Captcha::reCAPTCHA->new;
                   19197:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19198:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19199:                &mt('If the text is hard to read, [_1] will replace them.',
                   19200:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19201:                '<br /><br />';
                   19202:     }
1.1094    raeburn  19203: }
                   19204: 
                   19205: sub check_recaptcha {
1.1234    raeburn  19206:     my ($privkey,$version) = @_;
1.1094    raeburn  19207:     my $captcha_chk;
1.1350    raeburn  19208:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19209:     if ($version >= 2) {
                   19210:         my %info = (
                   19211:                      secret   => $privkey, 
                   19212:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19213:                      remoteip => $ip,
1.1234    raeburn  19214:                    );
1.1280    raeburn  19215:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19216:         $request->content(join('&',map {
                   19217:                          my $name = escape($_);
                   19218:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19219:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19220:                          : &escape($info{$_}) );
                   19221:         } keys(%info)));
                   19222:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19223:         if ($response->is_success)  {
                   19224:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19225:             if (ref($data) eq 'HASH') {
                   19226:                 if ($data->{'success'}) {
                   19227:                     $captcha_chk = 1;
                   19228:                 }
                   19229:             }
                   19230:         }
                   19231:     } else {
                   19232:         my $captcha = Captcha::reCAPTCHA->new;
                   19233:         my $captcha_result =
                   19234:             $captcha->check_answer(
                   19235:                                     $privkey,
1.1350    raeburn  19236:                                     $ip,
1.1234    raeburn  19237:                                     $env{'form.recaptcha_challenge_field'},
                   19238:                                     $env{'form.recaptcha_response_field'},
                   19239:                                   );
                   19240:         if ($captcha_result->{is_valid}) {
                   19241:             $captcha_chk = 1;
                   19242:         }
1.1094    raeburn  19243:     }
                   19244:     return $captcha_chk;
                   19245: }
                   19246: 
1.1174    raeburn  19247: sub emailusername_info {
1.1244    raeburn  19248:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19249:     my %titles = &Apache::lonlocal::texthash (
                   19250:                      lastname      => 'Last Name',
                   19251:                      firstname     => 'First Name',
                   19252:                      institution   => 'School/college/university',
                   19253:                      location      => "School's city, state/province, country",
                   19254:                      web           => "School's web address",
                   19255:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19256:                      id            => 'Student/Employee ID',
1.1174    raeburn  19257:                  );
                   19258:     return (\@fields,\%titles);
                   19259: }
                   19260: 
1.1161    raeburn  19261: sub cleanup_html {
                   19262:     my ($incoming) = @_;
                   19263:     my $outgoing;
                   19264:     if ($incoming ne '') {
                   19265:         $outgoing = $incoming;
                   19266:         $outgoing =~ s/;/&#059;/g;
                   19267:         $outgoing =~ s/\#/&#035;/g;
                   19268:         $outgoing =~ s/\&/&#038;/g;
                   19269:         $outgoing =~ s/</&#060;/g;
                   19270:         $outgoing =~ s/>/&#062;/g;
                   19271:         $outgoing =~ s/\(/&#040/g;
                   19272:         $outgoing =~ s/\)/&#041;/g;
                   19273:         $outgoing =~ s/"/&#034;/g;
                   19274:         $outgoing =~ s/'/&#039;/g;
                   19275:         $outgoing =~ s/\$/&#036;/g;
                   19276:         $outgoing =~ s{/}{&#047;}g;
                   19277:         $outgoing =~ s/=/&#061;/g;
                   19278:         $outgoing =~ s/\\/&#092;/g
                   19279:     }
                   19280:     return $outgoing;
                   19281: }
                   19282: 
1.1190    musolffc 19283: # Checks for critical messages and returns a redirect url if one exists.
                   19284: # $interval indicates how often to check for messages.
1.1282    raeburn  19285: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19286: sub critical_redirect {
1.1282    raeburn  19287:     my ($interval,$context) = @_;
1.1356    raeburn  19288:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19289:         return ();
                   19290:     }
1.1190    musolffc 19291:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19292:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19293:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19294:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19295:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19296:             if ($blocked) {
                   19297:                 my $checkrole = "cm./$cdom/$cnum";
                   19298:                 if ($env{'request.course.sec'} ne '') {
                   19299:                     $checkrole .= "/$env{'request.course.sec'}";
                   19300:                 }
                   19301:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19302:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19303:                     return;
                   19304:                 }
                   19305:             }
                   19306:         }
1.1190    musolffc 19307:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19308:                                         $env{'user.name'});
                   19309:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19310:         my $redirecturl;
1.1190    musolffc 19311:         if ($what[0]) {
1.1356    raeburn  19312: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19313: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19314: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19315:                 return (1, $url);
1.1190    musolffc 19316:             }
1.1191    raeburn  19317:         }
                   19318:     } 
                   19319:     return ();
1.1190    musolffc 19320: }
                   19321: 
1.1174    raeburn  19322: # Use:
                   19323: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19324: #
                   19325: ##################################################
                   19326: #          password associated functions         #
                   19327: ##################################################
                   19328: sub des_keys {
                   19329:     # Make a new key for DES encryption.
                   19330:     # Each key has two parts which are returned separately.
                   19331:     # Please note:  Each key must be passed through the &hex function
                   19332:     # before it is output to the web browser.  The hex versions cannot
                   19333:     # be used to decrypt.
                   19334:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19335:                 '8','9','a','b','c','d','e','f');
                   19336:     my $lkey='';
                   19337:     for (0..7) {
                   19338:         $lkey.=$hexstr[rand(15)];
                   19339:     }
                   19340:     my $ukey='';
                   19341:     for (0..7) {
                   19342:         $ukey.=$hexstr[rand(15)];
                   19343:     }
                   19344:     return ($lkey,$ukey);
                   19345: }
                   19346: 
                   19347: sub des_decrypt {
                   19348:     my ($key,$cyphertext) = @_;
                   19349:     my $keybin=pack("H16",$key);
                   19350:     my $cypher;
                   19351:     if ($Crypt::DES::VERSION>=2.03) {
                   19352:         $cypher=new Crypt::DES $keybin;
                   19353:     } else {
                   19354:         $cypher=new DES $keybin;
                   19355:     }
1.1233    raeburn  19356:     my $plaintext='';
                   19357:     my $cypherlength = length($cyphertext);
                   19358:     my $numchunks = int($cypherlength/32);
                   19359:     for (my $j=0; $j<$numchunks; $j++) {
                   19360:         my $start = $j*32;
                   19361:         my $cypherblock = substr($cyphertext,$start,32);
                   19362:         my $chunk =
                   19363:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19364:         $chunk .=
                   19365:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19366:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19367:         $plaintext .= $chunk;
                   19368:     }
1.1174    raeburn  19369:     return $plaintext;
                   19370: }
                   19371: 
1.1344    raeburn  19372: sub get_requested_shorturls {
1.1309    raeburn  19373:     my ($cdom,$cnum,$navmap) = @_;
                   19374:     return unless (ref($navmap));
1.1344    raeburn  19375:     my ($numnew,$errors);
1.1309    raeburn  19376:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19377:     if (@toshorten) {
                   19378:         my (%maps,%resources,%titles);
                   19379:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19380:                                                                'shorturls',$cdom,$cnum);
                   19381:         if (keys(%resources)) {
1.1344    raeburn  19382:             my %tocreate;
1.1309    raeburn  19383:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19384:                 my $symb = $resources{$item};
                   19385:                 if ($symb) {
                   19386:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19387:                 }
                   19388:             }
1.1344    raeburn  19389:             if (keys(%tocreate)) {
                   19390:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19391:                                                       \%tocreate);
                   19392:             }
1.1309    raeburn  19393:         }
1.1344    raeburn  19394:     }
                   19395:     return ($numnew,$errors);
                   19396: }
                   19397: 
                   19398: sub make_short_symbs {
                   19399:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19400:     my ($numnew,@errors);
                   19401:     if (ref($tocreateref) eq 'HASH') {
                   19402:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19403:         if (keys(%tocreate)) {
                   19404:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19405:             my $su = Short::URL->new(no_vowels => 1);
                   19406:             my $init = '';
                   19407:             my (%newunique,%addcourse,%courseonly,%failed);
                   19408:             # get lock on tiny db
                   19409:             my $now = time;
1.1344    raeburn  19410:             if ($lockuser eq '') {
                   19411:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19412:             }
1.1309    raeburn  19413:             my $lockhash = {
1.1344    raeburn  19414:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19415:                             };
                   19416:             my $tries = 0;
                   19417:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19418:             my ($code,$error);
                   19419:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19420:                 $tries ++;
                   19421:                 sleep 1;
1.1319    raeburn  19422:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19423:             }
                   19424:             if ($gotlock eq 'ok') {
                   19425:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19426:                                        \%addcourse,\%courseonly,\%failed);
                   19427:                 if (keys(%failed)) {
                   19428:                     my $numfailed = scalar(keys(%failed));
                   19429:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19430:                 }
                   19431:                 if (keys(%newunique)) {
                   19432:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19433:                     if ($putres eq 'ok') {
                   19434:                         $numnew = scalar(keys(%newunique));
                   19435:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19436:                         unless ($newputres eq 'ok') {
                   19437:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19438:                         }
                   19439:                     } else {
                   19440:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19441:                     }
                   19442:                 }
                   19443:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19444:                 unless ($dellockres eq 'ok') {
                   19445:                     push(@errors,&mt('error: could not release lockfile'));
                   19446:                 }
                   19447:             } else {
                   19448:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19449:             }
                   19450:             if (keys(%courseonly)) {
                   19451:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19452:                 if ($result ne 'ok') {
                   19453:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19454:                 }
                   19455:             }
                   19456:         }
                   19457:     }
                   19458:     return ($numnew,\@errors);
                   19459: }
                   19460: 
                   19461: sub shorten_symbs {
                   19462:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19463:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19464:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19465:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19466:     my (%possibles,%collisions);
                   19467:     foreach my $key (keys(%{$tocreate})) {
                   19468:         my $num = String::CRC32::crc32($key);
                   19469:         my $tiny = $su->encode($num,$init);
                   19470:         if ($tiny) {
                   19471:             $possibles{$tiny} = $key;
                   19472:         }
                   19473:     }
                   19474:     if (!$init) {
                   19475:         $init = 1;
                   19476:     } else {
                   19477:         $init ++;
                   19478:     }
                   19479:     if (keys(%possibles)) {
                   19480:         my @posstiny = keys(%possibles);
                   19481:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19482:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19483:         if (keys(%currtiny)) {
                   19484:             foreach my $key (keys(%currtiny)) {
                   19485:                 next if ($currtiny{$key} eq '');
                   19486:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19487:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19488:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19489:                         $courseonly->{$tsymb} = $key;
                   19490:                     }
                   19491:                 } else {
                   19492:                     $collisions{$possibles{$key}} = 1;
                   19493:                 }
                   19494:                 delete($possibles{$key});
                   19495:             }
                   19496:         }
                   19497:         foreach my $key (keys(%possibles)) {
                   19498:             $newunique->{$key} = $possibles{$key};
                   19499:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19500:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19501:                 $addcourse->{$tsymb} = $key;
                   19502:             }
                   19503:         }
                   19504:     }
                   19505:     if (keys(%collisions)) {
                   19506:         if ($init <5) {
                   19507:             if (!$init) {
                   19508:                 $init = 1;
                   19509:             } else {
                   19510:                 $init ++;
                   19511:             }
                   19512:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19513:                                    $newunique,$addcourse,$courseonly,$failed);
                   19514:         } else {
                   19515:             foreach my $key (keys(%collisions)) {
                   19516:                 $failed->{$key} = 1;
                   19517:             }
                   19518:         }
                   19519:     }
                   19520:     return $init;
                   19521: }
                   19522: 
1.1328    raeburn  19523: sub is_nonframeable {
1.1329    raeburn  19524:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19525:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19526:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19527: 
                   19528:     $remprotocol = lc($remprotocol);
                   19529:     $remhost = lc($remhost);
                   19530:     my $remport = 80;
                   19531:     if ($remprotocol eq 'https') {
                   19532:         $remport = 443;
                   19533:     }
1.1330    raeburn  19534:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19535:     if ($cached) {
                   19536:         unless ($nocache) {
                   19537:             if ($result) {
                   19538:                 return 1;
                   19539:             } else {
                   19540:                 return 0;
                   19541:             }
                   19542:         }
                   19543:     }
1.1328    raeburn  19544:     my $uselink;
                   19545:     my $request = new HTTP::Request('HEAD',$url);
                   19546:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19547:     if ($response->is_success()) {
                   19548:         my $secpolicy = lc($response->header('content-security-policy'));
                   19549:         my $xframeop = lc($response->header('x-frame-options'));
                   19550:         $secpolicy =~ s/^\s+|\s+$//g;
                   19551:         $xframeop =~ s/^\s+|\s+$//g;
                   19552:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19553:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19554:             my ($origin,$protocol,$port);
                   19555:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19556:                 $port = $ENV{'SERVER_PORT'};
                   19557:             } else {
                   19558:                 $port = 80;
                   19559:             }
                   19560:             if ($absolute eq '') {
                   19561:                 $protocol = 'http:';
                   19562:                 if ($port == 443) {
                   19563:                     $protocol = 'https:';
                   19564:                 }
                   19565:                 $origin = $protocol.'//'.lc($hostname);
                   19566:             } else {
                   19567:                 $origin = lc($absolute);
                   19568:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19569:             }
                   19570:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19571:                 my $framepolicy = $1;
                   19572:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19573:                 my @policies = split(/\s+/,$framepolicy);
                   19574:                 if (@policies) {
                   19575:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19576:                         $uselink = 1;
                   19577:                     } else {
                   19578:                         $uselink = 1;
                   19579:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19580:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19581:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19582:                             undef($uselink);
                   19583:                         }
                   19584:                         if ($uselink) {
                   19585:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19586:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19587:                                     undef($uselink);
                   19588:                                 }
                   19589:                             }
                   19590:                         }
                   19591:                         if ($uselink) {
                   19592:                             my @possok;
                   19593:                             if ($ip ne '') {
                   19594:                                 push(@possok,$ip);
                   19595:                             }
                   19596:                             my $hoststr = '';
                   19597:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19598:                                 if ($hoststr eq '') {
                   19599:                                     $hoststr = $part;
                   19600:                                 } else {
                   19601:                                     $hoststr = "$part.$hoststr";
                   19602:                                 }
                   19603:                                 if ($hoststr eq $hostname) {
                   19604:                                     push(@possok,$hostname);
                   19605:                                 } else {
                   19606:                                     push(@possok,"*.$hoststr");
                   19607:                                 }
                   19608:                             }
                   19609:                             if (@possok) {
                   19610:                                 foreach my $poss (@possok) {
                   19611:                                     last if (!$uselink);
                   19612:                                     foreach my $policy (@policies) {
                   19613:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19614:                                             undef($uselink);
                   19615:                                             last;
                   19616:                                         }
                   19617:                                     }
                   19618:                                 }
                   19619:                             }
                   19620:                         }
                   19621:                     }
                   19622:                 }
                   19623:             } elsif ($xframeop ne '') {
                   19624:                 $uselink = 1;
                   19625:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19626:                 if (@policies) {
                   19627:                     unless (grep(/^deny$/,@policies)) {
                   19628:                         if ($origin ne '') {
                   19629:                             if (grep(/^sameorigin$/,@policies)) {
                   19630:                                 if ($remotehost eq $origin) {
                   19631:                                     undef($uselink);
                   19632:                                 }
                   19633:                             }
                   19634:                             if ($uselink) {
                   19635:                                 foreach my $policy (@policies) {
                   19636:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19637:                                         my $allowfrom = $1;
                   19638:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19639:                                             undef($uselink);
                   19640:                                             last;
                   19641:                                         }
                   19642:                                     }
                   19643:                                 }
                   19644:                             }
                   19645:                         }
                   19646:                     }
                   19647:                 }
                   19648:             }
                   19649:         }
                   19650:     }
1.1329    raeburn  19651:     if ($nocache) {
                   19652:         if ($cached) {
                   19653:             my $devalidate;
                   19654:             if ($uselink && !$result) {
                   19655:                 $devalidate = 1;
                   19656:             } elsif (!$uselink && $result) {
                   19657:                 $devalidate = 1;
                   19658:             }
                   19659:             if ($devalidate) {
                   19660:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19661:             }
                   19662:         }
                   19663:     } else {
                   19664:         if ($uselink) {
                   19665:             $result = 1;
                   19666:         } else {
                   19667:             $result = 0;
                   19668:         }
                   19669:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19670:     }
1.1328    raeburn  19671:     return $uselink;
                   19672: }
                   19673: 
1.1359    raeburn  19674: sub page_menu {
                   19675:     my ($menucolls,$menunum) = @_;
                   19676:     my %menu;
                   19677:     foreach my $item (split(/;/,$menucolls)) {
                   19678:         my ($num,$value) = split(/\%/,$item);
                   19679:         if ($num eq $menunum) {
                   19680:             my @entries = split(/\&/,$value);
                   19681:             foreach my $entry (@entries) {
                   19682:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19683:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19684:                     $menu{$name} = $fields;
                   19685:                 } else {
                   19686:                     my @shown;
                   19687:                     if ($fields =~ /,/) {
                   19688:                         @shown = split(/,/,$fields);
                   19689:                     } else {
                   19690:                         @shown = ($fields);
                   19691:                     }
                   19692:                     if (@shown) {
                   19693:                         foreach my $field (@shown) {
                   19694:                             next if ($field eq '');
                   19695:                             $menu{$field} = 1;
                   19696:                         }
                   19697:                     }
                   19698:                 }
                   19699:             }
                   19700:         }
                   19701:     }
                   19702:     return %menu;
                   19703: }
                   19704: 
1.112     bowersj2 19705: 1;
                   19706: __END__;
1.41      ng       19707: 

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