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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1452  ! raeburn     4: # $Id: loncommon.pm,v 1.1451 2025/02/07 05:40:54 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,
1.1450    raeburn  1177:         $suffix,
                   1178:         $haslabel
1.36      matthew  1179:         ) = @_;
                   1180:     my $second = "document.$formname.$secondselectname";
                   1181:     my $first = "document.$formname.$firstselectname";
                   1182:     # output the javascript to do the changing
                   1183:     my $result = '';
1.776     bisitz   1184:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1185:     $result.="// <![CDATA[\n";
1.1245    raeburn  1186:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1187:     $" = '","';
                   1188:     my $debug = '';
                   1189:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1191:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1192:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1193:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1194:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1195:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1196:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1197:         }
1.36      matthew  1198:         $result.="\"@s2values\");\n";
1.1245    raeburn  1199:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1200:         my @s2texts;
                   1201:         foreach my $value (@s2values) {
1.1263    raeburn  1202:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1203:         }
                   1204:         $result.="\"@s2texts\");\n";
                   1205:     }
                   1206:     $"=' ';
                   1207:     $result.= <<"END";
                   1208: 
1.1245    raeburn  1209: function select1${suffix}_changed() {
1.36      matthew  1210:     // Determine new choice
1.1245    raeburn  1211:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1212:     // update select2
1.1245    raeburn  1213:     var values     = select2data${suffix}[newvalue].values;
                   1214:     var texts      = select2data${suffix}[newvalue].texts;
                   1215:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1216:     var i;
                   1217:     // out with the old
1.1245    raeburn  1218:     $second.options.length = 0;
                   1219:     // in with the new
1.36      matthew  1220:     for (i=0;i<values.length; i++) {
                   1221:         $second.options[i] = new Option(values[i]);
1.143     matthew  1222:         $second.options[i].value = values[i];
1.36      matthew  1223:         $second.options[i].text = texts[i];
                   1224:         if (values[i] == select2def) {
                   1225:             $second.options[i].selected = true;
                   1226:         }
                   1227:     }
                   1228: }
1.824     bisitz   1229: // ]]>
1.36      matthew  1230: </script>
                   1231: END
                   1232:     # output the initial values for the selection lists
1.1245    raeburn  1233:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1234:     my @order = sort(keys(%{$hashref}));
                   1235:     if (ref($menuorder) eq 'ARRAY') {
                   1236:         @order = @{$menuorder};
                   1237:     }
                   1238:     foreach my $value (@order) {
1.36      matthew  1239:         $result.="    <option value=\"$value\" ";
1.253     albertel 1240:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1241:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1242:     }
                   1243:     $result .= "</select>\n";
1.1450    raeburn  1244:     if ($haslabel) {
                   1245:         $result .= '</label>';
                   1246:     }
1.1400    raeburn  1247:     my %select2;
                   1248:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1249:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1250:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1251:         }
                   1252:     }
1.1450    raeburn  1253:     if ($middletext ne '') {
1.1452  ! raeburn  1254:         $result .= '<label>'.$middletext;
1.1450    raeburn  1255:     }
1.1115    raeburn  1256:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1257:     if ($onchangesecond) {
                   1258:         $result .= ' onchange="'.$onchangesecond.'"';
                   1259:     }
                   1260:     $result .= ">\n";
1.36      matthew  1261:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1262:     
                   1263:     my @secondorder = sort(keys(%select2));
                   1264:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1265:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1266:     }
                   1267:     foreach my $value (@secondorder) {
1.36      matthew  1268:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1269:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1270:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1271:     }
                   1272:     $result .= "</select>\n";
1.1450    raeburn  1273:     if ($middletext ne '') {
                   1274:         $result .= '</label>';
                   1275:     }
1.36      matthew  1276:     #    return $debug;
                   1277:     return $result;
                   1278: }   #  end of sub linked_select_forms {
                   1279: 
1.45      matthew  1280: =pod
1.44      bowersj2 1281: 
1.1381    raeburn  1282: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1283: 
1.112     bowersj2 1284: Returns a string corresponding to an HTML link to the given help
                   1285: $topic, where $topic corresponds to the name of a .tex file in
                   1286: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1287: spaces. 
                   1288: 
                   1289: $text will optionally be linked to the same topic, allowing you to
                   1290: link text in addition to the graphic. If you do not want to link
                   1291: text, but wish to specify one of the later parameters, pass an
                   1292: empty string. 
                   1293: 
                   1294: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1295: the link will not open a new window. If false, the link will open
                   1296: a new window using Javascript. (Default is false.) 
                   1297: 
                   1298: $width and $height are optional numerical parameters that will
                   1299: override the width and height of the popped up window, which may
1.973     raeburn  1300: be useful for certain help topics with big pictures included.
                   1301: 
                   1302: $imgid is the id of the img tag used for the help icon. This may be
                   1303: used in a javascript call to switch the image src.  See 
                   1304: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1305: 
1.1381    raeburn  1306: $links_target will optionally be set to a target (_top, _parent or _self).
                   1307: 
1.44      bowersj2 1308: =cut
                   1309: 
                   1310: sub help_open_topic {
1.1381    raeburn  1311:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1312:     $text = "" if (not defined $text);
1.44      bowersj2 1313:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1314:     $width = 500 if (not defined $width);
1.44      bowersj2 1315:     $height = 400 if (not defined $height);
                   1316:     my $filename = $topic;
                   1317:     $filename =~ s/ /_/g;
                   1318: 
1.48      bowersj2 1319:     my $template = "";
                   1320:     my $link;
1.572     banghart 1321:     
1.159     www      1322:     $topic=~s/\W/\_/g;
1.44      bowersj2 1323: 
1.572     banghart 1324:     if (!$stayOnPage) {
1.1033    www      1325: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1326:     } elsif ($stayOnPage eq 'popup') {
                   1327:         $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 1328:     } else {
1.48      bowersj2 1329: 	$link = "/adm/help/${filename}.hlp";
                   1330:     }
                   1331: 
                   1332:     # Add the text
1.1314    raeburn  1333:     my $target = ' target="_top"';
1.1381    raeburn  1334:     if ($links_target) {
                   1335:         $target = ' target="'.$links_target.'"';
                   1336:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1337:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1338:         $target = '';
1.1378    raeburn  1339:     }
1.1380    raeburn  1340:     if ($text ne "") {
1.763     bisitz   1341: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1342:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1343:                   .$text.'</a>';
1.48      bowersj2 1344:     }
                   1345: 
1.763     bisitz   1346:     # (Always) Add the graphic
1.179     matthew  1347:     my $title = &mt('Online Help');
1.667     raeburn  1348:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1349:     if ($imgid ne '') {
                   1350:         $imgid = ' id="'.$imgid.'"';
                   1351:     }
1.1314    raeburn  1352:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1353:               .'<img src="'.$helpicon.'" border="0"'
                   1354:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1355:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1356:               .' /></a>';
                   1357:     if ($text ne "") {	
                   1358:         $template.='</span>';
                   1359:     }
1.44      bowersj2 1360:     return $template;
                   1361: 
1.106     bowersj2 1362: }
                   1363: 
                   1364: # This is a quicky function for Latex cheatsheet editing, since it 
                   1365: # appears in at least four places
                   1366: sub helpLatexCheatsheet {
1.1037    www      1367:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1368:     my $out;
1.106     bowersj2 1369:     my $addOther = '';
1.732     raeburn  1370:     if ($topic) {
1.1037    www      1371: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1372:     }
                   1373:     $out = '<span>' # Start cheatsheet
                   1374: 	  .$addOther
                   1375:           .'<span>'
1.1037    www      1376: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1377: 	  .'</span> <span>'
1.1037    www      1378: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1379: 	  .'</span>';
1.732     raeburn  1380:     unless ($not_author) {
1.1186    kruse    1381:         $out .= '<span>'
                   1382:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1383:                .'</span> <span>'
1.1424    raeburn  1384:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.763     bisitz   1385: 	       .'</span>';
1.732     raeburn  1386:     }
1.763     bisitz   1387:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1388:     return $out;
1.172     www      1389: }
                   1390: 
1.430     albertel 1391: sub general_help {
                   1392:     my $helptopic='Student_Intro';
                   1393:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1394: 	$helptopic='Authoring_Intro';
1.907     raeburn  1395:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1396: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1397:     } elsif ($env{'request.role'}=~/^dc/) {
                   1398:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1399:     }
                   1400:     return $helptopic;
                   1401: }
                   1402: 
                   1403: sub update_help_link {
                   1404:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1405:     my $origurl = $ENV{'REQUEST_URI'};
                   1406:     $origurl=~s|^/~|/priv/|;
                   1407:     my $timestamp = time;
                   1408:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1409:         $$datum = &escape($$datum);
                   1410:     }
                   1411: 
                   1412:     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";
                   1413:     my $output .= <<"ENDOUTPUT";
                   1414: <script type="text/javascript">
1.824     bisitz   1415: // <![CDATA[
1.430     albertel 1416: banner_link = '$banner_link';
1.824     bisitz   1417: // ]]>
1.430     albertel 1418: </script>
                   1419: ENDOUTPUT
                   1420:     return $output;
                   1421: }
                   1422: 
                   1423: # now just updates the help link and generates a blue icon
1.193     raeburn  1424: sub help_open_menu {
1.1381    raeburn  1425:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1426: 	= @_;    
1.949     droeschl 1427:     $stayOnPage = 1;
1.430     albertel 1428:     my $output;
                   1429:     if ($component_help) {
                   1430: 	if (!$text) {
                   1431: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1432: 				       $width,$height,'',$links_target);
1.430     albertel 1433: 	} else {
                   1434: 	    my $help_text;
                   1435: 	    $help_text=&unescape($topic);
                   1436: 	    $output='<table><tr><td>'.
                   1437: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1438: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1439: 	}
                   1440:     }
                   1441:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1442:     return $output.$banner_link;
                   1443: }
                   1444: 
                   1445: sub top_nav_help {
1.1369    raeburn  1446:     my ($text,$linkattr) = @_;
1.436     albertel 1447:     $text = &mt($text);
1.949     droeschl 1448:     my $stay_on_page = 1;
                   1449: 
1.1168    raeburn  1450:     my ($link,$banner_link);
                   1451:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1452:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1453: 	                         : "javascript:helpMenu('open')";
                   1454:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1455:     }
1.201     raeburn  1456:     my $title = &mt('Get help');
1.1168    raeburn  1457:     if ($link) {
                   1458:         return <<"END";
1.436     albertel 1459: $banner_link
1.1369    raeburn  1460: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1461: END
1.1168    raeburn  1462:     } else {
                   1463:         return '&nbsp;'.$text.'&nbsp;';
                   1464:     }
1.436     albertel 1465: }
                   1466: 
                   1467: sub help_menu_js {
1.1154    raeburn  1468:     my ($httphost) = @_;
1.949     droeschl 1469:     my $stayOnPage = 1;
1.436     albertel 1470:     my $width = 620;
                   1471:     my $height = 600;
1.430     albertel 1472:     my $helptopic=&general_help();
1.1154    raeburn  1473:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1474:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1475:     my $start_page =
                   1476:         &Apache::loncommon::start_page('Help Menu', undef,
                   1477: 				       {'frameset'    => 1,
                   1478: 					'js_ready'    => 1,
1.1154    raeburn  1479:                                         'use_absolute' => $httphost,
1.331     albertel 1480: 					'add_entries' => {
1.1168    raeburn  1481: 					    'border' => '0', 
1.579     raeburn  1482: 					    'rows'   => "110,*",},});
1.331     albertel 1483:     my $end_page =
                   1484:         &Apache::loncommon::end_page({'frameset' => 1,
                   1485: 				      'js_ready' => 1,});
                   1486: 
1.436     albertel 1487:     my $template .= <<"ENDTEMPLATE";
                   1488: <script type="text/javascript">
1.877     bisitz   1489: // <![CDATA[
1.253     albertel 1490: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1491: var banner_link = '';
1.243     raeburn  1492: function helpMenu(target) {
                   1493:     var caller = this;
                   1494:     if (target == 'open') {
                   1495:         var newWindow = null;
                   1496:         try {
1.262     albertel 1497:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1498:         }
                   1499:         catch(error) {
                   1500:             writeHelp(caller);
                   1501:             return;
                   1502:         }
                   1503:         if (newWindow) {
                   1504:             caller = newWindow;
                   1505:         }
1.193     raeburn  1506:     }
1.243     raeburn  1507:     writeHelp(caller);
                   1508:     return;
                   1509: }
                   1510: function writeHelp(caller) {
1.1168    raeburn  1511:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1512:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1513:     caller.document.close();
                   1514:     caller.focus();
1.193     raeburn  1515: }
1.877     bisitz   1516: // END LON-CAPA Internal -->
1.253     albertel 1517: // ]]>
1.436     albertel 1518: </script>
1.193     raeburn  1519: ENDTEMPLATE
                   1520:     return $template;
                   1521: }
                   1522: 
1.172     www      1523: sub help_open_bug {
                   1524:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1525:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1526:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1527:     $text = "" if (not defined $text);
                   1528: 	$stayOnPage=1;
1.184     albertel 1529:     $width = 600 if (not defined $width);
                   1530:     $height = 600 if (not defined $height);
1.172     www      1531: 
                   1532:     $topic=~s/\W+/\+/g;
                   1533:     my $link='';
                   1534:     my $template='';
1.379     albertel 1535:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1536: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1537:     if (!$stayOnPage)
                   1538:     {
                   1539: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1540:     }
                   1541:     else
                   1542:     {
                   1543: 	$link = $url;
                   1544:     }
1.1314    raeburn  1545: 
1.1382    raeburn  1546:     my $target = '_top';
                   1547:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1548:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1549:         $target = '_blank';
1.1378    raeburn  1550:     }
1.1382    raeburn  1551: 
1.172     www      1552:     # Add the text
                   1553:     if ($text ne "")
                   1554:     {
                   1555: 	$template .= 
                   1556:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1557:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1558:     }
                   1559: 
                   1560:     # Add the graphic
1.179     matthew  1561:     my $title = &mt('Report a Bug');
1.215     albertel 1562:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1563:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1564:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1565: ENDTEMPLATE
                   1566:     if ($text ne '') { $template.='</td></tr></table>' };
                   1567:     return $template;
                   1568: 
                   1569: }
                   1570: 
                   1571: sub help_open_faq {
                   1572:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1573:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1574:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1575:     $text = "" if (not defined $text);
                   1576: 	$stayOnPage=1;
                   1577:     $width = 350 if (not defined $width);
                   1578:     $height = 400 if (not defined $height);
                   1579: 
                   1580:     $topic=~s/\W+/\+/g;
                   1581:     my $link='';
                   1582:     my $template='';
                   1583:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1584:     if (!$stayOnPage)
                   1585:     {
                   1586: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1587:     }
                   1588:     else
                   1589:     {
                   1590: 	$link = $url;
                   1591:     }
                   1592: 
                   1593:     # Add the text
                   1594:     if ($text ne "")
                   1595:     {
                   1596: 	$template .= 
1.173     www      1597:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1598:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1599:     }
                   1600: 
                   1601:     # Add the graphic
1.179     matthew  1602:     my $title = &mt('View the FAQ');
1.215     albertel 1603:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1604:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1605:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1606: ENDTEMPLATE
                   1607:     if ($text ne '') { $template.='</td></tr></table>' };
                   1608:     return $template;
                   1609: 
1.44      bowersj2 1610: }
1.37      matthew  1611: 
1.180     matthew  1612: ###############################################################
                   1613: ###############################################################
                   1614: 
1.45      matthew  1615: =pod
                   1616: 
1.648     raeburn  1617: =item * &change_content_javascript():
1.256     matthew  1618: 
                   1619: This and the next function allow you to create small sections of an
                   1620: otherwise static HTML page that you can update on the fly with
                   1621: Javascript, even in Netscape 4.
                   1622: 
                   1623: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1624: must be written to the HTML page once. It will prove the Javascript
                   1625: function "change(name, content)". Calling the change function with the
                   1626: name of the section 
                   1627: you want to update, matching the name passed to C<changable_area>, and
                   1628: the new content you want to put in there, will put the content into
                   1629: that area.
                   1630: 
                   1631: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1632: to contain room for the original contents. You need to "make space"
                   1633: for whatever changes you wish to make, and be B<sure> to check your
                   1634: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1635: it's adequate for updating a one-line status display, but little more.
                   1636: This script will set the space to 100% width, so you only need to
                   1637: worry about height in Netscape 4.
                   1638: 
                   1639: Modern browsers are much less limiting, and if you can commit to the
                   1640: user not using Netscape 4, this feature may be used freely with
                   1641: pretty much any HTML.
                   1642: 
                   1643: =cut
                   1644: 
                   1645: sub change_content_javascript {
                   1646:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1647:     if ($env{'browser.type'} eq 'netscape' &&
                   1648: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1649: 	return (<<NETSCAPE4);
                   1650: 	function change(name, content) {
                   1651: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1652: 	    doc.open();
                   1653: 	    doc.write(content);
                   1654: 	    doc.close();
                   1655: 	}
                   1656: NETSCAPE4
                   1657:     } else {
                   1658: 	# Otherwise, we need to use semi-standards-compliant code
                   1659: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1660: 	# is really scary, and every useful browser supports it
                   1661: 	return (<<DOMBASED);
                   1662: 	function change(name, content) {
                   1663: 	    element = document.getElementById(name);
                   1664: 	    element.innerHTML = content;
                   1665: 	}
                   1666: DOMBASED
                   1667:     }
                   1668: }
                   1669: 
                   1670: =pod
                   1671: 
1.648     raeburn  1672: =item * &changable_area($name,$origContent):
1.256     matthew  1673: 
                   1674: This provides a "changable area" that can be modified on the fly via
                   1675: the Javascript code provided in C<change_content_javascript>. $name is
                   1676: the name you will use to reference the area later; do not repeat the
                   1677: same name on a given HTML page more then once. $origContent is what
                   1678: the area will originally contain, which can be left blank.
                   1679: 
                   1680: =cut
                   1681: 
                   1682: sub changable_area {
                   1683:     my ($name, $origContent) = @_;
                   1684: 
1.258     albertel 1685:     if ($env{'browser.type'} eq 'netscape' &&
                   1686: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1687: 	# If this is netscape 4, we need to use the Layer tag
                   1688: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1689:     } else {
                   1690: 	return "<span id='$name'>$origContent</span>";
                   1691:     }
                   1692: }
                   1693: 
                   1694: =pod
                   1695: 
1.648     raeburn  1696: =item * &viewport_geometry_js 
1.590     raeburn  1697: 
                   1698: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1699: 
                   1700: =cut
                   1701: 
                   1702: 
                   1703: sub viewport_geometry_js { 
                   1704:     return <<"GEOMETRY";
                   1705: var Geometry = {};
                   1706: function init_geometry() {
                   1707:     if (Geometry.init) { return };
                   1708:     Geometry.init=1;
                   1709:     if (window.innerHeight) {
                   1710:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1711:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1712:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1713:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1714:     }
                   1715:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1716:         Geometry.getViewportHeight =
                   1717:             function() { return document.documentElement.clientHeight; };
                   1718:         Geometry.getViewportWidth =
                   1719:             function() { return document.documentElement.clientWidth; };
                   1720: 
                   1721:         Geometry.getHorizontalScroll =
                   1722:             function() { return document.documentElement.scrollLeft; };
                   1723:         Geometry.getVerticalScroll =
                   1724:             function() { return document.documentElement.scrollTop; };
                   1725:     }
                   1726:     else if (document.body.clientHeight) {
                   1727:         Geometry.getViewportHeight =
                   1728:             function() { return document.body.clientHeight; };
                   1729:         Geometry.getViewportWidth =
                   1730:             function() { return document.body.clientWidth; };
                   1731:         Geometry.getHorizontalScroll =
                   1732:             function() { return document.body.scrollLeft; };
                   1733:         Geometry.getVerticalScroll =
                   1734:             function() { return document.body.scrollTop; };
                   1735:     }
                   1736: }
                   1737: 
                   1738: GEOMETRY
                   1739: }
                   1740: 
                   1741: =pod
                   1742: 
1.648     raeburn  1743: =item * &viewport_size_js()
1.590     raeburn  1744: 
                   1745: 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. 
                   1746: 
                   1747: =cut
                   1748: 
                   1749: sub viewport_size_js {
                   1750:     my $geometry = &viewport_geometry_js();
                   1751:     return <<"DIMS";
                   1752: 
                   1753: $geometry
                   1754: 
                   1755: function getViewportDims(width,height) {
                   1756:     init_geometry();
                   1757:     width.value = Geometry.getViewportWidth();
                   1758:     height.value = Geometry.getViewportHeight();
                   1759:     return;
                   1760: }
                   1761: 
                   1762: DIMS
                   1763: }
                   1764: 
                   1765: =pod
                   1766: 
1.648     raeburn  1767: =item * &resize_textarea_js()
1.565     albertel 1768: 
                   1769: emits the needed javascript to resize a textarea to be as big as possible
                   1770: 
                   1771: creates a function resize_textrea that takes two IDs first should be
                   1772: the id of the element to resize, second should be the id of a div that
                   1773: surrounds everything that comes after the textarea, this routine needs
                   1774: to be attached to the <body> for the onload and onresize events.
                   1775: 
                   1776: =cut
                   1777: 
                   1778: sub resize_textarea_js {
1.590     raeburn  1779:     my $geometry = &viewport_geometry_js();
1.565     albertel 1780:     return <<"RESIZE";
                   1781:     <script type="text/javascript">
1.824     bisitz   1782: // <![CDATA[
1.590     raeburn  1783: $geometry
1.565     albertel 1784: 
1.588     albertel 1785: function getX(element) {
                   1786:     var x = 0;
                   1787:     while (element) {
                   1788: 	x += element.offsetLeft;
                   1789: 	element = element.offsetParent;
                   1790:     }
                   1791:     return x;
                   1792: }
                   1793: function getY(element) {
                   1794:     var y = 0;
                   1795:     while (element) {
                   1796: 	y += element.offsetTop;
                   1797: 	element = element.offsetParent;
                   1798:     }
                   1799:     return y;
                   1800: }
                   1801: 
                   1802: 
1.565     albertel 1803: function resize_textarea(textarea_id,bottom_id) {
                   1804:     init_geometry();
                   1805:     var textarea        = document.getElementById(textarea_id);
                   1806:     //alert(textarea);
                   1807: 
1.588     albertel 1808:     var textarea_top    = getY(textarea);
1.565     albertel 1809:     var textarea_height = textarea.offsetHeight;
                   1810:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1811:     var bottom_top      = getY(bottom);
1.565     albertel 1812:     var bottom_height   = bottom.offsetHeight;
                   1813:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1814:     var fudge           = 23;
1.565     albertel 1815:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1816:     if (new_height < 300) {
                   1817: 	new_height = 300;
                   1818:     }
                   1819:     textarea.style.height=new_height+'px';
                   1820: }
1.824     bisitz   1821: // ]]>
1.565     albertel 1822: </script>
                   1823: RESIZE
                   1824: 
                   1825: }
                   1826: 
1.1205    golterma 1827: sub colorfuleditor_js {
1.1248    raeburn  1828:     my $browse_or_search;
                   1829:     my $respath;
                   1830:     my ($cnum,$cdom) = &crsauthor_url();
                   1831:     if ($cnum) {
                   1832:         $respath = "/res/$cdom/$cnum/";
                   1833:         my %js_lt = &Apache::lonlocal::texthash(
                   1834:             sunm => 'Sub-directory name',
                   1835:             save => 'Save page to make this permanent',
                   1836:         );
                   1837:         &js_escape(\%js_lt);
1.1400    raeburn  1838:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1839:         $browse_or_search = <<"END";
                   1840: 
1.1400    raeburn  1841:     $showfile_js
                   1842: 
1.1248    raeburn  1843:     function toggleChooser(form,element,titleid,only,search) {
                   1844:         var disp = 'none';
                   1845:         if (document.getElementById('chooser_'+element)) {
                   1846:             var curr = document.getElementById('chooser_'+element).style.display;
                   1847:             if (curr == 'none') {
                   1848:                 disp='inline';
                   1849:                 if (form.elements['chooser_'+element].length) {
                   1850:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1851:                         form.elements['chooser_'+element][i].checked = false;
                   1852:                     }
                   1853:                 }
                   1854:                 toggleResImport(form,element);
                   1855:             }
                   1856:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1857:             var dirsel = '';
                   1858:             var filesel = '';
                   1859:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1860:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1861:                 if (currcrsres == 'none') {
                   1862:                     dirsel = 'coursepath_'+element;
                   1863:                     var filesel = 'coursefile_'+element;
                   1864:                     var include;
                   1865:                     if (document.getElementById('crsres_include_'+element)) {
                   1866:                         include = document.getElementById('crsres_include_'+element).value;
                   1867:                     }
1.1402    raeburn  1868:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1869:                 }
                   1870:             }
                   1871:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1872:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1873:                 if (currcrsupload == 'none') {
                   1874:                     dirsel = 'crsauthorpath_'+element;
                   1875:                     filesel = '';
1.1402    raeburn  1876:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1877:                 }
                   1878:             }
1.1248    raeburn  1879:         }
                   1880:     }
                   1881: 
1.1400    raeburn  1882:     function toggleCrsFile(form,element) {
1.1248    raeburn  1883:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1884:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1885:             if (curr == 'none') {
1.1400    raeburn  1886:                 if (document.getElementById('coursepath_'+element)) {
                   1887:                     var numdirs;
                   1888:                     if (document.getElementById('coursepath_'+element).length) {
                   1889:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1890:                     }
1.1402    raeburn  1891:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1892:                         (document.getElementById('nocrsres_'+element))) {
                   1893:                         if (numdirs) {
                   1894:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1895:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1896:                         } else {
                   1897:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1898:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1899:                         }
                   1900:                     }
1.1248    raeburn  1901:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1902:                     if (numdirs > 1) {
1.1400    raeburn  1903:                         var selelem = form.elements['coursefile_'+element];
                   1904:                         var i, len = selelem.options.length -1;
                   1905:                         if (len >=0) {
                   1906:                             for (i = len; i >= 0; i--) {
                   1907:                                 selelem.remove(i);
                   1908:                             }
                   1909:                             selelem.options[0] = new Option('','');
                   1910:                         }
1.1248    raeburn  1911:                     }
                   1912:                 }
1.1400    raeburn  1913:             }
1.1248    raeburn  1914:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1915:         }
                   1916:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1917:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1918:             if (document.getElementById('uploadcrsres_'+element)) {
                   1919:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1920:             }
                   1921:         }
                   1922:         return;
                   1923:     }
                   1924: 
1.1400    raeburn  1925:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1926:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1927:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1928:         }
                   1929:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1930:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1931:             if (curr == 'none') {
1.1400    raeburn  1932:                 form.elements['newsubdir_'+element][0].checked = true;
                   1933:                 toggleNewsubdir(form,element);
                   1934:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1935:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1936:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1937:                 }
                   1938:             }
                   1939:         }
                   1940:         return;
                   1941:     }
                   1942: 
                   1943:     function toggleResImport(form,element) {
                   1944:         var choices = new Array('crsres','upload');
                   1945:         for (var i=0; i<choices.length; i++) {
                   1946:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1947:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1948:             }
                   1949:         }
                   1950:     }
                   1951: 
                   1952:     function toggleNewsubdir(form,element) {
                   1953:         var newsub = form.elements['newsubdir_'+element];
                   1954:         if (newsub) {
                   1955:             if (newsub.length) {
                   1956:                 for (var j=0; j<newsub.length; j++) {
                   1957:                     if (newsub[j].checked) {
                   1958:                         if (document.getElementById('newsubdirname_'+element)) {
                   1959:                             if (newsub[j].value == '1') {
                   1960:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1961:                                 if (document.getElementById('newsubdir_'+element)) {
                   1962:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1963:                                 }
                   1964:                             } else {
                   1965:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1966:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1967:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1968:                             }
                   1969:                         }
                   1970:                         break; 
                   1971:                     }
                   1972:                 }
                   1973:             }
                   1974:         }
                   1975:     }
                   1976: 
                   1977:     function updateCrsFile(form,element) {
                   1978:         var directory = form.elements['coursepath_'+element];
                   1979:         var filename = form.elements['coursefile_'+element];
                   1980:         var path = directory.options[directory.selectedIndex].value;
                   1981:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1982:         if (file != '') {
                   1983:             form.elements[element].value = '$respath';
                   1984:             if (path == '/') {
                   1985:                 form.elements[element].value += file;
                   1986:             } else {
                   1987:                 form.elements[element].value += path+'/'+file;
                   1988:             }
                   1989:             unClean();
                   1990:             if (document.getElementById('previewimg_'+element)) {
                   1991:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1992:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1993:             }
                   1994:             if (document.getElementById('showimg_'+element)) {
                   1995:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1996:             }
1.1248    raeburn  1997:         }
                   1998:         toggleChooser(form,element);
                   1999:         return;
                   2000:     }
                   2001: 
                   2002:     function uploadDone(suffix,name) {
                   2003:         if (name) {
                   2004: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   2005:             unClean();
                   2006:             toggleChooser(document.forms["lonhomework"],suffix);
                   2007:         }
                   2008:     }
                   2009: 
                   2010: \$(document).ready(function(){
                   2011: 
                   2012:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2013:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2014:             var buttonId = this.id;
                   2015:             var suffix = buttonId.toString();
                   2016:             suffix = suffix.replace(/^crsupload_/,'');
                   2017:             event.preventDefault();
                   2018:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2019:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2020:             \$(this.form).submit();
                   2021:             document.lonhomework.target = '';
                   2022:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2023:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2024:             }
                   2025:             return false;
                   2026:         }
                   2027:     });
                   2028: });
                   2029: END
                   2030:     }
1.1205    golterma 2031:     return <<"COLORFULEDIT"
                   2032: <script type="text/javascript">
                   2033: // <![CDATA[>
                   2034:     function fold_box(curDepth, lastresource){
                   2035: 
                   2036:     // we need a list because there can be several blocks you need to fold in one tag
                   2037:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2038:     // but there is only one folding button per tag
                   2039:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2040: 
                   2041:         if(block.item(0).style.display == 'none'){
                   2042: 
                   2043:             foldbutton.value = '@{[&mt("Hide")]}';
                   2044:             for (i = 0; i < block.length; i++){
                   2045:                 block.item(i).style.display = '';
                   2046:             }
                   2047:         }else{
                   2048: 
                   2049:             foldbutton.value = '@{[&mt("Show")]}';
                   2050:             for (i = 0; i < block.length; i++){
                   2051:                 // block.item(i).style.visibility = 'collapse';
                   2052:                 block.item(i).style.display = 'none';
                   2053:             }
                   2054:         };
                   2055:         saveState(lastresource);
                   2056:     }
                   2057: 
                   2058:     function saveState (lastresource) {
                   2059: 
                   2060:         var tag_list = getTagList();
                   2061:         if(tag_list != null){
                   2062:             var timestamp = new Date().getTime();
                   2063:             var key = lastresource;
                   2064: 
                   2065:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2066:             // starting with timestamp
                   2067:             var value = timestamp+';';
                   2068: 
                   2069:             // building the list of key-value pairs
                   2070:             for(var i = 0; i < tag_list.length; i++){
                   2071:                 value += tag_list[i]+',';
                   2072:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2073:             }
                   2074: 
                   2075:             // only iterate whole storage if nothing to override
                   2076:             if(localStorage.getItem(key) == null){        
                   2077: 
                   2078:                 // prevent storage from growing large
                   2079:                 if(localStorage.length > 50){
                   2080:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2081:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2082:                     var oldest_key;
                   2083:                     
                   2084:                     for(var i = 1; i < localStorage.length; i++){
                   2085:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2086:                             oldest_key = localStorage.key(i);
                   2087:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2088:                         }
                   2089:                     }
                   2090:                     localStorage.removeItem(oldest_key);
                   2091:                 }
                   2092:             }
                   2093:             localStorage.setItem(key,value);
                   2094:         }
                   2095:     }
                   2096: 
                   2097:     // restore folding status of blocks (on page load)
                   2098:     function restoreState (lastresource) {
                   2099:         if(localStorage.getItem(lastresource) != null){
                   2100:             var key = lastresource;
                   2101:             var value = localStorage.getItem(key);
                   2102:             var regex_delTimestamp = /^\d+;/;
                   2103: 
                   2104:             value.replace(regex_delTimestamp, '');
                   2105: 
                   2106:             var valueArr = value.split(';');
                   2107:             var pairs;
                   2108:             var elements;
                   2109:             for (var i = 0; i < valueArr.length; i++){
                   2110:                 pairs = valueArr[i].split(',');
                   2111:                 elements = document.getElementsByName(pairs[0]);
                   2112: 
                   2113:                 for (var j = 0; j < elements.length; j++){  
                   2114:                     elements[j].style.display = pairs[1];
                   2115:                     if (pairs[1] == "none"){
                   2116:                         var regex_id = /([_\\d]+)\$/;
                   2117:                         regex_id.exec(pairs[0]);
                   2118:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2119:                     }
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
                   2124: 
                   2125:     function getTagList () {
                   2126:         
                   2127:         var stringToSearch = document.lonhomework.innerHTML;
                   2128: 
                   2129:         var ret = new Array();
                   2130:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2131:         var tag_list = stringToSearch.match(regex_findBlock);
                   2132: 
                   2133:         if(tag_list != null){
                   2134:             for(var i = 0; i < tag_list.length; i++){            
                   2135:                 ret.push(tag_list[i].replace(/"/, ''));
                   2136:             }
                   2137:         }
                   2138:         return ret;
                   2139:     }
                   2140: 
                   2141:     function saveScrollPosition (resource) {
                   2142:         var tag_list = getTagList();
                   2143: 
                   2144:         // we dont always want to jump to the first block
                   2145:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2146:         if(\$(window).scrollTop() > 170){
                   2147:             if(tag_list != null){
                   2148:                 var result;
                   2149:                 for(var i = 0; i < tag_list.length; i++){
                   2150:                     if(isElementInViewport(tag_list[i])){
                   2151:                         result += tag_list[i]+';';
                   2152:                     }
                   2153:                 }
                   2154:                 sessionStorage.setItem('anchor_'+resource, result);
                   2155:             }
                   2156:         } else {
                   2157:             // we dont need to save zero, just delete the item to leave everything tidy
                   2158:             sessionStorage.removeItem('anchor_'+resource);
                   2159:         }
                   2160:     }
                   2161: 
                   2162:     function restoreScrollPosition(resource){
                   2163: 
                   2164:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2165:         if(elem != null){
                   2166:             var tag_list = elem.split(';');
                   2167:             var elem_list;
                   2168: 
                   2169:             for(var i = 0; i < tag_list.length; i++){
                   2170:                 elem_list = document.getElementsByName(tag_list[i]);
                   2171:                 
                   2172:                 if(elem_list.length > 0){
                   2173:                     elem = elem_list[0];
                   2174:                     break;
                   2175:                 }
                   2176:             }
                   2177:             elem.scrollIntoView();
                   2178:         }
                   2179:     }
                   2180: 
                   2181:     function isElementInViewport(el) {
                   2182: 
                   2183:         // change to last element instead of first
                   2184:         var elem = document.getElementsByName(el);
                   2185:         var rect = elem[0].getBoundingClientRect();
                   2186: 
                   2187:         return (
                   2188:             rect.top >= 0 &&
                   2189:             rect.left >= 0 &&
                   2190:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2191:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2192:         );
                   2193:     }
                   2194:     
                   2195:     function autosize(depth){
                   2196:         var cmInst = window['cm'+depth];
                   2197:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2198: 
                   2199:         // is fixed size, switching to dynamic
                   2200:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2201:             cmInst.setSize("","auto");
                   2202:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2203:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2204: 
                   2205:         // is dynamic size, switching to fixed
                   2206:         } else {
                   2207:             cmInst.setSize("","300px");
                   2208:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2209:             sessionStorage.removeItem("autosized_"+depth);
                   2210:         }
                   2211:     }
                   2212: 
1.1248    raeburn  2213: $browse_or_search
1.1205    golterma 2214: 
                   2215: // ]]>
                   2216: </script>
                   2217: COLORFULEDIT
                   2218: }
                   2219: 
                   2220: sub xmleditor_js {
                   2221:     return <<XMLEDIT
                   2222: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2223: <script type="text/javascript">
                   2224: // <![CDATA[>
                   2225: 
                   2226:     function saveScrollPosition (resource) {
                   2227: 
                   2228:         var scrollPos = \$(window).scrollTop();
                   2229:         sessionStorage.setItem(resource,scrollPos);
                   2230:     }
                   2231: 
                   2232:     function restoreScrollPosition(resource){
                   2233: 
                   2234:         var scrollPos = sessionStorage.getItem(resource);
                   2235:         \$(window).scrollTop(scrollPos);
                   2236:     }
                   2237: 
                   2238:     // unless internet explorer
                   2239:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2240: 
                   2241:         \$(document).ready(function() {
                   2242:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2243:         });
                   2244:     }
                   2245: 
                   2246:     // inserts text at cursor position into codemirror (xml editor only)
                   2247:     function insertText(text){
                   2248:         cm.focus();
                   2249:         var curPos = cm.getCursor();
                   2250:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2251:     }
                   2252: // ]]>
                   2253: </script>
                   2254: XMLEDIT
                   2255: }
                   2256: 
                   2257: sub insert_folding_button {
                   2258:     my $curDepth = $Apache::lonxml::curdepth;
                   2259:     my $lastresource = $env{'request.ambiguous'};
                   2260: 
                   2261:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2262:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2263: }
                   2264: 
1.1248    raeburn  2265: sub crsauthor_url {
                   2266:     my ($url) = @_;
                   2267:     if ($url eq '') {
                   2268:         $url = $ENV{'REQUEST_URI'};
                   2269:     }
                   2270:     my ($cnum,$cdom);
                   2271:     if ($env{'request.course.id'}) {
                   2272:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2273:         if ($audom ne '' && $auname ne '') {
                   2274:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2275:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2276:                 $cnum = $auname;
                   2277:                 $cdom = $audom;
                   2278:             }
                   2279:         }
                   2280:     }
                   2281:     return ($cnum,$cdom);
                   2282: }
                   2283: 
                   2284: sub import_crsauthor_form {
1.1400    raeburn  2285:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2286:     return (0) unless ($env{'request.course.id'});
                   2287:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2288:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2289:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2290:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2291:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2292:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2293: 
1.1248    raeburn  2294:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2295:         $is_home = 1;
                   2296:     }
1.1400    raeburn  2297:     $toppath = "/priv/$cdom/$cnum";
                   2298:     my $nonemptydir = 1;
                   2299:     my $js_only;
                   2300:     if ($only) {
                   2301:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2302:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2303:     }
                   2304:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2305:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2306:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2307:     my %lt = &Apache::lonlocal::texthash (
                   2308:         fnam => 'Filename',
                   2309:         dire => 'Directory',
1.1400    raeburn  2310:         se   => 'Select',
1.1248    raeburn  2311:     );
1.1450    raeburn  2312:     $output = '<label>'.$lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2313:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2314:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2315:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2316:     if ($files{'/'}) {
                   2317:         $output .= '<option value="/">/</option>'."\n";
                   2318:     }
1.1400    raeburn  2319:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2320:         next if ($key eq '/');
1.1400    raeburn  2321:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2322:     }
1.1450    raeburn  2323:     $output .= '</select></label><br /><label>'."\n".
1.1402    raeburn  2324:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2325:                '<option value="" selected="selected"></option>'."\n".
1.1450    raeburn  2326:                '</select></label>'."\n".
1.1402    raeburn  2327:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2328:     return ($numdirs,$output);
                   2329: }
                   2330: 
                   2331: sub show_crsfiles_js {
                   2332:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2333:     my $se = &js_escape(&mt('Select'));
                   2334:     my $exclude;
                   2335:     if (ref($excluderef) eq 'HASH') {
                   2336:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2337:     }
                   2338:     my $js = <<"END";
                   2339: 
                   2340: 
1.1402    raeburn  2341:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2342:         var relpath = '';
                   2343:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2344:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2345:             if (currdir == '') {
                   2346:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2347:                     selelem = form.elements[filesel];
                   2348:                     var j, numfiles = selelem.options.length -1;
                   2349:                     if (numfiles >=0) {
                   2350:                         for (j = numfiles; j >= 0; j--) {
                   2351:                             selelem.remove(j);
                   2352:                         }
                   2353:                     }
                   2354:                     if (selelem.options.length == 0) {
                   2355:                         selelem.options[selelem.options.length] = new Option('','');
                   2356:                         selelem.selectedIndex = 0;
1.1248    raeburn  2357:                     }
                   2358:                 }
1.1400    raeburn  2359:                 return;
                   2360:             } else {
                   2361:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2362:             }
                   2363:         }
1.1400    raeburn  2364:         var http = new XMLHttpRequest();
                   2365:         var url = "/adm/courseauthor";
                   2366:         var crsrole = "$env{'request.role'}";
                   2367:         var exclude = '';
                   2368:         if (exc) {
                   2369:             exclude = '$exclude';
                   2370:         }
1.1402    raeburn  2371:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2372:         http.open("POST", url, true);
                   2373:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2374:         http.onreadystatechange = function() {
                   2375:             if (http.readyState == 4 && http.status == 200) {
                   2376:                 var data = JSON.parse(http.responseText);
                   2377:                 var selelem;
                   2378:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2379:                     if (Array.isArray(data.dirs)) {
                   2380:                         selelem = form.elements[dirsel];
                   2381:                         var i, numdirs = selelem.options.length -1;
                   2382:                         if (numdirs >=0) {
                   2383:                             for (i = numdirs; i >= 0; i--) {
                   2384:                                 selelem.remove(i);
                   2385:                             }
                   2386:                         }
                   2387:                         var len = data.dirs.length;
                   2388:                         if (len) {
1.1402    raeburn  2389:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2390:                             var j;
                   2391:                             for (j = 0; j < len; j++) {
                   2392:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2393:                             }
                   2394:                             selelem.selectedIndex = 0;
                   2395:                         }
                   2396:                         if (!setfile) {
                   2397:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2398:                                 selelem = form.elements[filesel];
                   2399:                                 var j, numfiles = selelem.options.length -1;
                   2400:                                 if (numfiles >=0) {
                   2401:                                     for (j = numfiles; j >= 0; j--) {
                   2402:                                         selelem.remove(j);
                   2403:                                     }
                   2404:                                 }
                   2405:                                 if (selelem.options.length == 0) {
                   2406:                                     selelem.options[selelem.options.length] = new Option('','');
                   2407:                                     selelem.selectedIndex = 0;
                   2408:                                 }
                   2409:                             }
                   2410:                         }
                   2411:                     }
                   2412:                 }
                   2413:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2414:                     selelem = form.elements[filesel];
                   2415:                     var i, numfiles = selelem.options.length -1;
                   2416:                     if (numfiles >=0) {
                   2417:                         for (i = numfiles; i >= 0; i--) {
                   2418:                             selelem.remove(i);
                   2419:                         }
                   2420:                     }
                   2421:                     var x;
                   2422:                     for (x in data.files) {
                   2423:                         if (Array.isArray(data.files[x])) {
                   2424:                             if (data.files[x].length > 1) {
                   2425:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2426:                             }
                   2427:                             var len = data.files[x].length;
                   2428:                             if (len) {
                   2429:                                 var k;
                   2430:                                 for (k = 0; k < len; k++) {
                   2431:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2432:                                 }
                   2433:                                 selelem.selectedIndex = 0;
                   2434:                             }
                   2435:                         }
                   2436:                     }
                   2437:                     if (selelem.options.length == 0) {
                   2438:                         selelem.options[selelem.options.length] = new Option('','');
                   2439:                         selelem.selectedIndex = 0;
                   2440:                     }
1.1248    raeburn  2441:                 }
                   2442:             }
                   2443:         }
1.1400    raeburn  2444:         http.send(params);
1.1248    raeburn  2445:     }
1.1400    raeburn  2446: END
1.1248    raeburn  2447: }
                   2448: 
1.1426    raeburn  2449: sub crsauthor_rights {
                   2450:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2451:     my $sourcerights = "$path/$rightsfile";
                   2452:     my $now = time;
                   2453:     if (!-e $sourcerights) {
                   2454:         my $cid = $cdom.'_'.$cnum;
                   2455:         if (!-e "$docroot/priv/$cdom") {
                   2456:             mkdir("$docroot/priv/$cdom",0755);
                   2457:         }
                   2458:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2459:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2460:         }
                   2461:         if (open(my $fh,">$sourcerights")) {
                   2462:             print $fh <<END;
                   2463: <accessrule effect="deny" realm="" type="course" role="" />
                   2464: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2465: END
                   2466:             close($fh);
                   2467:         }
                   2468:     }
                   2469:     if (!-e "$sourcerights.meta") {
                   2470:         if (open(my $fh,">$sourcerights.meta")) {
                   2471:             my $author=$env{'environment.firstname'}.' '.
                   2472:                        $env{'environment.middlename'}.' '.
                   2473:                        $env{'environment.lastname'}.' '.
                   2474:                        $env{'environment.generation'};
                   2475:             $author =~ s/\s+$//;
                   2476:             print $fh <<"END";
                   2477: 
                   2478: <abstract></abstract>
                   2479: <author>$author</author>
                   2480: <authorspace>$cnum:$cdom</authorspace>
                   2481: <copyright>private</copyright>
                   2482: <creationdate>$now</creationdate>
                   2483: <customdistributionfile></customdistributionfile>
                   2484: <dependencies></dependencies>
                   2485: <domain>$cdom</domain>
                   2486: <highestgradelevel>0</highestgradelevel>
                   2487: <keywords></keywords>
1.1445    raeburn  2488: <language>notset</language>
1.1426    raeburn  2489: <lastrevisiondate>$now</lastrevisiondate>
                   2490: <lowestgradelevel>0</lowestgradelevel>
                   2491: <mime>rights</mime>
                   2492: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2493: <notes></notes>
                   2494: <obsolete></obsolete>
                   2495: <obsoletereplacement></obsoletereplacement>
                   2496: <owner>$cnum:$cdom</owner>
                   2497: <rule>deny:::course,allow:$cid::course</rule>
                   2498: <sourceavail></sourceavail>
                   2499: <standards></standards>
                   2500: <subject></subject>
                   2501: <title>Course Authoring Rights</title>
                   2502: END
                   2503:             close($fh);
                   2504:         }
                   2505:     }
                   2506:     return;
                   2507: }
                   2508: 
1.565     albertel 2509: =pod
                   2510: 
1.1420    raeburn  2511: =item * &iframe_wrapper_headjs()
                   2512: 
1.1425    raeburn  2513: emits javascript containing two global vars to facilitate handling of resizing
                   2514: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2515: with standard LON-CAPA menus.
                   2516: 
                   2517: =cut
                   2518: 
1.1420    raeburn  2519: #
                   2520: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2521: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2522: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2523: # do not obscure the Functions menu.
                   2524: #
                   2525: 
                   2526: sub iframe_wrapper_headjs {
                   2527:     return <<"ENDJS";
                   2528: <script type="text/javascript">
                   2529: // <![CDATA[
                   2530: var LCnotready = 0;
                   2531: var LCresizedef = 0;
                   2532: // ]]>
                   2533: </script>
                   2534: 
                   2535: ENDJS
                   2536: 
                   2537: }
                   2538: 
                   2539: =pod
                   2540: 
                   2541: =item * &iframe_wrapper_resizejs()
                   2542: 
1.1425    raeburn  2543: emits javascript used to handle resizing for a page containing
                   2544: an iframe, to ensure that the iframe does not obscure any
                   2545: standard LON-CAPA menu items.
                   2546: 
                   2547: =back
                   2548: 
                   2549: =cut
                   2550: 
1.1420    raeburn  2551: #
                   2552: # jQuery to use when iframe is in use and a page resize occurs.
                   2553: # This script will ensure that the iframe does not obscure any
                   2554: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2555: # breadcrumbs and Functions menus. Expects javascript from
                   2556: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2557: # e.g., by inclusion in second arg passed to &start_page().
                   2558: #
                   2559: 
                   2560: sub iframe_wrapper_resizejs {
                   2561:     my $offset = 5;
                   2562:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2563:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2564:         $offset = 0;
                   2565:     }
                   2566:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2567:     \$(document).ready( function() {
                   2568:         \$(window).unbind('resize').resize(function(){
                   2569:             var header = null;
                   2570:             var offset = $offset;
                   2571:             var height = 0;
                   2572:             var hdrtop = 0;
1.1421    raeburn  2573:             if (\$('div.LC_menus_content:first').length) {
                   2574:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2575:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2576:                     offset = 12;
1.1421    raeburn  2577:                 }
                   2578:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2579:                 header = \$('div.LC_head_subbox:first');
                   2580:                 offset = 9;
                   2581:             } else {
                   2582:                 if (\$('#LC_breadcrumbs').length) {
                   2583:                     header = \$('#LC_breadcrumbs');
                   2584:                 }
                   2585:             }
                   2586:             if (header != null && header.length) {
                   2587:                 height = header.height();
                   2588:                 hdrtop = header.position().top;
                   2589:             }
                   2590:             var pos = height + hdrtop + offset;
                   2591:             \$('.LC_iframecontainer').css('top', pos);
                   2592:         });
                   2593:         LCresizedef = 1;
                   2594:         if (LCnotready == 1) {
                   2595:             LCnotready = 0;
                   2596:             \$(window).trigger('resize');
                   2597:         }
                   2598:     });
                   2599:     window.onload = function(){
                   2600:          if (LCresizedef) {
                   2601:              LCnotready = 0;
                   2602:              \$(window).trigger('resize');
                   2603:          } else {
                   2604:              LCnotready = 1;
                   2605:          }
                   2606:     };
                   2607: SCRIPT
                   2608: 
                   2609: }
                   2610: 
                   2611: =pod
                   2612: 
1.256     matthew  2613: =head1 Excel and CSV file utility routines
                   2614: 
                   2615: =cut
                   2616: 
                   2617: ###############################################################
                   2618: ###############################################################
                   2619: 
                   2620: =pod
                   2621: 
1.1162    raeburn  2622: =over 4
                   2623: 
1.648     raeburn  2624: =item * &csv_translate($text) 
1.37      matthew  2625: 
1.185     www      2626: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2627: format.
                   2628: 
                   2629: =cut
                   2630: 
1.180     matthew  2631: ###############################################################
                   2632: ###############################################################
1.37      matthew  2633: sub csv_translate {
                   2634:     my $text = shift;
                   2635:     $text =~ s/\"/\"\"/g;
1.209     albertel 2636:     $text =~ s/\n/ /g;
1.37      matthew  2637:     return $text;
                   2638: }
1.180     matthew  2639: 
                   2640: ###############################################################
                   2641: ###############################################################
                   2642: 
                   2643: =pod
                   2644: 
1.648     raeburn  2645: =item * &define_excel_formats()
1.180     matthew  2646: 
                   2647: Define some commonly used Excel cell formats.
                   2648: 
                   2649: Currently supported formats:
                   2650: 
                   2651: =over 4
                   2652: 
                   2653: =item header
                   2654: 
                   2655: =item bold
                   2656: 
                   2657: =item h1
                   2658: 
                   2659: =item h2
                   2660: 
                   2661: =item h3
                   2662: 
1.256     matthew  2663: =item h4
                   2664: 
                   2665: =item i
                   2666: 
1.180     matthew  2667: =item date
                   2668: 
                   2669: =back
                   2670: 
                   2671: Inputs: $workbook
                   2672: 
                   2673: Returns: $format, a hash reference.
                   2674: 
1.1057    foxr     2675: 
1.180     matthew  2676: =cut
                   2677: 
                   2678: ###############################################################
                   2679: ###############################################################
                   2680: sub define_excel_formats {
                   2681:     my ($workbook) = @_;
                   2682:     my $format;
                   2683:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2684:                                                 bottom    => 1,
                   2685:                                                 align     => 'center');
                   2686:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2687:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2688:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2689:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2690:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2691:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2692:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2693:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2694:     return $format;
                   2695: }
                   2696: 
                   2697: ###############################################################
                   2698: ###############################################################
1.113     bowersj2 2699: 
                   2700: =pod
                   2701: 
1.648     raeburn  2702: =item * &create_workbook()
1.255     matthew  2703: 
                   2704: Create an Excel worksheet.  If it fails, output message on the
                   2705: request object and return undefs.
                   2706: 
                   2707: Inputs: Apache request object
                   2708: 
                   2709: Returns (undef) on failure, 
                   2710:     Excel worksheet object, scalar with filename, and formats 
                   2711:     from &Apache::loncommon::define_excel_formats on success
                   2712: 
                   2713: =cut
                   2714: 
                   2715: ###############################################################
                   2716: ###############################################################
                   2717: sub create_workbook {
                   2718:     my ($r) = @_;
                   2719:         #
                   2720:     # Create the excel spreadsheet
                   2721:     my $filename = '/prtspool/'.
1.258     albertel 2722:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2723:         time.'_'.rand(1000000000).'.xls';
                   2724:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2725:     if (! defined($workbook)) {
                   2726:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2727:         $r->print(
                   2728:             '<p class="LC_error">'
                   2729:            .&mt('Problems occurred in creating the new Excel file.')
                   2730:            .' '.&mt('This error has been logged.')
                   2731:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2732:            .'</p>'
                   2733:         );
1.255     matthew  2734:         return (undef);
                   2735:     }
                   2736:     #
1.1014    foxr     2737:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2738:     #
                   2739:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2740:     return ($workbook,$filename,$format);
                   2741: }
                   2742: 
                   2743: ###############################################################
                   2744: ###############################################################
                   2745: 
                   2746: =pod
                   2747: 
1.648     raeburn  2748: =item * &create_text_file()
1.113     bowersj2 2749: 
1.542     raeburn  2750: Create a file to write to and eventually make available to the user.
1.256     matthew  2751: If file creation fails, outputs an error message on the request object and 
                   2752: return undefs.
1.113     bowersj2 2753: 
1.256     matthew  2754: Inputs: Apache request object, and file suffix
1.113     bowersj2 2755: 
1.256     matthew  2756: Returns (undef) on failure, 
                   2757:     Filehandle and filename on success.
1.113     bowersj2 2758: 
                   2759: =cut
                   2760: 
1.256     matthew  2761: ###############################################################
                   2762: ###############################################################
                   2763: sub create_text_file {
                   2764:     my ($r,$suffix) = @_;
                   2765:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2766:     my $fh;
                   2767:     my $filename = '/prtspool/'.
1.258     albertel 2768:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2769:         time.'_'.rand(1000000000).'.'.$suffix;
                   2770:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2771:     if (! defined($fh)) {
                   2772:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2773:         $r->print(
                   2774:             '<p class="LC_error">'
                   2775:            .&mt('Problems occurred in creating the output file.')
                   2776:            .' '.&mt('This error has been logged.')
                   2777:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2778:            .'</p>'
                   2779:         );
1.113     bowersj2 2780:     }
1.256     matthew  2781:     return ($fh,$filename)
1.113     bowersj2 2782: }
                   2783: 
                   2784: 
1.256     matthew  2785: =pod 
1.113     bowersj2 2786: 
                   2787: =back
                   2788: 
                   2789: =cut
1.37      matthew  2790: 
                   2791: ###############################################################
1.33      matthew  2792: ##        Home server <option> list generating code          ##
                   2793: ###############################################################
1.35      matthew  2794: 
1.169     www      2795: # ------------------------------------------
                   2796: 
                   2797: sub domain_select {
1.1289    raeburn  2798:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2799:     my @possdoms;
                   2800:     if (ref($incdoms) eq 'ARRAY') {
                   2801:         @possdoms = @{$incdoms};
                   2802:     } else {
                   2803:         @possdoms = &Apache::lonnet::all_domains();
                   2804:     }
                   2805: 
1.169     www      2806:     my %domains=map { 
1.514     albertel 2807: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2808:     } @possdoms;
                   2809: 
                   2810:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2811:         foreach my $dom (@{$excdoms}) {
                   2812:             delete($domains{$dom});
                   2813:         }
                   2814:     }
                   2815: 
1.169     www      2816:     if ($multiple) {
                   2817: 	$domains{''}=&mt('Any domain');
1.550     albertel 2818: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2819: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2820:     } else {
1.550     albertel 2821: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2822: 	return &select_form($name,$value,\%domains);
1.169     www      2823:     }
                   2824: }
                   2825: 
1.282     albertel 2826: #-------------------------------------------
                   2827: 
                   2828: =pod
                   2829: 
1.519     raeburn  2830: =head1 Routines for form select boxes
                   2831: 
                   2832: =over 4
                   2833: 
1.648     raeburn  2834: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2835: 
                   2836: Returns a string containing a <select> element int multiple mode
                   2837: 
                   2838: 
                   2839: Args:
                   2840:   $name - name of the <select> element
1.506     raeburn  2841:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2842:   $size - number of rows long the select element is
1.283     albertel 2843:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2844:           (shown text should already have been &mt())
1.506     raeburn  2845:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2846: 
1.282     albertel 2847: =cut
                   2848: 
                   2849: #-------------------------------------------
1.169     www      2850: sub multiple_select_form {
1.284     albertel 2851:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2852:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2853:     my $output='';
1.191     matthew  2854:     if (! defined($size)) {
                   2855:         $size = 4;
1.283     albertel 2856:         if (scalar(keys(%$hash))<4) {
                   2857:             $size = scalar(keys(%$hash));
1.191     matthew  2858:         }
                   2859:     }
1.734     bisitz   2860:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2861:     my @order;
1.506     raeburn  2862:     if (ref($order) eq 'ARRAY')  {
                   2863:         @order = @{$order};
                   2864:     } else {
                   2865:         @order = sort(keys(%$hash));
1.501     banghart 2866:     }
                   2867:     if (exists($$hash{'select_form_order'})) {
                   2868:         @order = @{$$hash{'select_form_order'}};
                   2869:     }
                   2870:         
1.284     albertel 2871:     foreach my $key (@order) {
1.356     albertel 2872:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2873:         $output.='selected="selected" ' if ($selected{$key});
                   2874:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2875:     }
                   2876:     $output.="</select>\n";
                   2877:     return $output;
                   2878: }
                   2879: 
1.88      www      2880: #-------------------------------------------
                   2881: 
                   2882: =pod
                   2883: 
1.1254    raeburn  2884: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2885: 
                   2886: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2887: allow a user to select options from a ref to a hash containing:
                   2888: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2889: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2890: An optional arg -- $readonly -- if true will cause the select form
                   2891: to be disabled, e.g., for the case where an instructor has a section-
                   2892: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2893: 
1.88      www      2894: See lonrights.pm for an example invocation and use.
                   2895: 
                   2896: =cut
                   2897: 
                   2898: #-------------------------------------------
                   2899: sub select_form {
1.1228    raeburn  2900:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2901:     return unless (ref($hashref) eq 'HASH');
                   2902:     if ($onchange) {
                   2903:         $onchange = ' onchange="'.$onchange.'"';
                   2904:     }
1.1228    raeburn  2905:     my $disabled;
                   2906:     if ($readonly) {
                   2907:         $disabled = ' disabled="disabled"';
                   2908:     }
                   2909:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2910:     my @keys;
1.970     raeburn  2911:     if (exists($hashref->{'select_form_order'})) {
                   2912: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2913:     } else {
1.970     raeburn  2914: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2915:     }
1.356     albertel 2916:     foreach my $key (@keys) {
                   2917:         $selectform.=
                   2918: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2919:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2920:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2921:     }
                   2922:     $selectform.="</select>";
                   2923:     return $selectform;
                   2924: }
                   2925: 
1.475     www      2926: # For display filters
                   2927: 
                   2928: sub display_filter {
1.1074    raeburn  2929:     my ($context) = @_;
1.475     www      2930:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2931:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2932:     my $phraseinput = 'hidden';
                   2933:     my $includeinput = 'hidden';
                   2934:     my ($checked,$includetypestext);
                   2935:     if ($env{'form.displayfilter'} eq 'containing') {
                   2936:         $phraseinput = 'text'; 
                   2937:         if ($context eq 'parmslog') {
                   2938:             $includeinput = 'checkbox';
                   2939:             if ($env{'form.includetypes'}) {
                   2940:                 $checked = ' checked="checked"';
                   2941:             }
                   2942:             $includetypestext = &mt('Include parameter types');
                   2943:         }
                   2944:     } else {
                   2945:         $includetypestext = '&nbsp;';
                   2946:     }
                   2947:     my ($additional,$secondid,$thirdid);
                   2948:     if ($context eq 'parmslog') {
                   2949:         $additional = 
                   2950:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2951:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2952:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2953:             '</label>';
                   2954:         $secondid = 'includetypes';
                   2955:         $thirdid = 'includetypestext';
                   2956:     }
                   2957:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2958:                                                     '$secondid','$thirdid')";
                   2959:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2960: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2961: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2962: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2963:            &mt('Filter: [_1]',
1.477     www      2964: 	   &select_form($env{'form.displayfilter'},
                   2965: 			'displayfilter',
1.970     raeburn  2966: 			{'currentfolder' => 'Current folder/page',
1.477     www      2967: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2968: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2969: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2970:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2971:                          '" />'.$additional;
                   2972: }
                   2973: 
                   2974: sub display_filter_js {
                   2975:     my $includetext = &mt('Include parameter types');
                   2976:     return <<"ENDJS";
                   2977:   
                   2978: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2979:     var firstType = 'hidden';
                   2980:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2981:         firstType = 'text';
                   2982:     }
                   2983:     firstObject = document.getElementById(firstid);
                   2984:     if (typeof(firstObject) == 'object') {
                   2985:         if (firstObject.type != firstType) {
                   2986:             changeInputType(firstObject,firstType);
                   2987:         }
                   2988:     }
                   2989:     if (context == 'parmslog') {
                   2990:         var secondType = 'hidden';
                   2991:         if (firstType == 'text') {
                   2992:             secondType = 'checkbox';
                   2993:         }
                   2994:         secondObject = document.getElementById(secondid);  
                   2995:         if (typeof(secondObject) == 'object') {
                   2996:             if (secondObject.type != secondType) {
                   2997:                 changeInputType(secondObject,secondType);
                   2998:             }
                   2999:         }
                   3000:         var textItem = document.getElementById(thirdid);
                   3001:         var currtext = textItem.innerHTML;
                   3002:         var newtext;
                   3003:         if (firstType == 'text') {
                   3004:             newtext = '$includetext';
                   3005:         } else {
                   3006:             newtext = '&nbsp;';
                   3007:         }
                   3008:         if (currtext != newtext) {
                   3009:             textItem.innerHTML = newtext;
                   3010:         }
                   3011:     }
                   3012:     return;
                   3013: }
                   3014: 
                   3015: function changeInputType(oldObject,newType) {
                   3016:     var newObject = document.createElement('input');
                   3017:     newObject.type = newType;
                   3018:     if (oldObject.size) {
                   3019:         newObject.size = oldObject.size;
                   3020:     }
                   3021:     if (oldObject.value) {
                   3022:         newObject.value = oldObject.value;
                   3023:     }
                   3024:     if (oldObject.name) {
                   3025:         newObject.name = oldObject.name;
                   3026:     }
                   3027:     if (oldObject.id) {
                   3028:         newObject.id = oldObject.id;
                   3029:     }
                   3030:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3031:     return;
                   3032: }
                   3033: 
                   3034: ENDJS
1.475     www      3035: }
                   3036: 
1.167     www      3037: sub gradeleveldescription {
                   3038:     my $gradelevel=shift;
                   3039:     my %gradelevels=(0 => 'Not specified',
                   3040: 		     1 => 'Grade 1',
                   3041: 		     2 => 'Grade 2',
                   3042: 		     3 => 'Grade 3',
                   3043: 		     4 => 'Grade 4',
                   3044: 		     5 => 'Grade 5',
                   3045: 		     6 => 'Grade 6',
                   3046: 		     7 => 'Grade 7',
                   3047: 		     8 => 'Grade 8',
                   3048: 		     9 => 'Grade 9',
                   3049: 		     10 => 'Grade 10',
                   3050: 		     11 => 'Grade 11',
                   3051: 		     12 => 'Grade 12',
                   3052: 		     13 => 'Grade 13',
                   3053: 		     14 => '100 Level',
                   3054: 		     15 => '200 Level',
                   3055: 		     16 => '300 Level',
                   3056: 		     17 => '400 Level',
                   3057: 		     18 => 'Graduate Level');
                   3058:     return &mt($gradelevels{$gradelevel});
                   3059: }
                   3060: 
1.163     www      3061: sub select_level_form {
                   3062:     my ($deflevel,$name)=@_;
                   3063:     unless ($deflevel) { $deflevel=0; }
1.167     www      3064:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   3065:     for (my $i=0; $i<=18; $i++) {
                   3066:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3067:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3068:                 ">".&gradeleveldescription($i)."</option>\n";
                   3069:     }
                   3070:     $selectform.="</select>";
                   3071:     return $selectform;
1.163     www      3072: }
1.167     www      3073: 
1.35      matthew  3074: #-------------------------------------------
                   3075: 
1.45      matthew  3076: =pod
                   3077: 
1.1256    raeburn  3078: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  3079: 
                   3080: Returns a string containing a <select name='$name' size='1'> form to 
                   3081: allow a user to select the domain to preform an operation in.  
                   3082: See loncreateuser.pm for an example invocation and use.
                   3083: 
1.90      www      3084: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3085: selected");
                   3086: 
1.743     raeburn  3087: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3088: 
1.910     raeburn  3089: 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.
                   3090: 
1.1121    raeburn  3091: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3092: 
                   3093: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3094: 
1.1256    raeburn  3095: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3096: 
1.35      matthew  3097: =cut
                   3098: 
                   3099: #-------------------------------------------
1.34      matthew  3100: sub select_dom_form {
1.1256    raeburn  3101:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  3102:     if ($onchange) {
1.874     raeburn  3103:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3104:     }
1.1256    raeburn  3105:     if ($disabled) {
                   3106:         $disabled = ' disabled="disabled"';
                   3107:     }
1.1121    raeburn  3108:     my (@domains,%exclude);
1.910     raeburn  3109:     if (ref($incdoms) eq 'ARRAY') {
                   3110:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3111:     } else {
                   3112:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3113:     }
1.90      www      3114:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3115:     if (ref($excdoms) eq 'ARRAY') {
                   3116:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3117:     }
1.1256    raeburn  3118:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 3119:     foreach my $dom (@domains) {
1.1121    raeburn  3120:         next if ($exclude{$dom});
1.356     albertel 3121:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3122:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3123:         if ($showdomdesc) {
                   3124:             if ($dom ne '') {
                   3125:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3126:                 if ($domdesc ne '') {
                   3127:                     $selectdomain .= ' ('.$domdesc.')';
                   3128:                 }
                   3129:             } 
                   3130:         }
                   3131:         $selectdomain .= "</option>\n";
1.34      matthew  3132:     }
                   3133:     $selectdomain.="</select>";
                   3134:     return $selectdomain;
                   3135: }
                   3136: 
1.35      matthew  3137: #-------------------------------------------
                   3138: 
1.45      matthew  3139: =pod
                   3140: 
1.648     raeburn  3141: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3142: 
1.586     raeburn  3143: input: 4 arguments (two required, two optional) - 
                   3144:     $domain - domain of new user
                   3145:     $name - name of form element
                   3146:     $default - Value of 'default' causes a default item to be first 
                   3147:                             option, and selected by default. 
                   3148:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3149:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3150: output: returns 2 items: 
1.586     raeburn  3151: (a) form element which contains either:
                   3152:    (i) <select name="$name">
                   3153:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3154:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3155:        </select>
                   3156:        form item if there are multiple library servers in $domain, or
                   3157:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3158:        if there is only one library server in $domain.
                   3159: 
                   3160: (b) number of library servers found.
                   3161: 
                   3162: See loncreateuser.pm for example of use.
1.35      matthew  3163: 
                   3164: =cut
                   3165: 
                   3166: #-------------------------------------------
1.586     raeburn  3167: sub home_server_form_item {
                   3168:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3169:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3170:     my $result;
                   3171:     my $numlib = keys(%servers);
                   3172:     if ($numlib > 1) {
                   3173:         $result .= '<select name="'.$name.'" />'."\n";
                   3174:         if ($default) {
1.804     bisitz   3175:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3176:                        '</option>'."\n";
                   3177:         }
                   3178:         foreach my $hostid (sort(keys(%servers))) {
                   3179:             $result.= '<option value="'.$hostid.'">'.
                   3180: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3181:         }
                   3182:         $result .= '</select>'."\n";
                   3183:     } elsif ($numlib == 1) {
                   3184:         my $hostid;
                   3185:         foreach my $item (keys(%servers)) {
                   3186:             $hostid = $item;
                   3187:         }
                   3188:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3189:                    $hostid.'" />';
                   3190:                    if (!$hide) {
                   3191:                        $result .= $hostid.' '.$servers{$hostid};
                   3192:                    }
                   3193:                    $result .= "\n";
                   3194:     } elsif ($default) {
                   3195:         $result .= '<input type="hidden" name="'.$name.
                   3196:                    '" value="default" />';
                   3197:                    if (!$hide) {
                   3198:                        $result .= &mt('default');
                   3199:                    }
                   3200:                    $result .= "\n";
1.33      matthew  3201:     }
1.586     raeburn  3202:     return ($result,$numlib);
1.33      matthew  3203: }
1.112     bowersj2 3204: 
                   3205: =pod
                   3206: 
1.534     albertel 3207: =back 
                   3208: 
1.112     bowersj2 3209: =cut
1.87      matthew  3210: 
                   3211: ###############################################################
1.112     bowersj2 3212: ##                  Decoding User Agent                      ##
1.87      matthew  3213: ###############################################################
                   3214: 
                   3215: =pod
                   3216: 
1.112     bowersj2 3217: =head1 Decoding the User Agent
                   3218: 
                   3219: =over 4
                   3220: 
                   3221: =item * &decode_user_agent()
1.87      matthew  3222: 
                   3223: Inputs: $r
                   3224: 
                   3225: Outputs:
                   3226: 
                   3227: =over 4
                   3228: 
1.112     bowersj2 3229: =item * $httpbrowser
1.87      matthew  3230: 
1.112     bowersj2 3231: =item * $clientbrowser
1.87      matthew  3232: 
1.112     bowersj2 3233: =item * $clientversion
1.87      matthew  3234: 
1.112     bowersj2 3235: =item * $clientmathml
1.87      matthew  3236: 
1.112     bowersj2 3237: =item * $clientunicode
1.87      matthew  3238: 
1.112     bowersj2 3239: =item * $clientos
1.87      matthew  3240: 
1.1137    raeburn  3241: =item * $clientmobile
                   3242: 
1.1141    raeburn  3243: =item * $clientinfo
                   3244: 
1.1194    raeburn  3245: =item * $clientosversion
                   3246: 
1.87      matthew  3247: =back
                   3248: 
1.157     matthew  3249: =back 
                   3250: 
1.87      matthew  3251: =cut
                   3252: 
                   3253: ###############################################################
                   3254: ###############################################################
                   3255: sub decode_user_agent {
1.247     albertel 3256:     my ($r)=@_;
1.87      matthew  3257:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3258:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3259:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3260:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3261:     my $clientbrowser='unknown';
                   3262:     my $clientversion='0';
                   3263:     my $clientmathml='';
                   3264:     my $clientunicode='0';
1.1137    raeburn  3265:     my $clientmobile=0;
1.1194    raeburn  3266:     my $clientosversion='';
1.87      matthew  3267:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3268:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3269: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3270: 	    $clientbrowser=$bname;
                   3271:             $httpbrowser=~/$vreg/i;
                   3272: 	    $clientversion=$1;
                   3273:             $clientmathml=($clientversion>=$minv);
                   3274:             $clientunicode=($clientversion>=$univ);
                   3275: 	}
                   3276:     }
                   3277:     my $clientos='unknown';
1.1141    raeburn  3278:     my $clientinfo;
1.87      matthew  3279:     if (($httpbrowser=~/linux/i) ||
                   3280:         ($httpbrowser=~/unix/i) ||
                   3281:         ($httpbrowser=~/ux/i) ||
                   3282:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3283:     if (($httpbrowser=~/vax/i) ||
                   3284:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3285:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3286:     if (($httpbrowser=~/mac/i) ||
                   3287:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3288:     if ($httpbrowser=~/win/i) {
                   3289:         $clientos='win';
                   3290:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3291:             $clientosversion = $1;
                   3292:         }
                   3293:     }
1.87      matthew  3294:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3295:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3296:         $clientmobile=lc($1);
                   3297:     }
1.1141    raeburn  3298:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3299:         $clientinfo = 'firefox-'.$1;
                   3300:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3301:         $clientinfo = 'chromeframe-'.$1;
                   3302:     }
1.87      matthew  3303:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3304:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3305:             $clientosversion);
1.87      matthew  3306: }
                   3307: 
1.32      matthew  3308: ###############################################################
                   3309: ##    Authentication changing form generation subroutines    ##
                   3310: ###############################################################
                   3311: ##
                   3312: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3313: ## hash, and have reasonable default values.
                   3314: ##
                   3315: ##    formname = the name given in the <form> tag.
1.35      matthew  3316: #-------------------------------------------
                   3317: 
1.45      matthew  3318: =pod
                   3319: 
1.112     bowersj2 3320: =head1 Authentication Routines
                   3321: 
                   3322: =over 4
                   3323: 
1.648     raeburn  3324: =item * &authform_xxxxxx()
1.35      matthew  3325: 
                   3326: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3327: handle some of the conveniences required for authentication forms.  
                   3328: This is not an optimal method, but it works.  
                   3329: 
                   3330: =over 4
                   3331: 
1.112     bowersj2 3332: =item * authform_header
1.35      matthew  3333: 
1.112     bowersj2 3334: =item * authform_authorwarning
1.35      matthew  3335: 
1.112     bowersj2 3336: =item * authform_nochange
1.35      matthew  3337: 
1.112     bowersj2 3338: =item * authform_kerberos
1.35      matthew  3339: 
1.112     bowersj2 3340: =item * authform_internal
1.35      matthew  3341: 
1.112     bowersj2 3342: =item * authform_filesystem
1.35      matthew  3343: 
1.1310    raeburn  3344: =item * authform_lti
                   3345: 
1.35      matthew  3346: =back
                   3347: 
1.648     raeburn  3348: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3349: 
1.35      matthew  3350: =cut
                   3351: 
                   3352: #-------------------------------------------
1.32      matthew  3353: sub authform_header{  
                   3354:     my %in = (
                   3355:         formname => 'cu',
1.80      albertel 3356:         kerb_def_dom => '',
1.32      matthew  3357:         @_,
                   3358:     );
                   3359:     $in{'formname'} = 'document.' . $in{'formname'};
                   3360:     my $result='';
1.80      albertel 3361: 
                   3362: #---------------------------------------------- Code for upper case translation
                   3363:     my $Javascript_toUpperCase;
                   3364:     unless ($in{kerb_def_dom}) {
                   3365:         $Javascript_toUpperCase =<<"END";
                   3366:         switch (choice) {
                   3367:            case 'krb': currentform.elements[choicearg].value =
                   3368:                currentform.elements[choicearg].value.toUpperCase();
                   3369:                break;
                   3370:            default:
                   3371:         }
                   3372: END
                   3373:     } else {
                   3374:         $Javascript_toUpperCase = "";
                   3375:     }
                   3376: 
1.165     raeburn  3377:     my $radioval = "'nochange'";
1.591     raeburn  3378:     if (defined($in{'curr_authtype'})) {
                   3379:         if ($in{'curr_authtype'} ne '') {
                   3380:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3381:         }
1.174     matthew  3382:     }
1.165     raeburn  3383:     my $argfield = 'null';
1.591     raeburn  3384:     if (defined($in{'mode'})) {
1.165     raeburn  3385:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3386:             if (defined($in{'curr_autharg'})) {
                   3387:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3388:                     $argfield = "'$in{'curr_autharg'}'";
                   3389:                 }
                   3390:             }
                   3391:         }
                   3392:     }
                   3393: 
1.32      matthew  3394:     $result.=<<"END";
                   3395: var current = new Object();
1.165     raeburn  3396: current.radiovalue = $radioval;
                   3397: current.argfield = $argfield;
1.32      matthew  3398: 
                   3399: function changed_radio(choice,currentform) {
                   3400:     var choicearg = choice + 'arg';
                   3401:     // If a radio button in changed, we need to change the argfield
                   3402:     if (current.radiovalue != choice) {
                   3403:         current.radiovalue = choice;
                   3404:         if (current.argfield != null) {
                   3405:             currentform.elements[current.argfield].value = '';
                   3406:         }
                   3407:         if (choice == 'nochange') {
                   3408:             current.argfield = null;
                   3409:         } else {
                   3410:             current.argfield = choicearg;
                   3411:             switch(choice) {
                   3412:                 case 'krb': 
                   3413:                     currentform.elements[current.argfield].value = 
                   3414:                         "$in{'kerb_def_dom'}";
                   3415:                 break;
                   3416:               default:
                   3417:                 break;
                   3418:             }
                   3419:         }
                   3420:     }
                   3421:     return;
                   3422: }
1.22      www      3423: 
1.32      matthew  3424: function changed_text(choice,currentform) {
                   3425:     var choicearg = choice + 'arg';
                   3426:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3427:         $Javascript_toUpperCase
1.32      matthew  3428:         // clear old field
                   3429:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3430:             currentform.elements[current.argfield].value = '';
                   3431:         }
                   3432:         current.argfield = choicearg;
                   3433:     }
                   3434:     set_auth_radio_buttons(choice,currentform);
                   3435:     return;
1.20      www      3436: }
1.32      matthew  3437: 
                   3438: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3439:     var numauthchoices = currentform.login.length;
                   3440:     if (typeof numauthchoices  == "undefined") {
                   3441:         return;
                   3442:     } 
1.32      matthew  3443:     var i=0;
1.986     raeburn  3444:     while (i < numauthchoices) {
1.32      matthew  3445:         if (currentform.login[i].value == newvalue) { break; }
                   3446:         i++;
                   3447:     }
1.986     raeburn  3448:     if (i == numauthchoices) {
1.32      matthew  3449:         return;
                   3450:     }
                   3451:     current.radiovalue = newvalue;
                   3452:     currentform.login[i].checked = true;
                   3453:     return;
                   3454: }
                   3455: END
                   3456:     return $result;
                   3457: }
                   3458: 
1.1106    raeburn  3459: sub authform_authorwarning {
1.32      matthew  3460:     my $result='';
1.144     matthew  3461:     $result='<i>'.
                   3462:         &mt('As a general rule, only authors or co-authors should be '.
                   3463:             'filesystem authenticated '.
                   3464:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3465:     return $result;
                   3466: }
                   3467: 
1.1106    raeburn  3468: sub authform_nochange {
1.32      matthew  3469:     my %in = (
                   3470:               formname => 'document.cu',
                   3471:               kerb_def_dom => 'MSU.EDU',
                   3472:               @_,
                   3473:           );
1.1106    raeburn  3474:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3475:     my $result;
1.1104    raeburn  3476:     if (!$authnum) {
1.1105    raeburn  3477:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3478:     } else {
                   3479:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3480:                   '<input type="radio" name="login" value="nochange" '.
                   3481:                   'checked="checked" onclick="'.
1.281     albertel 3482:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3483: 	    '</label>';
1.586     raeburn  3484:     }
1.32      matthew  3485:     return $result;
                   3486: }
                   3487: 
1.591     raeburn  3488: sub authform_kerberos {
1.32      matthew  3489:     my %in = (
                   3490:               formname => 'document.cu',
                   3491:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3492:               kerb_def_auth => 'krb4',
1.32      matthew  3493:               @_,
                   3494:               );
1.586     raeburn  3495:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3496:         $autharg,$jscall,$disabled);
1.1106    raeburn  3497:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3498:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3499:        $check5 = ' checked="checked"';
1.80      albertel 3500:     } else {
1.772     bisitz   3501:        $check4 = ' checked="checked"';
1.80      albertel 3502:     }
1.1259    raeburn  3503:     if ($in{'readonly'}) {
                   3504:         $disabled = ' disabled="disabled"';
                   3505:     }
1.165     raeburn  3506:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3507:     if (defined($in{'curr_authtype'})) {
                   3508:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3509:             $krbcheck = ' checked="checked"';
1.623     raeburn  3510:             if (defined($in{'mode'})) {
                   3511:                 if ($in{'mode'} eq 'modifyuser') {
                   3512:                     $krbcheck = '';
                   3513:                 }
                   3514:             }
1.591     raeburn  3515:             if (defined($in{'curr_kerb_ver'})) {
                   3516:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3517:                     $check5 = ' checked="checked"';
1.591     raeburn  3518:                     $check4 = '';
                   3519:                 } else {
1.772     bisitz   3520:                     $check4 = ' checked="checked"';
1.591     raeburn  3521:                     $check5 = '';
                   3522:                 }
1.586     raeburn  3523:             }
1.591     raeburn  3524:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3525:                 $krbarg = $in{'curr_autharg'};
                   3526:             }
1.586     raeburn  3527:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3528:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3529:                     $result = 
                   3530:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3531:         $in{'curr_autharg'},$krbver);
                   3532:                 } else {
                   3533:                     $result =
                   3534:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3535:                 }
                   3536:                 return $result; 
                   3537:             }
                   3538:         }
                   3539:     } else {
                   3540:         if ($authnum == 1) {
1.784     bisitz   3541:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3542:         }
                   3543:     }
1.586     raeburn  3544:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3545:         return;
1.587     raeburn  3546:     } elsif ($authtype eq '') {
1.591     raeburn  3547:         if (defined($in{'mode'})) {
1.587     raeburn  3548:             if ($in{'mode'} eq 'modifycourse') {
                   3549:                 if ($authnum == 1) {
1.1259    raeburn  3550:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3551:                 }
                   3552:             }
                   3553:         }
1.586     raeburn  3554:     }
                   3555:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3556:     if ($authtype eq '') {
                   3557:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3558:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3559:                     $krbcheck.$disabled.' />';
1.586     raeburn  3560:     }
                   3561:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3562:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3563:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3564:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3565:          $in{'curr_authtype'} eq 'krb4')) {
                   3566:         $result .= &mt
1.144     matthew  3567:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3568:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3569:          '<label>'.$authtype,
1.281     albertel 3570:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3571:              'value="'.$krbarg.'" '.
1.1259    raeburn  3572:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3573:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3574:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3575: 	 '</label>');
1.586     raeburn  3576:     } elsif ($can_assign{'krb4'}) {
                   3577:         $result .= &mt
                   3578:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3579:          '[_3] Version 4 [_4]',
                   3580:          '<label>'.$authtype,
                   3581:          '</label><input type="text" size="10" name="krbarg" '.
                   3582:              'value="'.$krbarg.'" '.
1.1259    raeburn  3583:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3584:          '<label><input type="hidden" name="krbver" value="4" />',
                   3585:          '</label>');
                   3586:     } elsif ($can_assign{'krb5'}) {
                   3587:         $result .= &mt
                   3588:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3589:          '[_3] Version 5 [_4]',
                   3590:          '<label>'.$authtype,
                   3591:          '</label><input type="text" size="10" name="krbarg" '.
                   3592:              'value="'.$krbarg.'" '.
1.1259    raeburn  3593:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3594:          '<label><input type="hidden" name="krbver" value="5" />',
                   3595:          '</label>');
                   3596:     }
1.32      matthew  3597:     return $result;
                   3598: }
                   3599: 
1.1106    raeburn  3600: sub authform_internal {
1.586     raeburn  3601:     my %in = (
1.32      matthew  3602:                 formname => 'document.cu',
                   3603:                 kerb_def_dom => 'MSU.EDU',
                   3604:                 @_,
                   3605:                 );
1.1259    raeburn  3606:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3607:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3608:     if ($in{'readonly'}) {
                   3609:         $disabled = ' disabled="disabled"';
                   3610:     }
1.591     raeburn  3611:     if (defined($in{'curr_authtype'})) {
                   3612:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3613:             if ($can_assign{'int'}) {
1.772     bisitz   3614:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3615:                 if (defined($in{'mode'})) {
                   3616:                     if ($in{'mode'} eq 'modifyuser') {
                   3617:                         $intcheck = '';
                   3618:                     }
                   3619:                 }
1.591     raeburn  3620:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3621:                     $intarg = $in{'curr_autharg'};
                   3622:                 }
                   3623:             } else {
                   3624:                 $result = &mt('Currently internally authenticated.');
                   3625:                 return $result;
1.165     raeburn  3626:             }
                   3627:         }
1.586     raeburn  3628:     } else {
                   3629:         if ($authnum == 1) {
1.784     bisitz   3630:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3631:         }
                   3632:     }
                   3633:     if (!$can_assign{'int'}) {
                   3634:         return;
1.587     raeburn  3635:     } elsif ($authtype eq '') {
1.591     raeburn  3636:         if (defined($in{'mode'})) {
1.587     raeburn  3637:             if ($in{'mode'} eq 'modifycourse') {
                   3638:                 if ($authnum == 1) {
1.1259    raeburn  3639:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3640:                 }
                   3641:             }
                   3642:         }
1.165     raeburn  3643:     }
1.586     raeburn  3644:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3645:     if ($authtype eq '') {
                   3646:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3647:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3648:     }
1.605     bisitz   3649:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3650:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3651:     $result = &mt
1.144     matthew  3652:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3653:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3654:     $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  3655:     return $result;
                   3656: }
                   3657: 
1.1104    raeburn  3658: sub authform_local {
1.32      matthew  3659:     my %in = (
                   3660:               formname => 'document.cu',
                   3661:               kerb_def_dom => 'MSU.EDU',
                   3662:               @_,
                   3663:               );
1.1259    raeburn  3664:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3665:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3666:     if ($in{'readonly'}) {
                   3667:         $disabled = ' disabled="disabled"';
                   3668:     } 
1.591     raeburn  3669:     if (defined($in{'curr_authtype'})) {
                   3670:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3671:             if ($can_assign{'loc'}) {
1.772     bisitz   3672:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3673:                 if (defined($in{'mode'})) {
                   3674:                     if ($in{'mode'} eq 'modifyuser') {
                   3675:                         $loccheck = '';
                   3676:                     }
                   3677:                 }
1.591     raeburn  3678:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3679:                     $locarg = $in{'curr_autharg'};
                   3680:                 }
                   3681:             } else {
                   3682:                 $result = &mt('Currently using local (institutional) authentication.');
                   3683:                 return $result;
1.165     raeburn  3684:             }
                   3685:         }
1.586     raeburn  3686:     } else {
                   3687:         if ($authnum == 1) {
1.784     bisitz   3688:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3689:         }
                   3690:     }
                   3691:     if (!$can_assign{'loc'}) {
                   3692:         return;
1.587     raeburn  3693:     } elsif ($authtype eq '') {
1.591     raeburn  3694:         if (defined($in{'mode'})) {
1.587     raeburn  3695:             if ($in{'mode'} eq 'modifycourse') {
                   3696:                 if ($authnum == 1) {
1.1259    raeburn  3697:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3698:                 }
                   3699:             }
                   3700:         }
1.165     raeburn  3701:     }
1.586     raeburn  3702:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3703:     if ($authtype eq '') {
                   3704:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3705:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3706:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3707:     }
                   3708:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3709:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3710:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3711:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3712:     return $result;
                   3713: }
                   3714: 
1.1106    raeburn  3715: sub authform_filesystem {
1.32      matthew  3716:     my %in = (
                   3717:               formname => 'document.cu',
                   3718:               kerb_def_dom => 'MSU.EDU',
                   3719:               @_,
                   3720:               );
1.1259    raeburn  3721:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3722:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3723:     if ($in{'readonly'}) {
                   3724:         $disabled = ' disabled="disabled"';
                   3725:     }
1.591     raeburn  3726:     if (defined($in{'curr_authtype'})) {
                   3727:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3728:             if ($can_assign{'fsys'}) {
1.772     bisitz   3729:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3730:                 if (defined($in{'mode'})) {
                   3731:                     if ($in{'mode'} eq 'modifyuser') {
                   3732:                         $fsyscheck = '';
                   3733:                     }
                   3734:                 }
1.586     raeburn  3735:             } else {
                   3736:                 $result = &mt('Currently Filesystem Authenticated.');
                   3737:                 return $result;
1.1259    raeburn  3738:             }
1.586     raeburn  3739:         }
                   3740:     } else {
                   3741:         if ($authnum == 1) {
1.784     bisitz   3742:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3743:         }
                   3744:     }
                   3745:     if (!$can_assign{'fsys'}) {
                   3746:         return;
1.587     raeburn  3747:     } elsif ($authtype eq '') {
1.591     raeburn  3748:         if (defined($in{'mode'})) {
1.587     raeburn  3749:             if ($in{'mode'} eq 'modifycourse') {
                   3750:                 if ($authnum == 1) {
1.1259    raeburn  3751:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3752:                 }
                   3753:             }
                   3754:         }
1.586     raeburn  3755:     }
                   3756:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3757:     if ($authtype eq '') {
                   3758:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3759:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3760:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3761:     }
1.1310    raeburn  3762:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3763:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3764:     $result = &mt
1.144     matthew  3765:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3766:          '<label>'.$authtype,'</label>'.$autharg);
                   3767:     return $result;
                   3768: }
                   3769: 
                   3770: sub authform_lti {
                   3771:     my %in = (
                   3772:               formname => 'document.cu',
                   3773:               kerb_def_dom => 'MSU.EDU',
                   3774:               @_,
                   3775:               );
                   3776:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3777:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3778:     if ($in{'readonly'}) {
                   3779:         $disabled = ' disabled="disabled"';
                   3780:     }
                   3781:     if (defined($in{'curr_authtype'})) {
                   3782:         if ($in{'curr_authtype'} eq 'lti') {
                   3783:             if ($can_assign{'lti'}) {
                   3784:                 $lticheck = 'checked="checked" ';
                   3785:                 if (defined($in{'mode'})) {
                   3786:                     if ($in{'mode'} eq 'modifyuser') {
                   3787:                         $lticheck = '';
                   3788:                     }
                   3789:                 }
                   3790:             } else {
                   3791:                 $result = &mt('Currently LTI Authenticated.');
                   3792:                 return $result;
                   3793:             }
                   3794:         }
                   3795:     } else {
                   3796:         if ($authnum == 1) {
                   3797:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3798:         }
                   3799:     }
                   3800:     if (!$can_assign{'lti'}) {
                   3801:         return;
                   3802:     } elsif ($authtype eq '') {
                   3803:         if (defined($in{'mode'})) {
                   3804:             if ($in{'mode'} eq 'modifycourse') {
                   3805:                 if ($authnum == 1) {
                   3806:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3807:                 }
                   3808:             }
                   3809:         }
                   3810:     }
                   3811:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3812:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3813:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3814:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3815:                     $jscall.'"'.$disabled.' />';
                   3816:     }
                   3817:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3818:     if ($authtype) {
                   3819:         $result = &mt('[_1] LTI Authenticated',
                   3820:                       '<label>'.$authtype.'</label>'.$autharg);
                   3821:     } else {
                   3822:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3823:                   $autharg;
                   3824:     }
1.32      matthew  3825:     return $result;
                   3826: }
                   3827: 
1.586     raeburn  3828: sub get_assignable_auth {
                   3829:     my ($dom) = @_;
                   3830:     if ($dom eq '') {
                   3831:         $dom = $env{'request.role.domain'};
                   3832:     }
                   3833:     my %can_assign = (
                   3834:                           krb4 => 1,
                   3835:                           krb5 => 1,
                   3836:                           int  => 1,
                   3837:                           loc  => 1,
1.1310    raeburn  3838:                           lti  => 1,
1.586     raeburn  3839:                      );
                   3840:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3841:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3842:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3843:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3844:             my $context;
                   3845:             if ($env{'request.role'} =~ /^au/) {
                   3846:                 $context = 'author';
1.1259    raeburn  3847:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3848:                 $context = 'domain';
                   3849:             } elsif ($env{'request.course.id'}) {
                   3850:                 $context = 'course';
                   3851:             }
                   3852:             if ($context) {
                   3853:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3854:                    %can_assign = %{$authhash->{$context}}; 
                   3855:                 }
                   3856:             }
                   3857:         }
                   3858:     }
                   3859:     my $authnum = 0;
                   3860:     foreach my $key (keys(%can_assign)) {
                   3861:         if ($can_assign{$key}) {
                   3862:             $authnum ++;
                   3863:         }
                   3864:     }
                   3865:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3866:         $authnum --;
                   3867:     }
                   3868:     return ($authnum,%can_assign);
                   3869: }
                   3870: 
1.1331    raeburn  3871: sub check_passwd_rules {
                   3872:     my ($domain,$plainpass) = @_;
                   3873:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3874:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3875:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3876:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3877:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3878:             if ($passwdconf{'min'} > $min) {
                   3879:                 $min = $passwdconf{'min'};
                   3880:             }
1.1331    raeburn  3881:         }
                   3882:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3883:             $max = $passwdconf{'max'};
                   3884:         }
                   3885:         @chars = @{$passwdconf{'chars'}};
                   3886:     }
                   3887:     if (($min) && (length($plainpass) < $min)) {
                   3888:         push(@brokerule,'min');
                   3889:     }
                   3890:     if (($max) && (length($plainpass) > $max)) {
                   3891:         push(@brokerule,'max');
                   3892:     }
                   3893:     if (@chars) {
                   3894:         my %rules;
                   3895:         map { $rules{$_} = 1; } @chars;
                   3896:         if ($rules{'uc'}) {
                   3897:             unless ($plainpass =~ /[A-Z]/) {
                   3898:                 push(@brokerule,'uc');
                   3899:             }
                   3900:         }
                   3901:         if ($rules{'lc'}) {
1.1332    raeburn  3902:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3903:                 push(@brokerule,'lc');
                   3904:             }
                   3905:         }
                   3906:         if ($rules{'num'}) {
                   3907:             unless ($plainpass =~ /\d/) {
                   3908:                 push(@brokerule,'num');
                   3909:             }
                   3910:         }
                   3911:         if ($rules{'spec'}) {
                   3912:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3913:                 push(@brokerule,'spec');
                   3914:             }
                   3915:         }
                   3916:     }
                   3917:     if (@brokerule) {
                   3918:         my %rulenames = &Apache::lonlocal::texthash(
                   3919:             uc   => 'At least one upper case letter',
                   3920:             lc   => 'At least one lower case letter',
                   3921:             num  => 'At least one number',
                   3922:             spec => 'At least one non-alphanumeric',
                   3923:         );
                   3924:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3925:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3926:         $rulenames{'num'} .= ': 0123456789';
                   3927:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3928:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3929:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3930:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3931:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3932:             if (grep(/^$rule$/,@brokerule)) {
                   3933:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3934:             }
                   3935:         }
                   3936:         $warning .= '</ul>';
                   3937:     }
1.1332    raeburn  3938:     if (wantarray) {
                   3939:         return @brokerule;
                   3940:     }
1.1331    raeburn  3941:     return $warning;
                   3942: }
                   3943: 
1.1376    raeburn  3944: sub passwd_validation_js {
1.1377    raeburn  3945:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3946:     my (%passwdconf,$alertmsg);
                   3947:     if ($context eq 'linkprot') {
                   3948:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3949:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3950:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3951:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3952:             }
                   3953:         }
                   3954:         if ($id eq 'add') {
                   3955:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3956:         } elsif ($id =~ /^\d+$/) {
                   3957:             my $pos = $id+1;
                   3958:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3959:         } else {
                   3960:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3961:         }
1.1434    raeburn  3962:     } elsif ($context eq 'ltitools') {
                   3963:         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3964:         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3965:             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3966:                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3967:             }
                   3968:         }
                   3969:         if ($id eq 'add') {
                   3970:             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3971:         } elsif ($id =~ /^\d+$/) {
                   3972:             my $pos = $id+1;
                   3973:             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3974:         } else {
                   3975:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3976:         }
1.1377    raeburn  3977:     } else {
                   3978:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3979:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3980:     }
1.1376    raeburn  3981:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3982:     $numrules = 0;
                   3983:     $min = $Apache::lonnet::passwdmin;
                   3984:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3985:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3986:             if ($passwdconf{'min'} > $min) {
                   3987:                 $min = $passwdconf{'min'};
                   3988:             }
                   3989:         }
                   3990:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3991:             $max = $passwdconf{'max'};
                   3992:             $numrules ++;
                   3993:         }
                   3994:         @chars = @{$passwdconf{'chars'}};
                   3995:         if (@chars) {
                   3996:             $numrules ++;
                   3997:         }
                   3998:     }
                   3999:     if ($min > 0) {
                   4000:         $numrules ++;
                   4001:     }
                   4002:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   4003:         if ($min) {
                   4004:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   4005:         }
                   4006:         if ($max) {
                   4007:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   4008:         }
                   4009:         my (@charalerts,@charrules);
                   4010:         if (@chars) {
                   4011:             if (grep(/^uc$/,@chars)) {
                   4012:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   4013:                 push(@charrules,'uc');
                   4014:             }
                   4015:             if (grep(/^lc$/,@chars)) {
                   4016:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   4017:                 push(@charrules,'lc');
                   4018:             }
                   4019:             if (grep(/^num$/,@chars)) {
                   4020:                 push(@charalerts,&mt('contain at least one number'));
                   4021:                 push(@charrules,'num');
                   4022:             }
                   4023:             if (grep(/^spec$/,@chars)) {
                   4024:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4025:                 push(@charrules,'spec');
                   4026:             }
                   4027:         }
                   4028:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4029:                     qq|            var currpwval = $currpasswdval;\n|;
                   4030:             if ($min) {
                   4031:                 $intargjs .= qq|
                   4032:             if (currpwval.length < $min) {
                   4033:                 rulesmsg += ' - $alert{min}';
                   4034:             }
                   4035: |;
                   4036:             }
                   4037:             if ($max) {
                   4038:                 $intargjs .= qq|
                   4039:             if (currpwval.length > $max) {
                   4040:                 rulesmsg += ' - $alert{max}';
                   4041:             }
                   4042: |;
                   4043:             }
                   4044:             if (@chars > 0) {
                   4045:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4046:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4047:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4048:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4049:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4050:                 my %rules;
                   4051:                 map { $rules{$_} = 1; } @chars;
                   4052:                 if ($rules{'uc'}) {
                   4053:                     $intargjs .= qq|
                   4054:             var ucRegExp = /[A-Z]/;
                   4055:             if (!ucRegExp.test(currpwval)) {
                   4056:                 brokerules.push('uc');
                   4057:             }
                   4058: |;
                   4059:                 }
                   4060:                 if ($rules{'lc'}) {
                   4061:                     $intargjs .= qq|
                   4062:             var lcRegExp = /[a-z]/;
                   4063:             if (!lcRegExp.test(currpwval)) {
                   4064:                 brokerules.push('lc');
                   4065:             }
                   4066: |;
                   4067:                 }
                   4068:                 if ($rules{'num'}) {
                   4069:                      $intargjs .= qq|
                   4070:             var numRegExp = /[0-9]/;
                   4071:             if (!numRegExp.test(currpwval)) {
                   4072:                 brokerules.push('num');
                   4073:             }
                   4074: |;
                   4075:                 }
                   4076:                 if ($rules{'spec'}) {
                   4077:                      $intargjs .= q|
                   4078:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4079:             if (!specRegExp.test(currpwval)) {
                   4080:                 brokerules.push('spec');
                   4081:             }
                   4082: |;
                   4083:                 }
                   4084:                 $intargjs .= qq|
                   4085:             if (brokerules.length > 0) {
                   4086:                 for (var i=0; i<brokerules.length; i++) {
                   4087:                     for (var j=0; j<charrules.length; j++) {
                   4088:                         if (brokerules[i] == charrules[j]) {
                   4089:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4090:                             break;
                   4091:                         }
                   4092:                     }
                   4093:                 }
                   4094:             }
                   4095: |;
                   4096:             }
                   4097:             $intargjs .= qq|
                   4098:             if (rulesmsg != '') {
                   4099:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4100:                 alert(rulesmsg);
                   4101:                 return false;
                   4102:             }
                   4103: |;
                   4104:     }
                   4105:     return ($numrules,$intargjs);
                   4106: }
                   4107: 
1.80      albertel 4108: ###############################################################
                   4109: ##    Get Kerberos Defaults for Domain                 ##
                   4110: ###############################################################
                   4111: ##
                   4112: ## Returns default kerberos version and an associated argument
                   4113: ## as listed in file domain.tab. If not listed, provides
                   4114: ## appropriate default domain and kerberos version.
                   4115: ##
                   4116: #-------------------------------------------
                   4117: 
                   4118: =pod
                   4119: 
1.648     raeburn  4120: =item * &get_kerberos_defaults()
1.80      albertel 4121: 
                   4122: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4123: version and domain. If not found, it defaults to version 4 and the 
                   4124: domain of the server.
1.80      albertel 4125: 
1.648     raeburn  4126: =over 4
                   4127: 
1.80      albertel 4128: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4129: 
1.648     raeburn  4130: =back
                   4131: 
                   4132: =back
                   4133: 
1.80      albertel 4134: =cut
                   4135: 
                   4136: #-------------------------------------------
                   4137: sub get_kerberos_defaults {
                   4138:     my $domain=shift;
1.641     raeburn  4139:     my ($krbdef,$krbdefdom);
                   4140:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4141:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4142:         $krbdef = $domdefaults{'auth_def'};
                   4143:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4144:     } else {
1.80      albertel 4145:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4146:         my $krbdefdom=$1;
                   4147:         $krbdefdom=~tr/a-z/A-Z/;
                   4148:         $krbdef = "krb4";
                   4149:     }
                   4150:     return ($krbdef,$krbdefdom);
                   4151: }
1.112     bowersj2 4152: 
1.32      matthew  4153: 
1.46      matthew  4154: ###############################################################
                   4155: ##                Thesaurus Functions                        ##
                   4156: ###############################################################
1.20      www      4157: 
1.46      matthew  4158: =pod
1.20      www      4159: 
1.112     bowersj2 4160: =head1 Thesaurus Functions
                   4161: 
                   4162: =over 4
                   4163: 
1.648     raeburn  4164: =item * &initialize_keywords()
1.46      matthew  4165: 
                   4166: Initializes the package variable %Keywords if it is empty.  Uses the
                   4167: package variable $thesaurus_db_file.
                   4168: 
                   4169: =cut
                   4170: 
                   4171: ###################################################
                   4172: 
                   4173: sub initialize_keywords {
                   4174:     return 1 if (scalar keys(%Keywords));
                   4175:     # If we are here, %Keywords is empty, so fill it up
                   4176:     #   Make sure the file we need exists...
                   4177:     if (! -e $thesaurus_db_file) {
                   4178:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4179:                                  " failed because it does not exist");
                   4180:         return 0;
                   4181:     }
                   4182:     #   Set up the hash as a database
                   4183:     my %thesaurus_db;
                   4184:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4185:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4186:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4187:                                  $thesaurus_db_file);
                   4188:         return 0;
                   4189:     } 
                   4190:     #  Get the average number of appearances of a word.
                   4191:     my $avecount = $thesaurus_db{'average.count'};
                   4192:     #  Put keywords (those that appear > average) into %Keywords
                   4193:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4194:         my ($count,undef) = split /:/,$data;
                   4195:         $Keywords{$word}++ if ($count > $avecount);
                   4196:     }
                   4197:     untie %thesaurus_db;
                   4198:     # Remove special values from %Keywords.
1.356     albertel 4199:     foreach my $value ('total.count','average.count') {
                   4200:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4201:   }
1.46      matthew  4202:     return 1;
                   4203: }
                   4204: 
                   4205: ###################################################
                   4206: 
                   4207: =pod
                   4208: 
1.648     raeburn  4209: =item * &keyword($word)
1.46      matthew  4210: 
                   4211: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4212: than the average number of times in the thesaurus database.  Calls 
                   4213: &initialize_keywords
                   4214: 
                   4215: =cut
                   4216: 
                   4217: ###################################################
1.20      www      4218: 
                   4219: sub keyword {
1.46      matthew  4220:     return if (!&initialize_keywords());
                   4221:     my $word=lc(shift());
                   4222:     $word=~s/\W//g;
                   4223:     return exists($Keywords{$word});
1.20      www      4224: }
1.46      matthew  4225: 
                   4226: ###############################################################
                   4227: 
                   4228: =pod 
1.20      www      4229: 
1.648     raeburn  4230: =item * &get_related_words()
1.46      matthew  4231: 
1.160     matthew  4232: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4233: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4234: will be returned.  The order of the words returned is determined by the
                   4235: database which holds them.
                   4236: 
                   4237: Uses global $thesaurus_db_file.
                   4238: 
1.1057    foxr     4239: 
1.46      matthew  4240: =cut
                   4241: 
                   4242: ###############################################################
                   4243: sub get_related_words {
                   4244:     my $keyword = shift;
                   4245:     my %thesaurus_db;
                   4246:     if (! -e $thesaurus_db_file) {
                   4247:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4248:                                  "failed because the file does not exist");
                   4249:         return ();
                   4250:     }
                   4251:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4252:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4253:         return ();
                   4254:     } 
                   4255:     my @Words=();
1.429     www      4256:     my $count=0;
1.46      matthew  4257:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4258: 	# The first element is the number of times
                   4259: 	# the word appears.  We do not need it now.
1.429     www      4260: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4261: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4262: 	my $threshold=$mostfrequentcount/10;
                   4263:         foreach my $possibleword (@RelatedWords) {
                   4264:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4265:             if ($wordcount>$threshold) {
                   4266: 		push(@Words,$word);
                   4267:                 $count++;
                   4268:                 if ($count>10) { last; }
                   4269: 	    }
1.20      www      4270:         }
                   4271:     }
1.46      matthew  4272:     untie %thesaurus_db;
                   4273:     return @Words;
1.14      harris41 4274: }
1.1090    foxr     4275: ###############################################################
                   4276: #
                   4277: #  Spell checking
                   4278: #
                   4279: 
                   4280: =pod
                   4281: 
1.1142    raeburn  4282: =back
                   4283: 
1.1090    foxr     4284: =head1 Spell checking
                   4285: 
                   4286: =over 4
                   4287: 
                   4288: =item * &check_spelling($wordlist $language)
                   4289: 
                   4290: Takes a string containing words and feeds it to an external
                   4291: spellcheck program via a pipeline. Returns a string containing
                   4292: them mis-spelled words.
                   4293: 
                   4294: Parameters:
                   4295: 
                   4296: =over 4
                   4297: 
                   4298: =item - $wordlist
                   4299: 
                   4300: String that will be fed into the spellcheck program.
                   4301: 
                   4302: =item - $language
                   4303: 
                   4304: Language string that specifies the language for which the spell
                   4305: check will be performed.
                   4306: 
                   4307: =back
                   4308: 
                   4309: =back
                   4310: 
                   4311: Note: This sub assumes that aspell is installed.
                   4312: 
                   4313: 
                   4314: =cut
                   4315: 
1.46      matthew  4316: 
1.1090    foxr     4317: sub check_spelling {
                   4318:     my ($wordlist, $language) = @_;
1.1091    foxr     4319:     my @misspellings;
                   4320:     
                   4321:     # Generate the speller and set the langauge.
                   4322:     # if explicitly selected:
1.1090    foxr     4323: 
1.1091    foxr     4324:     my $speller = Text::Aspell->new;
1.1090    foxr     4325:     if ($language) {
1.1091    foxr     4326: 	$speller->set_option('lang', $language);
1.1090    foxr     4327:     }
                   4328: 
1.1091    foxr     4329:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4330: 
1.1091    foxr     4331:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4332: 
1.1091    foxr     4333:     foreach my $word (@words) {
                   4334: 	if(! $speller->check($word)) {
                   4335: 	    push(@misspellings, $word);
1.1090    foxr     4336: 	}
                   4337:     }
1.1091    foxr     4338:     return join(' ', @misspellings);
                   4339:     
1.1090    foxr     4340: }
                   4341: 
1.61      www      4342: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4343: =pod
                   4344: 
1.112     bowersj2 4345: =head1 User Name Functions
                   4346: 
                   4347: =over 4
                   4348: 
1.648     raeburn  4349: =item * &plainname($uname,$udom,$first)
1.81      albertel 4350: 
1.112     bowersj2 4351: Takes a users logon name and returns it as a string in
1.226     albertel 4352: "first middle last generation" form 
                   4353: if $first is set to 'lastname' then it returns it as
                   4354: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4355: 
                   4356: =cut
1.61      www      4357: 
1.295     www      4358: 
1.81      albertel 4359: ###############################################################
1.61      www      4360: sub plainname {
1.226     albertel 4361:     my ($uname,$udom,$first)=@_;
1.537     albertel 4362:     return if (!defined($uname) || !defined($udom));
1.295     www      4363:     my %names=&getnames($uname,$udom);
1.226     albertel 4364:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4365: 					  $names{'middlename'},
                   4366: 					  $names{'lastname'},
                   4367: 					  $names{'generation'},$first);
                   4368:     $name=~s/^\s+//;
1.62      www      4369:     $name=~s/\s+$//;
                   4370:     $name=~s/\s+/ /g;
1.353     albertel 4371:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4372:     return $name;
1.61      www      4373: }
1.66      www      4374: 
                   4375: # -------------------------------------------------------------------- Nickname
1.81      albertel 4376: =pod
                   4377: 
1.648     raeburn  4378: =item * &nickname($uname,$udom)
1.81      albertel 4379: 
                   4380: Gets a users name and returns it as a string as
                   4381: 
                   4382: "&quot;nickname&quot;"
1.66      www      4383: 
1.81      albertel 4384: if the user has a nickname or
                   4385: 
                   4386: "first middle last generation"
                   4387: 
                   4388: if the user does not
                   4389: 
                   4390: =cut
1.66      www      4391: 
                   4392: sub nickname {
                   4393:     my ($uname,$udom)=@_;
1.537     albertel 4394:     return if (!defined($uname) || !defined($udom));
1.295     www      4395:     my %names=&getnames($uname,$udom);
1.68      albertel 4396:     my $name=$names{'nickname'};
1.66      www      4397:     if ($name) {
                   4398:        $name='&quot;'.$name.'&quot;'; 
                   4399:     } else {
                   4400:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4401: 	     $names{'lastname'}.' '.$names{'generation'};
                   4402:        $name=~s/\s+$//;
                   4403:        $name=~s/\s+/ /g;
                   4404:     }
                   4405:     return $name;
                   4406: }
                   4407: 
1.295     www      4408: sub getnames {
                   4409:     my ($uname,$udom)=@_;
1.537     albertel 4410:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4411:     if ($udom eq 'public' && $uname eq 'public') {
                   4412: 	return ('lastname' => &mt('Public'));
                   4413:     }
1.295     www      4414:     my $id=$uname.':'.$udom;
                   4415:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4416:     if ($cached) {
                   4417: 	return %{$names};
                   4418:     } else {
                   4419: 	my %loadnames=&Apache::lonnet::get('environment',
                   4420:                     ['firstname','middlename','lastname','generation','nickname'],
                   4421: 					 $udom,$uname);
                   4422: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4423: 	return %loadnames;
                   4424:     }
                   4425: }
1.61      www      4426: 
1.542     raeburn  4427: # -------------------------------------------------------------------- getemails
1.648     raeburn  4428: 
1.542     raeburn  4429: =pod
                   4430: 
1.648     raeburn  4431: =item * &getemails($uname,$udom)
1.542     raeburn  4432: 
                   4433: Gets a user's email information and returns it as a hash with keys:
                   4434: notification, critnotification, permanentemail
                   4435: 
                   4436: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4437: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4438:  
1.648     raeburn  4439: 
1.542     raeburn  4440: =cut
                   4441: 
1.648     raeburn  4442: 
1.466     albertel 4443: sub getemails {
                   4444:     my ($uname,$udom)=@_;
                   4445:     if ($udom eq 'public' && $uname eq 'public') {
                   4446: 	return;
                   4447:     }
1.467     www      4448:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4449:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4450:     my $id=$uname.':'.$udom;
                   4451:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4452:     if ($cached) {
                   4453: 	return %{$names};
                   4454:     } else {
                   4455: 	my %loadnames=&Apache::lonnet::get('environment',
                   4456:                     			   ['notification','critnotification',
                   4457: 					    'permanentemail'],
                   4458: 					   $udom,$uname);
                   4459: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4460: 	return %loadnames;
                   4461:     }
                   4462: }
                   4463: 
1.551     albertel 4464: sub flush_email_cache {
                   4465:     my ($uname,$udom)=@_;
                   4466:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4467:     if (!$uname) { $uname=$env{'user.name'};   }
                   4468:     return if ($udom eq 'public' && $uname eq 'public');
                   4469:     my $id=$uname.':'.$udom;
                   4470:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4471: }
                   4472: 
1.728     raeburn  4473: # -------------------------------------------------------------------- getlangs
                   4474: 
                   4475: =pod
                   4476: 
                   4477: =item * &getlangs($uname,$udom)
                   4478: 
                   4479: Gets a user's language preference and returns it as a hash with key:
                   4480: language.
                   4481: 
                   4482: =cut
                   4483: 
                   4484: 
                   4485: sub getlangs {
                   4486:     my ($uname,$udom) = @_;
                   4487:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4488:     if (!$uname) { $uname=$env{'user.name'};   }
                   4489:     my $id=$uname.':'.$udom;
                   4490:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4491:     if ($cached) {
                   4492:         return %{$langs};
                   4493:     } else {
                   4494:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4495:                                            $udom,$uname);
                   4496:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4497:         return %loadlangs;
                   4498:     }
                   4499: }
                   4500: 
                   4501: sub flush_langs_cache {
                   4502:     my ($uname,$udom)=@_;
                   4503:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4504:     if (!$uname) { $uname=$env{'user.name'};   }
                   4505:     return if ($udom eq 'public' && $uname eq 'public');
                   4506:     my $id=$uname.':'.$udom;
                   4507:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4508: }
                   4509: 
1.61      www      4510: # ------------------------------------------------------------------ Screenname
1.81      albertel 4511: 
                   4512: =pod
                   4513: 
1.648     raeburn  4514: =item * &screenname($uname,$udom)
1.81      albertel 4515: 
                   4516: Gets a users screenname and returns it as a string
                   4517: 
                   4518: =cut
1.61      www      4519: 
                   4520: sub screenname {
                   4521:     my ($uname,$udom)=@_;
1.258     albertel 4522:     if ($uname eq $env{'user.name'} &&
                   4523: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4524:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4525:     return $names{'screenname'};
1.62      www      4526: }
                   4527: 
1.212     albertel 4528: 
1.802     bisitz   4529: # ------------------------------------------------------------- Confirm Wrapper
                   4530: =pod
                   4531: 
1.1142    raeburn  4532: =item * &confirmwrapper($message)
1.802     bisitz   4533: 
                   4534: Wrap messages about completion of operation in box
                   4535: 
                   4536: =cut
                   4537: 
                   4538: sub confirmwrapper {
                   4539:     my ($message)=@_;
                   4540:     if ($message) {
                   4541:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4542:                .$message."\n"
                   4543:                .'</div>'."\n";
                   4544:     } else {
                   4545:         return $message;
                   4546:     }
                   4547: }
                   4548: 
1.62      www      4549: # ------------------------------------------------------------- Message Wrapper
                   4550: 
                   4551: sub messagewrapper {
1.369     www      4552:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4553:     return 
1.441     albertel 4554:         '<a href="/adm/email?compose=individual&amp;'.
                   4555:         'recname='.$username.'&amp;recdom='.$domain.
                   4556: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4557:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4558: }
1.802     bisitz   4559: 
1.74      www      4560: # --------------------------------------------------------------- Notes Wrapper
                   4561: 
                   4562: sub noteswrapper {
                   4563:     my ($link,$un,$do)=@_;
                   4564:     return 
1.896     amueller 4565: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4566: }
1.802     bisitz   4567: 
1.62      www      4568: # ------------------------------------------------------------- Aboutme Wrapper
                   4569: 
                   4570: sub aboutmewrapper {
1.1070    raeburn  4571:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4572:     if (!defined($username)  && !defined($domain)) {
                   4573:         return;
                   4574:     }
1.1096    raeburn  4575:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4576: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4577: }
                   4578: 
                   4579: # ------------------------------------------------------------ Syllabus Wrapper
                   4580: 
                   4581: sub syllabuswrapper {
1.707     bisitz   4582:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4583:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4584: }
1.14      harris41 4585: 
1.1397    raeburn  4586: # -----------------------------------------------------------------------------
                   4587: 
1.1396    raeburn  4588: sub aboutme_on {
                   4589:     my ($uname,$udom)=@_;
                   4590:     unless ($uname) { $uname=$env{'user.name'}; }
                   4591:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4592:     return if ($udom eq 'public' && $uname eq 'public');
                   4593:     my $hashkey=$uname.':'.$udom;
                   4594:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4595:     if ($cached) {
                   4596:         return $aboutme;
                   4597:     }
                   4598:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4599:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4600:     return $aboutme;
                   4601: }
                   4602: 
                   4603: sub devalidate_aboutme_cache {
                   4604:     my ($uname,$udom)=@_;
                   4605:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4606:     if (!$uname) { $uname=$env{'user.name'};   }
                   4607:     return if ($udom eq 'public' && $uname eq 'public');
                   4608:     my $id=$uname.':'.$udom;
                   4609:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4610: }
                   4611: 
1.208     matthew  4612: sub track_student_link {
1.887     raeburn  4613:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4614:     my $link ="/adm/trackstudent?";
1.208     matthew  4615:     my $title = 'View recent activity';
                   4616:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4617:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4618:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4619:         $title .= ' of this student';
1.268     albertel 4620:     } 
1.208     matthew  4621:     if (defined($target) && $target !~ /^\s*$/) {
                   4622:         $target = qq{target="$target"};
                   4623:     } else {
                   4624:         $target = '';
                   4625:     }
1.268     albertel 4626:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4627:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4628:     $title = &mt($title);
                   4629:     $linktext = &mt($linktext);
1.448     albertel 4630:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4631: 	&help_open_topic('View_recent_activity');
1.208     matthew  4632: }
                   4633: 
1.781     raeburn  4634: sub slot_reservations_link {
                   4635:     my ($linktext,$sname,$sdom,$target) = @_;
                   4636:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4637:     my $title = 'View slot reservation history';
                   4638:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4639:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4640:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4641:         $title .= ' of this student';
                   4642:     }
                   4643:     if (defined($target) && $target !~ /^\s*$/) {
                   4644:         $target = qq{target="$target"};
                   4645:     } else {
                   4646:         $target = '';
                   4647:     }
                   4648:     $title = &mt($title);
                   4649:     $linktext = &mt($linktext);
                   4650:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4651: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4652: 
                   4653: }
                   4654: 
1.508     www      4655: # ===================================================== Display a student photo
                   4656: 
                   4657: 
1.509     albertel 4658: sub student_image_tag {
1.508     www      4659:     my ($domain,$user)=@_;
                   4660:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4661:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4662: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4663:     } else {
                   4664: 	return '';
                   4665:     }
                   4666: }
                   4667: 
1.112     bowersj2 4668: =pod
                   4669: 
                   4670: =back
                   4671: 
                   4672: =head1 Access .tab File Data
                   4673: 
                   4674: =over 4
                   4675: 
1.648     raeburn  4676: =item * &languageids() 
1.112     bowersj2 4677: 
                   4678: returns list of all language ids
                   4679: 
                   4680: =cut
                   4681: 
1.14      harris41 4682: sub languageids {
1.16      harris41 4683:     return sort(keys(%language));
1.14      harris41 4684: }
                   4685: 
1.112     bowersj2 4686: =pod
                   4687: 
1.648     raeburn  4688: =item * &languagedescription() 
1.112     bowersj2 4689: 
                   4690: returns description of a specified language id
                   4691: 
                   4692: =cut
                   4693: 
1.14      harris41 4694: sub languagedescription {
1.125     www      4695:     my $code=shift;
                   4696:     return  ($supported_language{$code}?'* ':'').
                   4697:             $language{$code}.
1.126     www      4698: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4699: }
                   4700: 
1.1048    foxr     4701: =pod
                   4702: 
                   4703: =item * &plainlanguagedescription
                   4704: 
                   4705: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4706: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4707: 
                   4708: =cut
                   4709: 
1.145     www      4710: sub plainlanguagedescription {
                   4711:     my $code=shift;
                   4712:     return $language{$code};
                   4713: }
                   4714: 
1.1048    foxr     4715: =pod
                   4716: 
                   4717: =item * &supportedlanguagecode
                   4718: 
                   4719: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4720: code.
                   4721: 
                   4722: =cut
                   4723: 
1.145     www      4724: sub supportedlanguagecode {
                   4725:     my $code=shift;
                   4726:     return $supported_language{$code};
1.97      www      4727: }
                   4728: 
1.112     bowersj2 4729: =pod
                   4730: 
1.1048    foxr     4731: =item * &latexlanguage()
                   4732: 
                   4733: Given a language key code returns the correspondnig language to use
                   4734: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4735: is no supported hyphenation for the language code.
                   4736: 
                   4737: =cut
                   4738: 
                   4739: sub latexlanguage {
                   4740:     my $code = shift;
                   4741:     return $latex_language{$code};
                   4742: }
                   4743: 
                   4744: =pod
                   4745: 
                   4746: =item * &latexhyphenation()
                   4747: 
                   4748: Same as above but what's supplied is the language as it might be stored
                   4749: in the metadata.
                   4750: 
                   4751: =cut
                   4752: 
                   4753: sub latexhyphenation {
                   4754:     my $key = shift;
                   4755:     return $latex_language_bykey{$key};
                   4756: }
                   4757: 
                   4758: =pod
                   4759: 
1.648     raeburn  4760: =item * &copyrightids() 
1.112     bowersj2 4761: 
                   4762: returns list of all copyrights
                   4763: 
                   4764: =cut
                   4765: 
                   4766: sub copyrightids {
                   4767:     return sort(keys(%cprtag));
                   4768: }
                   4769: 
                   4770: =pod
                   4771: 
1.648     raeburn  4772: =item * &copyrightdescription() 
1.112     bowersj2 4773: 
                   4774: returns description of a specified copyright id
                   4775: 
                   4776: =cut
                   4777: 
                   4778: sub copyrightdescription {
1.166     www      4779:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4780: }
1.197     matthew  4781: 
                   4782: =pod
                   4783: 
1.648     raeburn  4784: =item * &source_copyrightids() 
1.192     taceyjo1 4785: 
                   4786: returns list of all source copyrights
                   4787: 
                   4788: =cut
                   4789: 
                   4790: sub source_copyrightids {
                   4791:     return sort(keys(%scprtag));
                   4792: }
                   4793: 
                   4794: =pod
                   4795: 
1.648     raeburn  4796: =item * &source_copyrightdescription() 
1.192     taceyjo1 4797: 
                   4798: returns description of a specified source copyright id
                   4799: 
                   4800: =cut
                   4801: 
                   4802: sub source_copyrightdescription {
                   4803:     return &mt($scprtag{shift(@_)});
                   4804: }
1.112     bowersj2 4805: 
                   4806: =pod
                   4807: 
1.648     raeburn  4808: =item * &filecategories() 
1.112     bowersj2 4809: 
                   4810: returns list of all file categories
                   4811: 
                   4812: =cut
                   4813: 
                   4814: sub filecategories {
                   4815:     return sort(keys(%category_extensions));
                   4816: }
                   4817: 
                   4818: =pod
                   4819: 
1.648     raeburn  4820: =item * &filecategorytypes() 
1.112     bowersj2 4821: 
                   4822: returns list of file types belonging to a given file
                   4823: category
                   4824: 
                   4825: =cut
                   4826: 
                   4827: sub filecategorytypes {
1.356     albertel 4828:     my ($cat) = @_;
1.1248    raeburn  4829:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4830:         return @{$category_extensions{lc($cat)}};
                   4831:     } else {
                   4832:         return ();
                   4833:     }
1.112     bowersj2 4834: }
                   4835: 
                   4836: =pod
                   4837: 
1.648     raeburn  4838: =item * &fileembstyle() 
1.112     bowersj2 4839: 
                   4840: returns embedding style for a specified file type
                   4841: 
                   4842: =cut
                   4843: 
                   4844: sub fileembstyle {
                   4845:     return $fe{lc(shift(@_))};
1.169     www      4846: }
                   4847: 
1.351     www      4848: sub filemimetype {
                   4849:     return $fm{lc(shift(@_))};
                   4850: }
                   4851: 
1.169     www      4852: 
                   4853: sub filecategoryselect {
                   4854:     my ($name,$value)=@_;
1.189     matthew  4855:     return &select_form($value,$name,
1.970     raeburn  4856:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4857: }
                   4858: 
                   4859: =pod
                   4860: 
1.648     raeburn  4861: =item * &filedescription() 
1.112     bowersj2 4862: 
                   4863: returns description for a specified file type
                   4864: 
                   4865: =cut
                   4866: 
                   4867: sub filedescription {
1.188     matthew  4868:     my $file_description = $fd{lc(shift())};
                   4869:     $file_description =~ s:([\[\]]):~$1:g;
                   4870:     return &mt($file_description);
1.112     bowersj2 4871: }
                   4872: 
                   4873: =pod
                   4874: 
1.648     raeburn  4875: =item * &filedescriptionex() 
1.112     bowersj2 4876: 
                   4877: returns description for a specified file type with
                   4878: extra formatting
                   4879: 
                   4880: =cut
                   4881: 
                   4882: sub filedescriptionex {
                   4883:     my $ex=shift;
1.188     matthew  4884:     my $file_description = $fd{lc($ex)};
                   4885:     $file_description =~ s:([\[\]]):~$1:g;
                   4886:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4887: }
                   4888: 
                   4889: # End of .tab access
                   4890: =pod
                   4891: 
                   4892: =back
                   4893: 
                   4894: =cut
                   4895: 
                   4896: # ------------------------------------------------------------------ File Types
                   4897: sub fileextensions {
                   4898:     return sort(keys(%fe));
                   4899: }
                   4900: 
1.97      www      4901: # ----------------------------------------------------------- Display Languages
                   4902: # returns a hash with all desired display languages
                   4903: #
                   4904: 
                   4905: sub display_languages {
                   4906:     my %languages=();
1.695     raeburn  4907:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4908: 	$languages{$lang}=1;
1.97      www      4909:     }
                   4910:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4911:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4912: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4913: 	    $languages{$lang}=1;
1.97      www      4914:         }
                   4915:     }
                   4916:     return %languages;
1.14      harris41 4917: }
                   4918: 
1.582     albertel 4919: sub languages {
                   4920:     my ($possible_langs) = @_;
1.695     raeburn  4921:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4922:     if (!ref($possible_langs)) {
                   4923: 	if( wantarray ) {
                   4924: 	    return @preferred_langs;
                   4925: 	} else {
                   4926: 	    return $preferred_langs[0];
                   4927: 	}
                   4928:     }
                   4929:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4930:     my @preferred_possibilities;
                   4931:     foreach my $preferred_lang (@preferred_langs) {
                   4932: 	if (exists($possibilities{$preferred_lang})) {
                   4933: 	    push(@preferred_possibilities, $preferred_lang);
                   4934: 	}
                   4935:     }
                   4936:     if( wantarray ) {
                   4937: 	return @preferred_possibilities;
                   4938:     }
                   4939:     return $preferred_possibilities[0];
                   4940: }
                   4941: 
1.742     raeburn  4942: sub user_lang {
                   4943:     my ($touname,$toudom,$fromcid) = @_;
                   4944:     my @userlangs;
                   4945:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4946:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4947:                     $env{'course.'.$fromcid.'.languages'}));
                   4948:     } else {
                   4949:         my %langhash = &getlangs($touname,$toudom);
                   4950:         if ($langhash{'languages'} ne '') {
                   4951:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4952:         } else {
                   4953:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4954:             if ($domdefs{'lang_def'} ne '') {
                   4955:                 @userlangs = ($domdefs{'lang_def'});
                   4956:             }
                   4957:         }
                   4958:     }
                   4959:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4960:     my $user_lh = Apache::localize->get_handle(@languages);
                   4961:     return $user_lh;
                   4962: }
                   4963: 
                   4964: 
1.112     bowersj2 4965: ###############################################################
                   4966: ##               Student Answer Attempts                     ##
                   4967: ###############################################################
                   4968: 
                   4969: =pod
                   4970: 
                   4971: =head1 Alternate Problem Views
                   4972: 
                   4973: =over 4
                   4974: 
1.648     raeburn  4975: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4976:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4977: 
                   4978: Return string with previous attempt on problem. Arguments:
                   4979: 
                   4980: =over 4
                   4981: 
                   4982: =item * $symb: Problem, including path
                   4983: 
                   4984: =item * $username: username of the desired student
                   4985: 
                   4986: =item * $domain: domain of the desired student
1.14      harris41 4987: 
1.112     bowersj2 4988: =item * $course: Course ID
1.14      harris41 4989: 
1.112     bowersj2 4990: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4991:     something
1.14      harris41 4992: 
1.112     bowersj2 4993: =item * $regexp: if string matches this regexp, the string will be
                   4994:     sent to $gradesub
1.14      harris41 4995: 
1.112     bowersj2 4996: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4997: 
1.1199    raeburn  4998: =item * $usec: section of the desired student
                   4999: 
                   5000: =item * $identifier: counter for student (multiple students one problem) or 
                   5001:     problem (one student; whole sequence).
                   5002: 
1.112     bowersj2 5003: =back
1.14      harris41 5004: 
1.112     bowersj2 5005: The output string is a table containing all desired attempts, if any.
1.16      harris41 5006: 
1.112     bowersj2 5007: =cut
1.1       albertel 5008: 
                   5009: sub get_previous_attempt {
1.1199    raeburn  5010:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 5011:   my $prevattempts='';
1.43      ng       5012:   no strict 'refs';
1.1       albertel 5013:   if ($symb) {
1.3       albertel 5014:     my (%returnhash)=
                   5015:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 5016:     if ($returnhash{'version'}) {
                   5017:       my %lasthash=();
                   5018:       my $version;
                   5019:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  5020:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   5021:             if ($key =~ /\.rawrndseed$/) {
                   5022:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   5023:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5024:             } else {
                   5025:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5026:             }
1.19      harris41 5027:         }
1.1       albertel 5028:       }
1.596     albertel 5029:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5030:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5031:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5032:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5033:       foreach my $key (sort(keys(%lasthash))) {
                   5034: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5035: 	if ($#parts > 0) {
1.31      albertel 5036: 	  my $data=$parts[-1];
1.989     raeburn  5037:           next if ($data eq 'foilorder');
1.31      albertel 5038: 	  pop(@parts);
1.1010    www      5039:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5040:           if ($data eq 'type') {
                   5041:               unless ($showsurv) {
                   5042:                   my $id = join(',',@parts);
                   5043:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5044:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5045:                       $lasthidden{$ign.'.'.$id} = 1;
                   5046:                   }
1.945     raeburn  5047:               }
1.1199    raeburn  5048:               if ($identifier ne '') {
                   5049:                   my $id = join(',',@parts);
                   5050:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5051:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5052:                       $hidestatus{$ign.'.'.$id} = 1;
                   5053:                   }
                   5054:               }
                   5055:           } elsif ($data eq 'regrader') {
                   5056:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5057:                   my $id = join(',',@parts);
                   5058:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5059:               }
1.1010    www      5060:           } 
1.31      albertel 5061: 	} else {
1.41      ng       5062: 	  if ($#parts == 0) {
                   5063: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5064: 	  } else {
                   5065: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5066: 	  }
1.31      albertel 5067: 	}
1.16      harris41 5068:       }
1.596     albertel 5069:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5070:       if ($getattempt eq '') {
1.1199    raeburn  5071:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5072:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5073:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5074:                 foreach my $id (keys(%regraded)) {
                   5075:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5076:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5077:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5078:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5079:                     }
                   5080:                 }
                   5081:             }
1.1200    raeburn  5082:         }
                   5083: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5084:             my (@hidden,@unsolved);
1.945     raeburn  5085:             if (%typeparts) {
                   5086:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5087:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5088:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5089:                         push(@hidden,$id);
1.1199    raeburn  5090:                     } elsif ($identifier ne '') {
                   5091:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5092:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5093:                                 ($hidestatus{$id})) {
1.1200    raeburn  5094:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5095:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5096:                                 push(@{$solved{$id}},$version);
                   5097:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5098:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5099:                                 my $skip;
                   5100:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5101:                                     foreach my $reset (@{$resets{$id}}) {
                   5102:                                         if ($reset > $solved{$id}[-1]) {
                   5103:                                             $skip=1;
                   5104:                                             last;
                   5105:                                         }
                   5106:                                     }
                   5107:                                 }
                   5108:                                 unless ($skip) {
                   5109:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5110:                                     push(@unsolved,$partslist);
                   5111:                                 }
                   5112:                             }
                   5113:                         }
1.945     raeburn  5114:                     }
                   5115:                 }
                   5116:             }
                   5117:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5118:                            '<td>'.&mt('Transaction [_1]',$version);
                   5119:             if (@unsolved) {
                   5120:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5121:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5122:                                  &mt('Hide').'</label></span>';
                   5123:             }
                   5124:             $prevattempts .= '</td>';
1.945     raeburn  5125:             if (@hidden) {
                   5126:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5127:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5128:                     my $hide;
                   5129:                     foreach my $id (@hidden) {
                   5130:                         if ($key =~ /^\Q$id\E/) {
                   5131:                             $hide = 1;
                   5132:                             last;
                   5133:                         }
                   5134:                     }
                   5135:                     if ($hide) {
                   5136:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5137:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5138:                             my $value = &format_previous_attempt_value($key,
                   5139:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5140:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5141:                         } else {
                   5142:                             $prevattempts.='<td>&nbsp;</td>';
                   5143:                         }
                   5144:                     } else {
                   5145:                         if ($key =~ /\./) {
1.1212    raeburn  5146:                             my $value = $returnhash{$version.':'.$key};
                   5147:                             if ($key =~ /\.rndseed$/) {
                   5148:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5149:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5150:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5151:                                 }
                   5152:                             }
                   5153:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5154:                                            '&nbsp;</td>';
1.945     raeburn  5155:                         } else {
                   5156:                             $prevattempts.='<td>&nbsp;</td>';
                   5157:                         }
                   5158:                     }
                   5159:                 }
                   5160:             } else {
                   5161: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5162:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5163:                     my $value = $returnhash{$version.':'.$key};
                   5164:                     if ($key =~ /\.rndseed$/) {
                   5165:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5166:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5167:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5168:                         }
                   5169:                     }
                   5170:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5171:                                    '&nbsp;</td>';
1.945     raeburn  5172: 	        }
                   5173:             }
                   5174: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5175: 	 }
1.1       albertel 5176:       }
1.945     raeburn  5177:       my @currhidden = keys(%lasthidden);
1.596     albertel 5178:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5179:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5180:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5181:           if (%typeparts) {
                   5182:               my $hidden;
                   5183:               foreach my $id (@currhidden) {
                   5184:                   if ($key =~ /^\Q$id\E/) {
                   5185:                       $hidden = 1;
                   5186:                       last;
                   5187:                   }
                   5188:               }
                   5189:               if ($hidden) {
                   5190:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5191:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5192:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5193:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5194:                           $value = &$gradesub($value);
                   5195:                       }
1.1173    kruse    5196:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5197:                   } else {
                   5198:                       $prevattempts.='<td>&nbsp;</td>';
                   5199:                   }
                   5200:               } else {
                   5201:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5202:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5203:                       $value = &$gradesub($value);
                   5204:                   }
1.1173    kruse    5205:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5206:               }
                   5207:           } else {
                   5208: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5209: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5210:                   $value = &$gradesub($value);
                   5211:               }
1.1173    kruse    5212: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5213:           }
1.16      harris41 5214:       }
1.596     albertel 5215:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5216:     } else {
1.1305    raeburn  5217:       my $msg;
                   5218:       if ($symb =~ /ext\.tool$/) {
                   5219:           $msg = &mt('No grade passed back.');
                   5220:       } else {
                   5221:           $msg = &mt('Nothing submitted - no attempts.');
                   5222:       }
1.596     albertel 5223:       $prevattempts=
                   5224: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5225: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5226: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5227:     }
                   5228:   } else {
1.596     albertel 5229:     $prevattempts=
                   5230: 	  &start_data_table().&start_data_table_row().
                   5231: 	  '<td>'.&mt('No data.').'</td>'.
                   5232: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5233:   }
1.10      albertel 5234: }
                   5235: 
1.581     albertel 5236: sub format_previous_attempt_value {
                   5237:     my ($key,$value) = @_;
1.1011    www      5238:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5239:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5240:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5241:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5242:     } elsif ($key =~ /answerstring$/) {
                   5243:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5244:         my @answer = %answers;
                   5245:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5246:         my @anskeys = sort(keys(%answers));
                   5247:         if (@anskeys == 1) {
                   5248:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5249:             if ($answer =~ m{\0}) {
                   5250:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5251:             }
                   5252:             my $tag_internal_answer_name = 'INTERNAL';
                   5253:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5254:                 $value = $answer; 
                   5255:             } else {
                   5256:                 $value = $anskeys[0].'='.$answer;
                   5257:             }
                   5258:         } else {
                   5259:             foreach my $ans (@anskeys) {
                   5260:                 my $answer = $answers{$ans};
1.1001    raeburn  5261:                 if ($answer =~ m{\0}) {
                   5262:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5263:                 }
                   5264:                 $value .=  $ans.'='.$answer.'<br />';;
                   5265:             } 
                   5266:         }
1.581     albertel 5267:     } else {
1.1173    kruse    5268:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5269:     }
                   5270:     return $value;
                   5271: }
                   5272: 
                   5273: 
1.107     albertel 5274: sub relative_to_absolute {
                   5275:     my ($url,$output)=@_;
                   5276:     my $parser=HTML::TokeParser->new(\$output);
                   5277:     my $token;
                   5278:     my $thisdir=$url;
                   5279:     my @rlinks=();
                   5280:     while ($token=$parser->get_token) {
                   5281: 	if ($token->[0] eq 'S') {
                   5282: 	    if ($token->[1] eq 'a') {
                   5283: 		if ($token->[2]->{'href'}) {
                   5284: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5285: 		}
                   5286: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5287: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5288: 	    } elsif ($token->[1] eq 'base') {
                   5289: 		$thisdir=$token->[2]->{'href'};
                   5290: 	    }
                   5291: 	}
                   5292:     }
                   5293:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5294:     foreach my $link (@rlinks) {
1.726     raeburn  5295: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5296: 		($link=~/^\//) ||
                   5297: 		($link=~/^javascript:/i) ||
                   5298: 		($link=~/^mailto:/i) ||
                   5299: 		($link=~/^\#/)) {
                   5300: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5301: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5302: 	}
                   5303:     }
                   5304: # -------------------------------------------------- Deal with Applet codebases
                   5305:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5306:     return $output;
                   5307: }
                   5308: 
1.112     bowersj2 5309: =pod
                   5310: 
1.648     raeburn  5311: =item * &get_student_view()
1.112     bowersj2 5312: 
                   5313: show a snapshot of what student was looking at
                   5314: 
                   5315: =cut
                   5316: 
1.10      albertel 5317: sub get_student_view {
1.186     albertel 5318:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5319:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5320:   my (%form);
1.10      albertel 5321:   my @elements=('symb','courseid','domain','username');
                   5322:   foreach my $element (@elements) {
1.186     albertel 5323:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5324:   }
1.186     albertel 5325:   if (defined($moreenv)) {
                   5326:       %form=(%form,%{$moreenv});
                   5327:   }
1.236     albertel 5328:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5329:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5330:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5331:       $feedurl =~ s{^/adm/wrapper}{};
                   5332:   }
1.650     www      5333:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5334:   $userview=~s/\<body[^\>]*\>//gi;
                   5335:   $userview=~s/\<\/body\>//gi;
                   5336:   $userview=~s/\<html\>//gi;
                   5337:   $userview=~s/\<\/html\>//gi;
                   5338:   $userview=~s/\<head\>//gi;
                   5339:   $userview=~s/\<\/head\>//gi;
                   5340:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5341:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5342:   if (wantarray) {
                   5343:      return ($userview,$response);
                   5344:   } else {
                   5345:      return $userview;
                   5346:   }
                   5347: }
                   5348: 
                   5349: sub get_student_view_with_retries {
                   5350:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5351: 
                   5352:     my $ok = 0;                 # True if we got a good response.
                   5353:     my $content;
                   5354:     my $response;
                   5355: 
                   5356:     # Try to get the student_view done. within the retries count:
                   5357:     
                   5358:     do {
                   5359:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5360:          $ok      = $response->is_success;
                   5361:          if (!$ok) {
                   5362:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5363:          }
                   5364:          $retries--;
                   5365:     } while (!$ok && ($retries > 0));
                   5366:     
                   5367:     if (!$ok) {
                   5368:        $content = '';          # On error return an empty content.
                   5369:     }
1.651     www      5370:     if (wantarray) {
                   5371:        return ($content, $response);
                   5372:     } else {
                   5373:        return $content;
                   5374:     }
1.11      albertel 5375: }
                   5376: 
1.1349    raeburn  5377: sub css_links {
                   5378:     my ($currsymb,$level) = @_;
                   5379:     my ($links,@symbs,%cssrefs,%httpref);
                   5380:     if ($level eq 'map') {
                   5381:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5382:         if (ref($navmap)) {
                   5383:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5384:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5385:             foreach my $res (@resources) {
                   5386:                 if (ref($res) && $res->symb()) {
                   5387:                     push(@symbs,$res->symb());
                   5388:                 }
                   5389:             }
                   5390:         }
                   5391:     } else {
                   5392:         @symbs = ($currsymb);
                   5393:     }
                   5394:     foreach my $symb (@symbs) {
                   5395:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5396:         if ($css_href =~ /\S/) {
                   5397:             unless ($css_href =~ m{https?://}) {
                   5398:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5399:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5400:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5401:                 unless ($css_href =~ m{^/}) {
                   5402:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5403:                 }
                   5404:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5405:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5406:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5407:                         my $thisurl = $proburl;
                   5408:                         if ($env{'httpref.'.$proburl}) {
                   5409:                             $thisurl = $env{'httpref.'.$proburl};
                   5410:                         }
                   5411:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5412:                     }
                   5413:                 }
                   5414:             }
                   5415:             $cssrefs{$css_href} = 1;
                   5416:         }
                   5417:     }
                   5418:     if (keys(%httpref)) {
                   5419:         &Apache::lonnet::appenv(\%httpref);
                   5420:     }
                   5421:     if (keys(%cssrefs)) {
                   5422:         foreach my $css_href (keys(%cssrefs)) {
                   5423:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5424:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5425:         }
                   5426:     }
                   5427:     return $links;
                   5428: }
                   5429: 
1.112     bowersj2 5430: =pod
                   5431: 
1.648     raeburn  5432: =item * &get_student_answers() 
1.112     bowersj2 5433: 
                   5434: show a snapshot of how student was answering problem
                   5435: 
                   5436: =cut
                   5437: 
1.11      albertel 5438: sub get_student_answers {
1.100     sakharuk 5439:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5440:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5441:   my (%moreenv);
1.11      albertel 5442:   my @elements=('symb','courseid','domain','username');
                   5443:   foreach my $element (@elements) {
1.186     albertel 5444:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5445:   }
1.186     albertel 5446:   $moreenv{'grade_target'}='answer';
                   5447:   %moreenv=(%form,%moreenv);
1.497     raeburn  5448:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5449:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5450:   return $userview;
1.1       albertel 5451: }
1.116     albertel 5452: 
                   5453: =pod
                   5454: 
                   5455: =item * &submlink()
                   5456: 
1.242     albertel 5457: Inputs: $text $uname $udom $symb $target
1.116     albertel 5458: 
                   5459: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5460: 
                   5461: =cut
                   5462: 
                   5463: ###############################################
                   5464: sub submlink {
1.242     albertel 5465:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5466:     if (!($uname && $udom)) {
                   5467: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5468: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5469: 	if (!$symb) { $symb=$cursymb; }
                   5470:     }
1.254     matthew  5471:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5472:     $symb=&escape($symb);
1.960     bisitz   5473:     if ($target) { $target=" target=\"$target\""; }
                   5474:     return
                   5475:         '<a href="/adm/grades?command=submission'.
                   5476:         '&amp;symb='.$symb.
                   5477:         '&amp;student='.$uname.
                   5478:         '&amp;userdom='.$udom.'"'.
                   5479:         $target.'>'.$text.'</a>';
1.242     albertel 5480: }
                   5481: ##############################################
                   5482: 
                   5483: =pod
                   5484: 
                   5485: =item * &pgrdlink()
                   5486: 
                   5487: Inputs: $text $uname $udom $symb $target
                   5488: 
                   5489: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5490: 
                   5491: =cut
                   5492: 
                   5493: ###############################################
                   5494: sub pgrdlink {
                   5495:     my $link=&submlink(@_);
                   5496:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5497:     return $link;
                   5498: }
                   5499: ##############################################
                   5500: 
                   5501: =pod
                   5502: 
                   5503: =item * &pprmlink()
                   5504: 
                   5505: Inputs: $text $uname $udom $symb $target
                   5506: 
                   5507: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5508: student and a specific resource
1.242     albertel 5509: 
                   5510: =cut
                   5511: 
                   5512: ###############################################
                   5513: sub pprmlink {
                   5514:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5515:     if (!($uname && $udom)) {
                   5516: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5517: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5518: 	if (!$symb) { $symb=$cursymb; }
                   5519:     }
1.254     matthew  5520:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5521:     $symb=&escape($symb);
1.242     albertel 5522:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5523:     return '<a href="/adm/parmset?command=set&amp;'.
                   5524: 	'symb='.$symb.'&amp;uname='.$uname.
                   5525: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5526: }
                   5527: ##############################################
1.37      matthew  5528: 
1.112     bowersj2 5529: =pod
                   5530: 
                   5531: =back
                   5532: 
                   5533: =cut
                   5534: 
1.37      matthew  5535: ###############################################
1.51      www      5536: 
                   5537: 
                   5538: sub timehash {
1.687     raeburn  5539:     my ($thistime) = @_;
                   5540:     my $timezone = &Apache::lonlocal::gettimezone();
                   5541:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5542:                      ->set_time_zone($timezone);
                   5543:     my $wday = $dt->day_of_week();
                   5544:     if ($wday == 7) { $wday = 0; }
                   5545:     return ( 'second' => $dt->second(),
                   5546:              'minute' => $dt->minute(),
                   5547:              'hour'   => $dt->hour(),
                   5548:              'day'     => $dt->day_of_month(),
                   5549:              'month'   => $dt->month(),
                   5550:              'year'    => $dt->year(),
                   5551:              'weekday' => $wday,
                   5552:              'dayyear' => $dt->day_of_year(),
                   5553:              'dlsav'   => $dt->is_dst() );
1.51      www      5554: }
                   5555: 
1.370     www      5556: sub utc_string {
                   5557:     my ($date)=@_;
1.371     www      5558:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5559: }
                   5560: 
1.51      www      5561: sub maketime {
                   5562:     my %th=@_;
1.687     raeburn  5563:     my ($epoch_time,$timezone,$dt);
                   5564:     $timezone = &Apache::lonlocal::gettimezone();
                   5565:     eval {
                   5566:         $dt = DateTime->new( year   => $th{'year'},
                   5567:                              month  => $th{'month'},
                   5568:                              day    => $th{'day'},
                   5569:                              hour   => $th{'hour'},
                   5570:                              minute => $th{'minute'},
                   5571:                              second => $th{'second'},
                   5572:                              time_zone => $timezone,
                   5573:                          );
                   5574:     };
                   5575:     if (!$@) {
                   5576:         $epoch_time = $dt->epoch;
                   5577:         if ($epoch_time) {
                   5578:             return $epoch_time;
                   5579:         }
                   5580:     }
1.51      www      5581:     return POSIX::mktime(
                   5582:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5583:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5584: }
                   5585: 
                   5586: #########################################
1.51      www      5587: 
                   5588: sub findallcourses {
1.482     raeburn  5589:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5590:     my %roles;
                   5591:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5592:     my %courses;
1.51      www      5593:     my $now=time;
1.482     raeburn  5594:     if (!defined($uname)) {
                   5595:         $uname = $env{'user.name'};
                   5596:     }
                   5597:     if (!defined($udom)) {
                   5598:         $udom = $env{'user.domain'};
                   5599:     }
                   5600:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5601:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5602:         if (!%roles) {
                   5603:             %roles = (
                   5604:                        cc => 1,
1.907     raeburn  5605:                        co => 1,
1.482     raeburn  5606:                        in => 1,
                   5607:                        ep => 1,
                   5608:                        ta => 1,
                   5609:                        cr => 1,
                   5610:                        st => 1,
                   5611:              );
                   5612:         }
                   5613:         foreach my $entry (keys(%roleshash)) {
                   5614:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5615:             if ($trole =~ /^cr/) { 
                   5616:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5617:             } else {
                   5618:                 next if (!exists($roles{$trole}));
                   5619:             }
                   5620:             if ($tend) {
                   5621:                 next if ($tend < $now);
                   5622:             }
                   5623:             if ($tstart) {
                   5624:                 next if ($tstart > $now);
                   5625:             }
1.1058    raeburn  5626:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5627:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5628:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5629:             if ($secpart eq '') {
                   5630:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5631:                 $sec = 'none';
1.1058    raeburn  5632:                 $value .= $cnum.'/';
1.482     raeburn  5633:             } else {
                   5634:                 $cnum = $cnumpart;
                   5635:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5636:                 $value .= $cnum.'/'.$sec;
                   5637:             }
                   5638:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5639:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5640:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5641:                 }
                   5642:             } else {
                   5643:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5644:             }
1.482     raeburn  5645:         }
                   5646:     } else {
                   5647:         foreach my $key (keys(%env)) {
1.483     albertel 5648: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5649:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5650: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5651: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5652: 	        next if (%roles && !exists($roles{$role}));
                   5653: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5654:                 my $active=1;
                   5655:                 if ($starttime) {
                   5656: 		    if ($now<$starttime) { $active=0; }
                   5657:                 }
                   5658:                 if ($endtime) {
                   5659:                     if ($now>$endtime) { $active=0; }
                   5660:                 }
                   5661:                 if ($active) {
1.1058    raeburn  5662:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5663:                     if ($sec eq '') {
                   5664:                         $sec = 'none';
1.1058    raeburn  5665:                     } else {
                   5666:                         $value .= $sec;
                   5667:                     }
                   5668:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5669:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5670:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5671:                         }
                   5672:                     } else {
                   5673:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5674:                     }
1.474     raeburn  5675:                 }
                   5676:             }
1.51      www      5677:         }
                   5678:     }
1.474     raeburn  5679:     return %courses;
1.51      www      5680: }
1.37      matthew  5681: 
1.54      www      5682: ###############################################
1.474     raeburn  5683: 
                   5684: sub blockcheck {
1.1372    raeburn  5685:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5686:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5687:         my ($has_evb,$check_ipaccess);
                   5688:         my $dom = $env{'user.domain'};
                   5689:         if ($env{'request.course.id'}) {
                   5690:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5691:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5692:             my $checkrole = "cm./$cdom/$cnum";
                   5693:             my $sec = $env{'request.course.sec'};
                   5694:             if ($sec ne '') {
                   5695:                 $checkrole .= "/$sec";
                   5696:             }
                   5697:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5698:                 ($env{'request.role'} !~ /^st/)) {
                   5699:                 $has_evb = 1;
                   5700:             }
                   5701:             unless ($has_evb) {
                   5702:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5703:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5704:                     ($activity eq 'chat')) {
1.1372    raeburn  5705:                     if ($udom eq $cdom) {
                   5706:                         $check_ipaccess = 1;
                   5707:                     }
                   5708:                 }
                   5709:             }
1.1375    raeburn  5710:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5711:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5712:             my $checkrole;
                   5713:             if ($env{'request.role.domain'} eq '') {
                   5714:                 $checkrole = "cm./$env{'user.domain'}/";
                   5715:             } else {
                   5716:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5717:             }
                   5718:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5719:                 $has_evb = 1;
                   5720:             }
1.1372    raeburn  5721:         }
                   5722:         unless ($has_evb || $check_ipaccess) {
                   5723:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5724:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5725:                 $dom = $udom;
                   5726:             }
                   5727:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5728:                 $check_ipaccess = 1;
                   5729:             } else {
                   5730:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5731:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5732:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5733:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5734:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5735:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5736:                         $check_ipaccess = 1;
                   5737:                     }
                   5738:                 }
                   5739:             }
                   5740:         }
                   5741:         if ($check_ipaccess) {
                   5742:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5743:             unless (defined($cached)) {
                   5744:                 my %domconfig =
                   5745:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5746:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5747:             }
                   5748:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5749:                 foreach my $id (keys(%{$ipaccessref})) {
                   5750:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5751:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5752:                         if ($range) {
                   5753:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5754:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5755:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5756:                                         return ('','','',$id,$dom);
                   5757:                                         last;
                   5758:                                     }
                   5759:                                 }
                   5760:                             }
                   5761:                         }
                   5762:                     }
                   5763:                 }
                   5764:             }
                   5765:         }
1.1373    raeburn  5766:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5767:             return ();
                   5768:         }
1.1372    raeburn  5769:     }
1.1189    raeburn  5770:     if (defined($udom) && defined($uname)) {
                   5771:         # If uname and udom are for a course, check for blocks in the course.
                   5772:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5773:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5774:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5775:             return ($startblock,$endblock,$triggerblock);
                   5776:         }
                   5777:     } else {
1.490     raeburn  5778:         $udom = $env{'user.domain'};
                   5779:         $uname = $env{'user.name'};
                   5780:     }
                   5781: 
1.502     raeburn  5782:     my $startblock = 0;
                   5783:     my $endblock = 0;
1.1062    raeburn  5784:     my $triggerblock = '';
1.1373    raeburn  5785:     my %live_courses;
                   5786:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5787:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5788:     }
1.474     raeburn  5789: 
1.490     raeburn  5790:     # If uname is for a user, and activity is course-specific, i.e.,
                   5791:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5792: 
1.490     raeburn  5793:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5794:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5795:          $activity eq 'search' || $activity eq 'index' ||
                   5796:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5797:         ($env{'request.course.id'})) {
1.490     raeburn  5798:         foreach my $key (keys(%live_courses)) {
                   5799:             if ($key ne $env{'request.course.id'}) {
                   5800:                 delete($live_courses{$key});
                   5801:             }
                   5802:         }
                   5803:     }
                   5804: 
                   5805:     my $otheruser = 0;
                   5806:     my %own_courses;
                   5807:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5808:         # Resource belongs to user other than current user.
                   5809:         $otheruser = 1;
                   5810:         # Gather courses for current user
                   5811:         %own_courses = 
                   5812:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5813:     }
                   5814: 
                   5815:     # Gather active course roles - course coordinator, instructor, 
                   5816:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5817: 
                   5818:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5819:         my ($cdom,$cnum);
                   5820:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5821:             $cdom = $env{'course.'.$course.'.domain'};
                   5822:             $cnum = $env{'course.'.$course.'.num'};
                   5823:         } else {
1.490     raeburn  5824:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5825:         }
                   5826:         my $no_ownblock = 0;
                   5827:         my $no_userblock = 0;
1.533     raeburn  5828:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5829:             # Check if current user has 'evb' priv for this
                   5830:             if (defined($own_courses{$course})) {
                   5831:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5832:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5833:                     if ($sec ne 'none') {
                   5834:                         $checkrole .= '/'.$sec;
                   5835:                     }
                   5836:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5837:                         $no_ownblock = 1;
                   5838:                         last;
                   5839:                     }
                   5840:                 }
                   5841:             }
                   5842:             # if they have 'evb' priv and are currently not playing student
                   5843:             next if (($no_ownblock) &&
                   5844:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5845:         }
1.474     raeburn  5846:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5847:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5848:             if ($sec ne 'none') {
1.482     raeburn  5849:                 $checkrole .= '/'.$sec;
1.474     raeburn  5850:             }
1.490     raeburn  5851:             if ($otheruser) {
                   5852:                 # Resource belongs to user other than current user.
                   5853:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5854:                 my (%allroles,%userroles);
                   5855:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5856:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5857:                         my ($trole,$tdom,$tnum,$tsec);
                   5858:                         if ($entry =~ /^cr/) {
                   5859:                             ($trole,$tdom,$tnum,$tsec) = 
                   5860:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5861:                         } else {
                   5862:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5863:                         }
                   5864:                         my ($spec,$area,$trest);
                   5865:                         $area = '/'.$tdom.'/'.$tnum;
                   5866:                         $trest = $tnum;
                   5867:                         if ($tsec ne '') {
                   5868:                             $area .= '/'.$tsec;
                   5869:                             $trest .= '/'.$tsec;
                   5870:                         }
                   5871:                         $spec = $trole.'.'.$area;
                   5872:                         if ($trole =~ /^cr/) {
                   5873:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5874:                                                               $tdom,$spec,$trest,$area);
                   5875:                         } else {
                   5876:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5877:                                                                 $tdom,$spec,$trest,$area);
                   5878:                         }
                   5879:                     }
1.1276    raeburn  5880:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5881:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5882:                         if ($1) {
                   5883:                             $no_userblock = 1;
                   5884:                             last;
                   5885:                         }
1.486     raeburn  5886:                     }
                   5887:                 }
1.490     raeburn  5888:             } else {
                   5889:                 # Resource belongs to current user
                   5890:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5891:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5892:                     $no_ownblock = 1;
                   5893:                     last;
                   5894:                 }
1.474     raeburn  5895:             }
                   5896:         }
                   5897:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5898:         next if (($no_ownblock) &&
1.491     albertel 5899:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5900:         next if ($no_userblock);
1.474     raeburn  5901: 
1.1303    raeburn  5902:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5903:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5904: 
1.1062    raeburn  5905:         my ($start,$end,$trigger) = 
1.1347    raeburn  5906:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5907:         if (($start != 0) && 
                   5908:             (($startblock == 0) || ($startblock > $start))) {
                   5909:             $startblock = $start;
1.1062    raeburn  5910:             if ($trigger ne '') {
                   5911:                 $triggerblock = $trigger;
                   5912:             }
1.502     raeburn  5913:         }
                   5914:         if (($end != 0)  &&
                   5915:             (($endblock == 0) || ($endblock < $end))) {
                   5916:             $endblock = $end;
1.1062    raeburn  5917:             if ($trigger ne '') {
                   5918:                 $triggerblock = $trigger;
                   5919:             }
1.502     raeburn  5920:         }
1.490     raeburn  5921:     }
1.1062    raeburn  5922:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5923: }
                   5924: 
                   5925: sub get_blocks {
1.1347    raeburn  5926:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5927:     my $startblock = 0;
                   5928:     my $endblock = 0;
1.1062    raeburn  5929:     my $triggerblock = '';
1.490     raeburn  5930:     my $course = $cdom.'_'.$cnum;
                   5931:     $setters->{$course} = {};
                   5932:     $setters->{$course}{'staff'} = [];
                   5933:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5934:     $setters->{$course}{'triggers'} = [];
                   5935:     my (@blockers,%triggered);
                   5936:     my $now = time;
                   5937:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5938:     if ($activity eq 'docs') {
1.1348    raeburn  5939:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5940:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5941:             $blocked = 1;
                   5942:             $nosymbcache = 1;
1.1348    raeburn  5943:             $noenccheck = 1;
1.1347    raeburn  5944:         }
1.1348    raeburn  5945:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5946:         foreach my $block (@blockers) {
                   5947:             if ($block =~ /^firstaccess____(.+)$/) {
                   5948:                 my $item = $1;
                   5949:                 my $type = 'map';
                   5950:                 my $timersymb = $item;
                   5951:                 if ($item eq 'course') {
                   5952:                     $type = 'course';
                   5953:                 } elsif ($item =~ /___\d+___/) {
                   5954:                     $type = 'resource';
                   5955:                 } else {
                   5956:                     $timersymb = &Apache::lonnet::symbread($item);
                   5957:                 }
                   5958:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5959:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5960:                 $triggered{$block} = {
                   5961:                                        start => $start,
                   5962:                                        end   => $end,
                   5963:                                        type  => $type,
                   5964:                                      };
                   5965:             }
                   5966:         }
                   5967:     } else {
                   5968:         foreach my $block (keys(%commblocks)) {
                   5969:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5970:                 my ($start,$end) = ($1,$2);
                   5971:                 if ($start <= time && $end >= time) {
                   5972:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5973:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5974:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5975:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5976:                                     push(@blockers,$block);
                   5977:                                 }
                   5978:                             }
                   5979:                         }
                   5980:                     }
                   5981:                 }
                   5982:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5983:                 my $item = $1;
                   5984:                 my $timersymb = $item; 
                   5985:                 my $type = 'map';
                   5986:                 if ($item eq 'course') {
                   5987:                     $type = 'course';
                   5988:                 } elsif ($item =~ /___\d+___/) {
                   5989:                     $type = 'resource';
                   5990:                 } else {
                   5991:                     $timersymb = &Apache::lonnet::symbread($item);
                   5992:                 }
                   5993:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5994:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5995:                 if ($start && $end) {
                   5996:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5997:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5998:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5999:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6000:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   6001:                                         push(@blockers,$block);
                   6002:                                         $triggered{$block} = {
                   6003:                                                                start => $start,
                   6004:                                                                end   => $end,
                   6005:                                                                type  => $type,
                   6006:                                                              };
                   6007:                                     }
                   6008:                                 }
                   6009:                             }
1.1062    raeburn  6010:                         }
                   6011:                     }
1.490     raeburn  6012:                 }
1.1062    raeburn  6013:             }
                   6014:         }
                   6015:     }
                   6016:     foreach my $blocker (@blockers) {
                   6017:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6018:             &parse_block_record($commblocks{$blocker});
                   6019:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6020:         my ($start,$end,$triggertype);
                   6021:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6022:             ($start,$end) = ($1,$2);
                   6023:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6024:             $start = $triggered{$blocker}{'start'};
                   6025:             $end = $triggered{$blocker}{'end'};
                   6026:             $triggertype = $triggered{$blocker}{'type'};
                   6027:         }
                   6028:         if ($start) {
                   6029:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6030:             if ($triggertype) {
                   6031:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6032:             } else {
                   6033:                 push(@{$$setters{$course}{'triggers'}},0);
                   6034:             }
                   6035:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6036:                 $startblock = $start;
                   6037:                 if ($triggertype) {
                   6038:                     $triggerblock = $blocker;
1.474     raeburn  6039:                 }
                   6040:             }
1.1062    raeburn  6041:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6042:                $endblock = $end;
                   6043:                if ($triggertype) {
                   6044:                    $triggerblock = $blocker;
                   6045:                }
                   6046:             }
1.474     raeburn  6047:         }
                   6048:     }
1.1062    raeburn  6049:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6050: }
                   6051: 
                   6052: sub parse_block_record {
                   6053:     my ($record) = @_;
                   6054:     my ($setuname,$setudom,$title,$blocks);
                   6055:     if (ref($record) eq 'HASH') {
                   6056:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6057:         $title = &unescape($record->{'event'});
                   6058:         $blocks = $record->{'blocks'};
                   6059:     } else {
                   6060:         my @data = split(/:/,$record,3);
                   6061:         if (scalar(@data) eq 2) {
                   6062:             $title = $data[1];
                   6063:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6064:         } else {
                   6065:             ($setuname,$setudom,$title) = @data;
                   6066:         }
                   6067:         $blocks = { 'com' => 'on' };
                   6068:     }
                   6069:     return ($setuname,$setudom,$title,$blocks);
                   6070: }
                   6071: 
1.854     kalberla 6072: sub blocking_status {
1.1372    raeburn  6073:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6074:     my %setters;
1.890     droeschl 6075: 
1.1061    raeburn  6076: # check for active blocking
1.1372    raeburn  6077:     if ($clientip eq '') {
                   6078:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6079:     }
                   6080:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6081:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6082:     my $blocked = 0;
1.1372    raeburn  6083:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6084:         $blocked = 1;
                   6085:     }
1.890     droeschl 6086: 
1.1061    raeburn  6087: # caller just wants to know whether a block is active
                   6088:     if (!wantarray) { return $blocked; }
                   6089: 
                   6090: # build a link to a popup window containing the details
                   6091:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6092: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6093:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6094:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6095:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6096:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6097:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6098:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6099:         if ($symb) {
                   6100:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6101:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6102:         }
1.1062    raeburn  6103:     }
1.1061    raeburn  6104: 
                   6105:     my $output .= <<'END_MYBLOCK';
                   6106: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6107:     var options = "width=" + w + ",height=" + h + ",";
                   6108:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6109:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6110:     var newWin = window.open(url, wdwName, options);
                   6111:     newWin.focus();
                   6112: }
1.890     droeschl 6113: END_MYBLOCK
1.854     kalberla 6114: 
1.1061    raeburn  6115:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6116:   
1.1061    raeburn  6117:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6118:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6119:     my $class = 'LC_comblock';
1.1062    raeburn  6120:     if ($activity eq 'docs') {
                   6121:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6122:         $class = '';
1.1063    raeburn  6123:     } elsif ($activity eq 'printout') {
                   6124:         $text = &mt('Printing Blocked');
1.1232    raeburn  6125:     } elsif ($activity eq 'passwd') {
                   6126:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6127:     } elsif ($activity eq 'grades') {
                   6128:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6129:     } elsif ($activity eq 'search') {
                   6130:         $text = &mt('Search Blocked');
1.1444    raeburn  6131:     } elsif ($activity eq 'index') {
                   6132:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6133:     } elsif ($activity eq 'alert') {
                   6134:         $text = &mt('Checking Critical Messages Blocked');
                   6135:     } elsif ($activity eq 'reinit') {
                   6136:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6137:     } elsif ($activity eq 'about') {
                   6138:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6139:     } elsif ($activity eq 'wishlist') {
                   6140:         $text = &mt('Access to Stored Links Blocked');
                   6141:     } elsif ($activity eq 'annotate') {
                   6142:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6143:     }
1.1061    raeburn  6144:     $output .= <<"END_BLOCK";
1.1217    raeburn  6145: <div class='$class'>
1.869     kalberla 6146:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6147:   title='$text'>
                   6148:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6149:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6150:   title='$text'>$text</a>
1.867     kalberla 6151: </div>
                   6152: 
                   6153: END_BLOCK
1.474     raeburn  6154: 
1.1061    raeburn  6155:     return ($blocked, $output);
1.854     kalberla 6156: }
1.490     raeburn  6157: 
1.60      matthew  6158: ###############################################
                   6159: 
1.682     raeburn  6160: sub check_ip_acc {
1.1201    raeburn  6161:     my ($acc,$clientip)=@_;
1.682     raeburn  6162:     &Apache::lonxml::debug("acc is $acc");
                   6163:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6164:         return 1;
                   6165:     }
1.1339    raeburn  6166:     my ($ip,$allowed);
                   6167:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6168:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6169:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6170:     } else {
1.1350    raeburn  6171:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6172:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6173:     }
1.682     raeburn  6174: 
                   6175:     my $name;
1.1219    raeburn  6176:     my %access = (
                   6177:                      allowfrom => 1,
                   6178:                      denyfrom  => 0,
                   6179:                  );
                   6180:     my @allows;
                   6181:     my @denies;
                   6182:     foreach my $item (split(',',$acc)) {
                   6183:         $item =~ s/^\s*//;
                   6184:         $item =~ s/\s*$//;
                   6185:         my $pattern;
                   6186:         if ($item =~ /^\!(.+)$/) {
                   6187:             push(@denies,$1);
                   6188:         } else {
                   6189:             push(@allows,$item);
                   6190:         }
                   6191:    }
                   6192:    my $numdenies = scalar(@denies);
                   6193:    my $numallows = scalar(@allows);
                   6194:    my $count = 0;
                   6195:    foreach my $pattern (@denies,@allows) {
                   6196:         $count ++; 
                   6197:         my $acctype = 'allowfrom';
                   6198:         if ($count <= $numdenies) {
                   6199:             $acctype = 'denyfrom';
                   6200:         }
1.682     raeburn  6201:         if ($pattern =~ /\*$/) {
                   6202:             #35.8.*
                   6203:             $pattern=~s/\*//;
1.1219    raeburn  6204:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6205:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6206:             #35.8.3.[34-56]
                   6207:             my $low=$2;
                   6208:             my $high=$3;
                   6209:             $pattern=$1;
                   6210:             if ($ip =~ /^\Q$pattern\E/) {
                   6211:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6212:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6213:             }
                   6214:         } elsif ($pattern =~ /^\*/) {
                   6215:             #*.msu.edu
                   6216:             $pattern=~s/\*//;
                   6217:             if (!defined($name)) {
                   6218:                 use Socket;
                   6219:                 my $netaddr=inet_aton($ip);
                   6220:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6221:             }
1.1219    raeburn  6222:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6223:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6224:             #127.0.0.1
1.1219    raeburn  6225:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6226:         } else {
                   6227:             #some.name.com
                   6228:             if (!defined($name)) {
                   6229:                 use Socket;
                   6230:                 my $netaddr=inet_aton($ip);
                   6231:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6232:             }
1.1219    raeburn  6233:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6234:         }
                   6235:         if ($allowed =~ /^(0|1)$/) { last; }
                   6236:     }
                   6237:     if ($allowed eq '') {
                   6238:         if ($numdenies && !$numallows) {
                   6239:             $allowed = 1;
                   6240:         } else {
                   6241:             $allowed = 0;
1.682     raeburn  6242:         }
                   6243:     }
                   6244:     return $allowed;
                   6245: }
                   6246: 
                   6247: ###############################################
                   6248: 
1.60      matthew  6249: =pod
                   6250: 
1.112     bowersj2 6251: =head1 Domain Template Functions
                   6252: 
                   6253: =over 4
                   6254: 
                   6255: =item * &determinedomain()
1.60      matthew  6256: 
                   6257: Inputs: $domain (usually will be undef)
                   6258: 
1.63      www      6259: Returns: Determines which domain should be used for designs
1.60      matthew  6260: 
                   6261: =cut
1.54      www      6262: 
1.60      matthew  6263: ###############################################
1.63      www      6264: sub determinedomain {
                   6265:     my $domain=shift;
1.531     albertel 6266:     if (! $domain) {
1.60      matthew  6267:         # Determine domain if we have not been given one
1.893     raeburn  6268:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6269:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6270:         if ($env{'request.role.domain'}) { 
                   6271:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6272:         }
                   6273:     }
1.63      www      6274:     return $domain;
                   6275: }
                   6276: ###############################################
1.517     raeburn  6277: 
1.518     albertel 6278: sub devalidate_domconfig_cache {
                   6279:     my ($udom)=@_;
                   6280:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6281: }
                   6282: 
                   6283: # ---------------------- Get domain configuration for a domain
                   6284: sub get_domainconf {
                   6285:     my ($udom) = @_;
                   6286:     my $cachetime=1800;
                   6287:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6288:     if (defined($cached)) { return %{$result}; }
                   6289: 
                   6290:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6291: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6292:     my (%designhash,%legacy);
1.518     albertel 6293:     if (keys(%domconfig) > 0) {
                   6294:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6295:             if (keys(%{$domconfig{'login'}})) {
                   6296:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6297:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6298:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6299:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6300:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6301:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6302:                                         if ($key eq 'loginvia') {
                   6303:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6304:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6305:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6306:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6307: 
                   6308:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6309:                                                 } else {
                   6310:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6311:                                                 }
1.948     raeburn  6312:                                             }
1.1208    raeburn  6313:                                         } elsif ($key eq 'headtag') {
                   6314:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6315:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6316:                                             }
1.946     raeburn  6317:                                         }
1.1208    raeburn  6318:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6319:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6320:                                         }
1.946     raeburn  6321:                                     }
                   6322:                                 }
                   6323:                             }
1.1366    raeburn  6324:                         } elsif ($key eq 'saml') {
                   6325:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6326:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6327:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6328:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6329:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6330:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6331:                                         }
                   6332:                                     }
                   6333:                                 }
                   6334:                             }
1.946     raeburn  6335:                         } else {
                   6336:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6337:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6338:                                     $domconfig{'login'}{$key}{$img};
                   6339:                             }
1.699     raeburn  6340:                         }
                   6341:                     } else {
                   6342:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6343:                     }
1.632     raeburn  6344:                 }
                   6345:             } else {
                   6346:                 $legacy{'login'} = 1;
1.518     albertel 6347:             }
1.632     raeburn  6348:         } else {
                   6349:             $legacy{'login'} = 1;
1.518     albertel 6350:         }
                   6351:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6352:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6353:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6354:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6355:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6356:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6357:                         }
1.518     albertel 6358:                     }
                   6359:                 }
1.632     raeburn  6360:             } else {
                   6361:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6362:             }
1.632     raeburn  6363:         } else {
                   6364:             $legacy{'rolecolors'} = 1;
1.518     albertel 6365:         }
1.948     raeburn  6366:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6367:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6368:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6369:             }
                   6370:         }
1.632     raeburn  6371:         if (keys(%legacy) > 0) {
                   6372:             my %legacyhash = &get_legacy_domconf($udom);
                   6373:             foreach my $item (keys(%legacyhash)) {
                   6374:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6375:                     if ($legacy{'login'}) { 
                   6376:                         $designhash{$item} = $legacyhash{$item};
                   6377:                     }
                   6378:                 } else {
                   6379:                     if ($legacy{'rolecolors'}) {
                   6380:                         $designhash{$item} = $legacyhash{$item};
                   6381:                     }
1.518     albertel 6382:                 }
                   6383:             }
                   6384:         }
1.632     raeburn  6385:     } else {
                   6386:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6387:     }
                   6388:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6389: 				  $cachetime);
                   6390:     return %designhash;
                   6391: }
                   6392: 
1.632     raeburn  6393: sub get_legacy_domconf {
                   6394:     my ($udom) = @_;
                   6395:     my %legacyhash;
                   6396:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6397:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6398:     if (-e $designfile) {
1.1317    raeburn  6399:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6400:             while (my $line = <$fh>) {
                   6401:                 next if ($line =~ /^\#/);
                   6402:                 chomp($line);
                   6403:                 my ($key,$val)=(split(/\=/,$line));
                   6404:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6405:             }
                   6406:             close($fh);
                   6407:         }
                   6408:     }
1.1026    raeburn  6409:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6410:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6411:     }
                   6412:     return %legacyhash;
                   6413: }
                   6414: 
1.63      www      6415: =pod
                   6416: 
1.112     bowersj2 6417: =item * &domainlogo()
1.63      www      6418: 
                   6419: Inputs: $domain (usually will be undef)
                   6420: 
                   6421: Returns: A link to a domain logo, if the domain logo exists.
                   6422: If the domain logo does not exist, a description of the domain.
                   6423: 
                   6424: =cut
1.112     bowersj2 6425: 
1.63      www      6426: ###############################################
                   6427: sub domainlogo {
1.517     raeburn  6428:     my $domain = &determinedomain(shift);
1.518     albertel 6429:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6430:     # See if there is a logo
                   6431:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6432:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6433:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6434: 	    if ($imgsrc =~ m{^/res/}) {
                   6435: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6436: 		&Apache::lonnet::repcopy($local_name);
                   6437: 	    }
                   6438: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6439:         }
                   6440:         my $alttext = $domain;
                   6441:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6442:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6443:         }
                   6444:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6445:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6446:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6447:     } else {
1.60      matthew  6448:         return '';
1.59      www      6449:     }
                   6450: }
1.63      www      6451: ##############################################
                   6452: 
                   6453: =pod
                   6454: 
1.112     bowersj2 6455: =item * &designparm()
1.63      www      6456: 
                   6457: Inputs: $which parameter; $domain (usually will be undef)
                   6458: 
                   6459: Returns: value of designparamter $which
                   6460: 
                   6461: =cut
1.112     bowersj2 6462: 
1.397     albertel 6463: 
1.400     albertel 6464: ##############################################
1.397     albertel 6465: sub designparm {
                   6466:     my ($which,$domain)=@_;
                   6467:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6468:         return $env{'environment.color.'.$which};
1.96      www      6469:     }
1.63      www      6470:     $domain=&determinedomain($domain);
1.1016    raeburn  6471:     my %domdesign;
                   6472:     unless ($domain eq 'public') {
                   6473:         %domdesign = &get_domainconf($domain);
                   6474:     }
1.520     raeburn  6475:     my $output;
1.517     raeburn  6476:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6477:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6478:     } else {
1.520     raeburn  6479:         $output = $defaultdesign{$which};
                   6480:     }
                   6481:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6482:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6483:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6484:             if ($output =~ m{^/res/}) {
                   6485:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6486:                 &Apache::lonnet::repcopy($local_name);
                   6487:             }
1.520     raeburn  6488:             $output = &lonhttpdurl($output);
                   6489:         }
1.63      www      6490:     }
1.520     raeburn  6491:     return $output;
1.63      www      6492: }
1.59      www      6493: 
1.822     bisitz   6494: ##############################################
                   6495: =pod
                   6496: 
1.832     bisitz   6497: =item * &authorspace()
                   6498: 
1.1028    raeburn  6499: Inputs: $url (usually will be undef).
1.832     bisitz   6500: 
1.1132    raeburn  6501: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6502:          directory being viewed (or for which action is being taken). 
                   6503:          If $url is provided, and begins /priv/<domain>/<uname>
                   6504:          the path will be that portion of the $context argument.
                   6505:          Otherwise the path will be for the author space of the current
                   6506:          user when the current role is author, or for that of the 
                   6507:          co-author/assistant co-author space when the current role 
                   6508:          is co-author or assistant co-author.
1.832     bisitz   6509: 
                   6510: =cut
                   6511: 
                   6512: sub authorspace {
1.1028    raeburn  6513:     my ($url) = @_;
                   6514:     if ($url ne '') {
                   6515:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6516:            return $1;
                   6517:         }
                   6518:     }
1.832     bisitz   6519:     my $caname = '';
1.1024    www      6520:     my $cadom = '';
1.1028    raeburn  6521:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6522:         ($cadom,$caname) =
1.832     bisitz   6523:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6524:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6525:         $caname = $env{'user.name'};
1.1024    www      6526:         $cadom = $env{'user.domain'};
1.832     bisitz   6527:     }
1.1028    raeburn  6528:     if (($caname ne '') && ($cadom ne '')) {
                   6529:         return "/priv/$cadom/$caname/";
                   6530:     }
                   6531:     return;
1.832     bisitz   6532: }
                   6533: 
                   6534: ##############################################
                   6535: =pod
                   6536: 
1.822     bisitz   6537: =item * &head_subbox()
                   6538: 
                   6539: Inputs: $content (contains HTML code with page functions, etc.)
                   6540: 
                   6541: Returns: HTML div with $content
                   6542:          To be included in page header
                   6543: 
                   6544: =cut
                   6545: 
                   6546: sub head_subbox {
                   6547:     my ($content)=@_;
                   6548:     my $output =
1.993     raeburn  6549:         '<div class="LC_head_subbox">'
1.822     bisitz   6550:        .$content
                   6551:        .'</div>'
                   6552: }
                   6553: 
                   6554: ##############################################
                   6555: =pod
                   6556: 
                   6557: =item * &CSTR_pageheader()
                   6558: 
1.1026    raeburn  6559: Input: (optional) filename from which breadcrumb trail is built.
                   6560:        In most cases no input as needed, as $env{'request.filename'}
                   6561:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6562:        frameset flag
                   6563:        If page header is being requested for use in a frameset, then
                   6564:        the second (option) argument -- frameset will be true, and
                   6565:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6566:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6567:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6568: 
                   6569: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6570:          To be included on Authoring Space pages
1.822     bisitz   6571: 
                   6572: =cut
                   6573: 
                   6574: sub CSTR_pageheader {
1.1407    raeburn  6575:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6576:     if ($trailfile eq '') {
                   6577:         $trailfile = $env{'request.filename'};
                   6578:     }
                   6579: 
                   6580: # this is for resources; directories have customtitle, and crumbs
                   6581: # and select recent are created in lonpubdir.pm
                   6582: 
                   6583:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6584:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6585:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6586:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6587:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6588: 
                   6589:     my $parentpath = '';
                   6590:     my $lastitem = '';
                   6591:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6592:         $parentpath = $1;
                   6593:         $lastitem = $2;
                   6594:     } else {
                   6595:         $lastitem = $thisdisfn;
                   6596:     }
1.921     bisitz   6597: 
1.1406    raeburn  6598:     my $crsauthor;
1.1246    raeburn  6599:     if (($env{'request.course.id'}) &&
                   6600:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6601:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6602:         $crsauthor = 1;
1.1406    raeburn  6603:         if ($title eq '') {
                   6604:             $title = &mt('Course Authoring Space');
                   6605:         }
                   6606:     } elsif ($title eq '') {
1.1246    raeburn  6607:         $title = &mt('Authoring Space');
                   6608:     }
                   6609: 
1.1379    raeburn  6610:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6611:     if ($frameset) {
                   6612:         $target = ' target="_parent"';
                   6613:         $crumbtarget = '_parent';
                   6614:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6615:         $target = '';
                   6616:         $crumbtarget = '';
1.1379    raeburn  6617:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6618:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6619:         $crumbtarget = $env{'request.deeplink.target'};
                   6620:     }
1.1313    raeburn  6621: 
1.921     bisitz   6622:     my $output =
1.1407    raeburn  6623:          '<div>'
1.822     bisitz   6624:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6625:         .'<b>'.$title.'</b> '
1.1314    raeburn  6626:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6627:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6628: 
                   6629:     if ($lastitem) {
                   6630:         $output .=
                   6631:              '<span class="LC_filename">'
                   6632:             .$lastitem
                   6633:             .'</span>';
                   6634:     }
1.1245    raeburn  6635: 
1.1246    raeburn  6636:     if ($crsauthor) {
1.1379    raeburn  6637:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6638:     } else {
                   6639:         $output .=
                   6640:              '<br />'
1.1314    raeburn  6641:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6642:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6643:             .'</form>'
1.1379    raeburn  6644:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6645:     }
1.1407    raeburn  6646:     $output .= '</div>';
1.921     bisitz   6647: 
                   6648:     return $output;
1.822     bisitz   6649: }
                   6650: 
1.1419    raeburn  6651: ##############################################
                   6652: =pod
                   6653: 
                   6654: =item * &nocodemirror()
                   6655: 
                   6656: Input: None
                   6657: 
                   6658: Returns: 1 if CodeMirror is deactivated based on
                   6659:          user's preference, or domain default,
                   6660:          if user indicated use of default.
                   6661: 
                   6662: =cut
                   6663: 
1.1416    raeburn  6664: sub nocodemirror {
                   6665:     my $nocodem = $env{'environment.nocodemirror'};
                   6666:     unless ($nocodem) {
                   6667:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6668:         if ($domdefs{'nocodemirror'}) {
                   6669:             $nocodem = 'yes';
                   6670:         }
                   6671:     }
1.1417    raeburn  6672:     if ($nocodem eq 'yes') {
                   6673:         return 1;
                   6674:     }
                   6675:     return;
1.1416    raeburn  6676: }
                   6677: 
1.1419    raeburn  6678: ##############################################
                   6679: =pod
                   6680: 
                   6681: =item * &permitted_editors()
                   6682: 
1.1422    raeburn  6683: Input: $uri (optional)
1.1419    raeburn  6684: 
                   6685: Returns: %editors hash in which keys are editors
1.1429    raeburn  6686:          permitted in current Authoring Space,
                   6687:          or in current course for web pages
                   6688:          created in a course.
                   6689: 
1.1419    raeburn  6690:          Value for each key is 1. Possible keys
1.1429    raeburn  6691:          are: edit, xml, and daxe.
                   6692: 
                   6693:          For a regular Authoring Space, if no specific
1.1419    raeburn  6694:          set of editors has been set for the Author
                   6695:          who owns the Authoring Space, then the
                   6696:          domain default will be used.  If no domain
                   6697:          default has been set, then the keys will be
                   6698:          edit and xml.
                   6699: 
1.1429    raeburn  6700:          For a course author, or for web pages created
                   6701:          in a course, if no specific set of editors has
                   6702:          been set for the course, then the domain
                   6703:          course default will be used. If no domain
                   6704:          course default has been set, then the keys
                   6705:          will be edit and xml.
                   6706: 
1.1419    raeburn  6707: =cut
                   6708: 
1.1418    raeburn  6709: sub permitted_editors {
1.1422    raeburn  6710:     my ($uri) = @_;
1.1429    raeburn  6711:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6712:     if ($env{'request.role'} =~ m{^au\./}) {
                   6713:         $is_author = 1;
                   6714:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6715:         ($audom,$auname) = ($1,$2);
                   6716:         if (($audom ne '') && ($auname ne '')) {
                   6717:             if (($env{'user.domain'} eq $audom) &&
                   6718:                 ($env{'user.name'} eq $auname)) {
                   6719:                 $is_author = 1;
                   6720:             } else {
                   6721:                 $is_coauthor = 1;
                   6722:             }
                   6723:         }
                   6724:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6725:         my ($cdom,$cnum);
                   6726:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6727:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6728:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6729:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6730:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6731:             $is_course = 1;
                   6732:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6733:             ($audom,$auname) = ($1,$2);
                   6734:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6735:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6736:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6737:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6738:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6739:             $is_course = 1;
                   6740:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6741:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6742:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6743:         }
1.1429    raeburn  6744:         unless ($is_course) {
                   6745:             if (($audom ne '') && ($auname ne '')) {
                   6746:                 if (($env{'user.domain'} eq $audom) &&
                   6747:                     ($env{'user.name'} eq $auname)) {
                   6748:                     $is_author = 1;
                   6749:                 } else {
                   6750:                     $is_coauthor = 1;
                   6751:                 }
1.1418    raeburn  6752:             }
                   6753:         }
                   6754:     }
                   6755:     if ($is_author) {
                   6756:         if (exists($env{'environment.editors'})) {
                   6757:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6758:         } else {
                   6759:             %editors = ( edit => 1,
                   6760:                          xml => 1,
                   6761:                        );
                   6762:         }
                   6763:     } elsif ($is_coauthor) {
                   6764:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6765:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6766:         } else {
                   6767:             %editors = ( edit => 1,
                   6768:                          xml => 1,
                   6769:                        );
                   6770:         }
1.1429    raeburn  6771:     } elsif ($is_course) {
                   6772:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6773:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6774:         } else {
                   6775:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6776:             if (exists($domdefaults{'crseditors'})) {
                   6777:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6778:             } else {
                   6779:                 %editors = ( edit => 1,
                   6780:                              xml => 1,
                   6781:                            );
                   6782:             }
                   6783:         }
1.1418    raeburn  6784:     } else {
                   6785:         %editors = ( edit => 1,
                   6786:                      xml => 1,
                   6787:                    );
                   6788:     }
                   6789:     return %editors;
                   6790: }
                   6791: 
1.60      matthew  6792: ###############################################
                   6793: ###############################################
                   6794: 
                   6795: =pod
                   6796: 
1.112     bowersj2 6797: =back
                   6798: 
1.549     albertel 6799: =head1 HTML Helpers
1.112     bowersj2 6800: 
                   6801: =over 4
                   6802: 
                   6803: =item * &bodytag()
1.60      matthew  6804: 
                   6805: Returns a uniform header for LON-CAPA web pages.
                   6806: 
                   6807: Inputs: 
                   6808: 
1.112     bowersj2 6809: =over 4
                   6810: 
                   6811: =item * $title, A title to be displayed on the page.
                   6812: 
                   6813: =item * $function, the current role (can be undef).
                   6814: 
                   6815: =item * $addentries, extra parameters for the <body> tag.
                   6816: 
                   6817: =item * $bodyonly, if defined, only return the <body> tag.
                   6818: 
                   6819: =item * $domain, if defined, force a given domain.
                   6820: 
                   6821: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6822:             text interface only)
1.60      matthew  6823: 
1.814     bisitz   6824: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6825:                      navigational links
1.317     albertel 6826: 
1.338     albertel 6827: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6828: 
1.460     albertel 6829: =item * $args, optional argument valid values are
                   6830:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6831:             use_absolute     -> for external resource or syllabus, this will
                   6832:                                 contain https://<hostname> if server uses
                   6833:                                 https (as per hosts.tab), but request is for http
                   6834:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6835: 
1.1096    raeburn  6836: =item * $advtoolsref, optional argument, ref to an array containing
                   6837:             inlineremote items to be added in "Functions" menu below
                   6838:             breadcrumbs.
                   6839: 
1.1316    raeburn  6840: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6841:             course, if LON-CAPA is in LTI Provider context. Value is
                   6842:             the scope of use, i.e., launch was for access to a single, a map
                   6843:             or the entire course.
                   6844: 
                   6845: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6846:             context, this will contain the URL for the landing item in
                   6847:             the course, after launch from an LTI Consumer
                   6848: 
1.1318    raeburn  6849: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6850:             context, this will contain a reference to hash of items
                   6851:             to be included in the page header and/or inline menu.
                   6852: 
1.1385    raeburn  6853: =item * $menucoll, optional argument, if specific menu collection is in
                   6854:             effect, either set as the default for the course, or set for
                   6855:             the deeplink paramater for $env{'request.deeplink.login'}
                   6856:             then $menucoll will be the number of that collection. 
                   6857: 
                   6858: =item * $menuref, optional argument, reference to a hash, containing the
                   6859:             menu options included for the menu in effect, based on the
                   6860:             configuration for the numbered menu collection in use.  
                   6861: 
                   6862: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6863:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6864:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6865:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6866:             being called a second time.
                   6867: 
1.112     bowersj2 6868: =back
                   6869: 
1.60      matthew  6870: Returns: A uniform header for LON-CAPA web pages.  
                   6871: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6872: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6873: other decorations will be returned.
                   6874: 
                   6875: =cut
                   6876: 
1.54      www      6877: sub bodytag {
1.831     bisitz   6878:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6879:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6880:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6881: 
1.954     raeburn  6882:     my $public;
                   6883:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6884:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6885:         $public = 1;
                   6886:     }
1.460     albertel 6887:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6888:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6889:     my $hostname = $args->{'hostname'};
1.339     albertel 6890: 
1.183     matthew  6891:     $function = &get_users_function() if (!$function);
1.339     albertel 6892:     my $font =   &designparm($function.'.font',$domain);
                   6893:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6894: 
1.803     bisitz   6895:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6896: 		   'bgcolor' => $pgbg,
1.339     albertel 6897: 		   'text'    => $font,
                   6898:                    'alink'   => &designparm($function.'.alink',$domain),
                   6899: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6900: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6901:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6902: 
1.63      www      6903:  # role and realm
1.1178    raeburn  6904:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6905:     if ($realm) {
                   6906:         $realm = '/'.$realm;
                   6907:     }
1.1357    raeburn  6908:     if ($role eq 'ca') {
1.479     albertel 6909:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6910:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6911:     } 
1.55      www      6912: # realm
1.1357    raeburn  6913:     my ($cid,$sec);
1.258     albertel 6914:     if ($env{'request.course.id'}) {
1.1357    raeburn  6915:         $cid = $env{'request.course.id'};
                   6916:         if ($env{'request.course.sec'}) {
                   6917:             $sec = $env{'request.course.sec'};
                   6918:         }
                   6919:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6920:         if (&Apache::lonnet::is_course($1,$2)) {
                   6921:             $cid = $1.'_'.$2;
                   6922:             $sec = $3;
                   6923:         }
                   6924:     }
                   6925:     if ($cid) {
1.378     raeburn  6926:         if ($env{'request.role'} !~ /^cr/) {
                   6927:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6928:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6929:             if ($env{'request.role.desc'}) {
                   6930:                 $role = $env{'request.role.desc'};
                   6931:             } else {
                   6932:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6933:             }
1.1257    raeburn  6934:         } else {
                   6935:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6936:         }
1.1357    raeburn  6937:         if ($sec) {
                   6938:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6939:         }   
1.1357    raeburn  6940: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6941:     } else {
                   6942:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6943:     }
1.433     albertel 6944: 
1.359     albertel 6945:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6946: 
1.438     albertel 6947:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6948: 
1.101     www      6949: # construct main body tag
1.359     albertel 6950:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6951: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6952: 
1.1131    raeburn  6953:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6954: 
1.1130    raeburn  6955:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6956:         return $bodytag;
1.1130    raeburn  6957:     }
1.359     albertel 6958: 
1.954     raeburn  6959:     if ($public) {
1.433     albertel 6960: 	undef($role);
                   6961:     }
1.1318    raeburn  6962: 
1.1359    raeburn  6963:     my $showcrstitle = 1;
1.1357    raeburn  6964:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6965:         if (ref($ltimenu) eq 'HASH') {
                   6966:             unless ($ltimenu->{'role'}) {
                   6967:                 undef($role);
                   6968:             }
                   6969:             unless ($ltimenu->{'coursetitle'}) {
                   6970:                 $realm='&nbsp;';
1.1359    raeburn  6971:                 $showcrstitle = 0;
                   6972:             }
                   6973:         }
                   6974:     } elsif (($cid) && ($menucoll)) {
                   6975:         if (ref($menuref) eq 'HASH') {
                   6976:             unless ($menuref->{'role'}) {
                   6977:                 undef($role);
                   6978:             }
                   6979:             unless ($menuref->{'crs'}) {
                   6980:                 $realm='&nbsp;';
                   6981:                 $showcrstitle = 0;
1.1318    raeburn  6982:             }
                   6983:         }
                   6984:     }
                   6985: 
1.762     bisitz   6986:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6987:     #
                   6988:     # Extra info if you are the DC
                   6989:     my $dc_info = '';
1.1359    raeburn  6990:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6991:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6992:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6993:         $dc_info =~ s/\s+$//;
1.359     albertel 6994:     }
                   6995: 
1.1237    raeburn  6996:     my $crstype;
1.1357    raeburn  6997:     if ($cid) {
                   6998:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6999:     } elsif ($args->{'crstype'}) {
                   7000:         $crstype = $args->{'crstype'};
                   7001:     }
                   7002:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   7003:         undef($role);
                   7004:     } else {
1.1242    raeburn  7005:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  7006:     }
1.853     droeschl 7007: 
1.903     droeschl 7008:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7009: 
                   7010:         #    if ($env{'request.state'} eq 'construct') {
                   7011:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7012:         #    }
                   7013: 
1.1440    raeburn  7014:         my $need_endlcint;
                   7015:         unless ($args->{'switchserver'}) {
                   7016:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7017:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7018:             $need_endlcint = 1;
                   7019:         }
1.359     albertel 7020: 
1.1427    raeburn  7021:         my $collapsible;
1.1423    raeburn  7022:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7023:             $collapsible = 1;
                   7024:             my ($menustate,$tiptext,$divclass);
                   7025:             if ($args->{'start_collapsed'}) {
                   7026:                 $menustate = 'collapsed';
                   7027:                 $tiptext = 'display';
                   7028:                 $divclass = 'hidden';
                   7029:             } else {
                   7030:                 $menustate = 'expanded';
                   7031:                 $tiptext = 'hide';
                   7032:                 $divclass = 'shown';
                   7033:             }
                   7034:             my $alttext = &mt('menu state: '.$menustate);
                   7035:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7036:             $bodytag .= <<"END";
                   7037: <div id="LC_expandingContainer" style="display:inline;">
                   7038: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7039: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   7040: <div class="LC_menus_content $divclass">
1.1421    raeburn  7041: END
                   7042:         }
1.1318    raeburn  7043:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7044:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7045:                                                               $args->{'links_disabled'},
1.1421    raeburn  7046:                                                               $args->{'links_target'},
1.1427    raeburn  7047:                                                               $collapsible);
1.359     albertel 7048: 
1.1318    raeburn  7049:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7050:                 if ($dc_info) {
                   7051:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7052:                 }
                   7053:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   7054:                                <em>$realm</em> $dc_info</div>|;
1.1440    raeburn  7055:                 if ($need_endlcint) {
                   7056:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7057:                 }
1.1318    raeburn  7058:                 return $bodytag;
                   7059:             }
1.894     droeschl 7060: 
1.1318    raeburn  7061:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7062:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7063:             }
1.916     droeschl 7064: 
1.1318    raeburn  7065:             $bodytag .= $right;
1.852     droeschl 7066: 
1.1318    raeburn  7067:             if ($dc_info) {
                   7068:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7069:             }
                   7070:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  7071:         }
1.916     droeschl 7072: 
1.1169    raeburn  7073:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7074:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7075:             if ($need_endlcint) {
                   7076:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7077:             }
1.1168    raeburn  7078:             return $bodytag;
                   7079:         }
1.1169    raeburn  7080:         #don't show menus for public users
1.954     raeburn  7081:         if (!$public){
1.1318    raeburn  7082:             unless ($args->{'no_inline_menu'}) {
                   7083:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7084:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7085:                                                             $menucoll,$menuref,
1.1380    raeburn  7086:                                                             $args->{'links_disabled'},
                   7087:                                                             $args->{'links_target'});
1.1318    raeburn  7088:             }
1.903     droeschl 7089:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7090:             if ($need_endlcint) {
                   7091:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7092:             }
1.920     raeburn  7093:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7094:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7095:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7096:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7097:             } elsif ($forcereg) {
                   7098:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7099:                                 $args->{'group'},$args->{'hide_buttons'},
                   7100:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7101:             } else {
                   7102:                 $bodytag .= 
                   7103:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7104:                                                         $forcereg,$args->{'group'},
                   7105:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7106:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7107:             }
1.1440    raeburn  7108:         } else {
                   7109:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7110:             # menu. Especially needed for publicly accessible resources.
1.903     droeschl 7111:             $bodytag .= '<hr style="clear:both" />';
1.1440    raeburn  7112:             if ($need_endlcint) {
                   7113:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7114:             }
1.235     raeburn  7115:         }
1.1423    raeburn  7116:         if ($args->{'collapsible_header'} ne '') {
                   7117:             $bodytag .= $args->{'collapsible_header'}.
                   7118:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7119:                         '</div></div>';
                   7120:         }
1.235     raeburn  7121:         return $bodytag;
1.182     matthew  7122: }
                   7123: 
1.917     raeburn  7124: sub dc_courseid_toggle {
                   7125:     my ($dc_info) = @_;
1.980     raeburn  7126:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7127:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7128:            &mt('(More ...)').'</a></span>'.
                   7129:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7130: }
                   7131: 
1.330     albertel 7132: sub make_attr_string {
                   7133:     my ($register,$attr_ref) = @_;
                   7134: 
                   7135:     if ($attr_ref && !ref($attr_ref)) {
                   7136: 	die("addentries Must be a hash ref ".
                   7137: 	    join(':',caller(1))." ".
                   7138: 	    join(':',caller(0))." ");
                   7139:     }
                   7140: 
                   7141:     if ($register) {
1.339     albertel 7142: 	my ($on_load,$on_unload);
                   7143: 	foreach my $key (keys(%{$attr_ref})) {
                   7144: 	    if      (lc($key) eq 'onload') {
                   7145: 		$on_load.=$attr_ref->{$key}.';';
                   7146: 		delete($attr_ref->{$key});
                   7147: 
                   7148: 	    } elsif (lc($key) eq 'onunload') {
                   7149: 		$on_unload.=$attr_ref->{$key}.';';
                   7150: 		delete($attr_ref->{$key});
                   7151: 	    }
                   7152: 	}
1.953     droeschl 7153: 	$attr_ref->{'onload'}  = $on_load;
                   7154: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7155:     }
1.339     albertel 7156: 
1.330     albertel 7157:     my $attr_string;
1.1159    raeburn  7158:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7159: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7160:     }
                   7161:     return $attr_string;
                   7162: }
                   7163: 
                   7164: 
1.182     matthew  7165: ###############################################
1.251     albertel 7166: ###############################################
                   7167: 
                   7168: =pod
                   7169: 
                   7170: =item * &endbodytag()
                   7171: 
                   7172: Returns a uniform footer for LON-CAPA web pages.
                   7173: 
1.635     raeburn  7174: Inputs: 1 - optional reference to an args hash
                   7175: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7176: a 'Continue' link is not displayed if the page contains an
                   7177: internal redirect in the <head></head> section,
                   7178: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7179: 
                   7180: =cut
                   7181: 
                   7182: sub endbodytag {
1.635     raeburn  7183:     my ($args) = @_;
1.1080    raeburn  7184:     my $endbodytag;
                   7185:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7186:         $endbodytag='</body>';
                   7187:     }
1.315     albertel 7188:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7189:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7190:             my ($endbodyjs,$idattr);
                   7191:             if ($env{'internal.head.to_opener'}) {
                   7192:                 my $linkid = 'LC_continue_link';
                   7193:                 $idattr = ' id="'.$linkid.'"';
                   7194:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7195:                 $endbodyjs=<<ENDJS;
                   7196: <script type="text/javascript">
                   7197: // <![CDATA[
                   7198: function ebFunction(evt) {
                   7199:     evt.preventDefault();
                   7200:     var dest = '$redirect_for_js';
                   7201:     if (window.opener != null && !window.opener.closed) {
                   7202:         window.opener.location.href=dest;
                   7203:         window.close();
                   7204:     } else {
                   7205:         window.location.href=dest;
                   7206:     }
                   7207:     return false;
                   7208: }
                   7209: 
                   7210: \$(document).ready(function () {
                   7211:   if (document.getElementById('$linkid')) {
                   7212:     var clickelem = document.getElementById('$linkid');
                   7213:     clickelem.addEventListener('click',ebFunction,false);
                   7214:   }
                   7215: });
                   7216: // ]]>
                   7217: </script>
                   7218: ENDJS
                   7219:             }
1.635     raeburn  7220: 	    $endbodytag=
1.1386    raeburn  7221: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7222: 	        &mt('Continue').'</a>'.
                   7223: 	        $endbodytag;
                   7224:         }
1.315     albertel 7225:     }
1.1411    raeburn  7226:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7227:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7228:     }
1.251     albertel 7229:     return $endbodytag;
                   7230: }
                   7231: 
1.352     albertel 7232: =pod
                   7233: 
                   7234: =item * &standard_css()
                   7235: 
                   7236: Returns a style sheet
                   7237: 
                   7238: Inputs: (all optional)
                   7239:             domain         -> force to color decorate a page for a specific
                   7240:                                domain
                   7241:             function       -> force usage of a specific rolish color scheme
                   7242:             bgcolor        -> override the default page bgcolor
                   7243: 
                   7244: =cut
                   7245: 
1.343     albertel 7246: sub standard_css {
1.345     albertel 7247:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7248:     $function  = &get_users_function() if (!$function);
                   7249:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7250:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7251:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7252: #second colour for later usage
1.345     albertel 7253:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7254:     my $pgbg_or_bgcolor =
                   7255: 	         $bgcolor ||
1.352     albertel 7256: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7257:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7258:     my $alink  = &designparm($function.'.alink', $domain);
                   7259:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7260:     my $link   = &designparm($function.'.link',  $domain);
                   7261: 
1.602     albertel 7262:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7263:     my $mono                 = 'monospace';
1.850     bisitz   7264:     my $data_table_head      = $sidebg;
                   7265:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7266:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7267:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7268:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7269:     my $mail_new             = '#FFBB77';
                   7270:     my $mail_new_hover       = '#DD9955';
                   7271:     my $mail_read            = '#BBBB77';
                   7272:     my $mail_read_hover      = '#999944';
                   7273:     my $mail_replied         = '#AAAA88';
                   7274:     my $mail_replied_hover   = '#888855';
                   7275:     my $mail_other           = '#99BBBB';
                   7276:     my $mail_other_hover     = '#669999';
1.391     albertel 7277:     my $table_header         = '#DDDDDD';
1.489     raeburn  7278:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7279:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7280:     my $button_hover         = '#BF2317';
1.392     albertel 7281: 
1.608     albertel 7282:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7283:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7284:                                              : '0 3px 0 4px';
1.448     albertel 7285: 
1.523     albertel 7286: 
1.343     albertel 7287:     return <<END;
1.947     droeschl 7288: 
                   7289: /* needed for iframe to allow 100% height in FF */
                   7290: body, html { 
                   7291:     margin: 0;
                   7292:     padding: 0 0.5%;
                   7293:     height: 99%; /* to avoid scrollbars */
                   7294: }
                   7295: 
1.795     www      7296: body {
1.911     bisitz   7297:   font-family: $sans;
                   7298:   line-height:130%;
                   7299:   font-size:0.83em;
                   7300:   color:$font;
1.1436    raeburn  7301:   background-color: $pgbg_or_bgcolor;
1.795     www      7302: }
                   7303: 
1.959     onken    7304: a:focus,
                   7305: a:focus img {
1.795     www      7306:   color: red;
                   7307: }
1.698     harmsja  7308: 
1.911     bisitz   7309: form, .inline {
                   7310:   display: inline;
1.795     www      7311: }
1.721     harmsja  7312: 
1.1443    raeburn  7313: .LC_visually_hidden:not(:focus):not(:active) {
                   7314:     clip-path: inset(50%);
                   7315:     height: 1px;
                   7316:     overflow: hidden;
                   7317:     position: absolute;
                   7318:     white-space: nowrap;
                   7319:     width: 1px;
                   7320:     display: inline;
                   7321: }
                   7322: 
1.1421    raeburn  7323: .LC_menus_content.shown{
1.1428    raeburn  7324:   display: block;
1.1421    raeburn  7325: }
                   7326: 
                   7327: .LC_menus_content.hidden {
                   7328:   display: none;
                   7329: }
                   7330: 
1.795     www      7331: .LC_right {
1.911     bisitz   7332:   text-align:right;
1.795     www      7333: }
                   7334: 
1.1449    raeburn  7335: .LC_center {
                   7336:   text-align:center;
                   7337: }
                   7338: 
1.795     www      7339: .LC_middle {
1.911     bisitz   7340:   vertical-align:middle;
1.795     www      7341: }
1.721     harmsja  7342: 
1.1130    raeburn  7343: .LC_floatleft {
                   7344:   float: left;
                   7345: }
                   7346: 
                   7347: .LC_floatright {
                   7348:   float: right;
                   7349: }
                   7350: 
1.911     bisitz   7351: .LC_400Box {
                   7352:   width:400px;
                   7353: }
1.721     harmsja  7354: 
1.1421    raeburn  7355: #LC_collapsible_separator {
                   7356:     border: 1px solid black;
                   7357:     width: 99.9%;
                   7358:     height: 0px;
                   7359: }
                   7360: 
1.947     droeschl 7361: .LC_iframecontainer {
                   7362:     width: 98%;
                   7363:     margin: 0;
                   7364:     position: fixed;
                   7365:     top: 8.5em;
                   7366:     bottom: 0;
                   7367: }
                   7368: 
                   7369: .LC_iframecontainer iframe{
                   7370:     border: none;
                   7371:     width: 100%;
                   7372:     height: 100%;
                   7373: }
                   7374: 
1.778     bisitz   7375: .LC_filename {
                   7376:   font-family: $mono;
                   7377:   white-space:pre;
1.921     bisitz   7378:   font-size: 120%;
1.778     bisitz   7379: }
                   7380: 
                   7381: .LC_fileicon {
                   7382:   border: none;
                   7383:   height: 1.3em;
                   7384:   vertical-align: text-bottom;
                   7385:   margin-right: 0.3em;
                   7386:   text-decoration:none;
                   7387: }
                   7388: 
1.1008    www      7389: .LC_setting {
                   7390:   text-decoration:underline;
                   7391: }
                   7392: 
1.350     albertel 7393: .LC_error {
                   7394:   color: red;
                   7395: }
1.795     www      7396: 
1.1097    bisitz   7397: .LC_warning {
                   7398:   color: darkorange;
                   7399: }
                   7400: 
1.457     albertel 7401: .LC_diff_removed {
1.733     bisitz   7402:   color: red;
1.394     albertel 7403: }
1.532     albertel 7404: 
                   7405: .LC_info,
1.457     albertel 7406: .LC_success,
                   7407: .LC_diff_added {
1.350     albertel 7408:   color: green;
                   7409: }
1.795     www      7410: 
1.802     bisitz   7411: div.LC_confirm_box {
                   7412:   background-color: #FAFAFA;
                   7413:   border: 1px solid $lg_border_color;
                   7414:   margin-right: 0;
                   7415:   padding: 5px;
                   7416: }
                   7417: 
                   7418: div.LC_confirm_box .LC_error img,
                   7419: div.LC_confirm_box .LC_success img {
                   7420:   vertical-align: middle;
                   7421: }
                   7422: 
1.1242    raeburn  7423: .LC_maxwidth {
                   7424:   max-width: 100%;
                   7425:   height: auto;
                   7426: }
                   7427: 
1.1243    raeburn  7428: .LC_textsize_mobile {
                   7429:   \@media only screen and (max-device-width: 480px) {
                   7430:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7431:   }
                   7432: }
                   7433: 
1.440     albertel 7434: .LC_icon {
1.771     droeschl 7435:   border: none;
1.790     droeschl 7436:   vertical-align: middle;
1.771     droeschl 7437: }
                   7438: 
1.543     albertel 7439: .LC_docs_spacer {
                   7440:   width: 25px;
                   7441:   height: 1px;
1.771     droeschl 7442:   border: none;
1.543     albertel 7443: }
1.346     albertel 7444: 
1.532     albertel 7445: .LC_internal_info {
1.735     bisitz   7446:   color: #999999;
1.532     albertel 7447: }
                   7448: 
1.794     www      7449: .LC_discussion {
1.1050    www      7450:   background: $data_table_dark;
1.911     bisitz   7451:   border: 1px solid black;
                   7452:   margin: 2px;
1.794     www      7453: }
                   7454: 
                   7455: .LC_disc_action_left {
1.1050    www      7456:   background: $sidebg;
1.911     bisitz   7457:   text-align: left;
1.1050    www      7458:   padding: 4px;
                   7459:   margin: 2px;
1.794     www      7460: }
                   7461: 
                   7462: .LC_disc_action_right {
1.1050    www      7463:   background: $sidebg;
1.911     bisitz   7464:   text-align: right;
1.1050    www      7465:   padding: 4px;
                   7466:   margin: 2px;
1.794     www      7467: }
                   7468: 
                   7469: .LC_disc_new_item {
1.911     bisitz   7470:   background: white;
                   7471:   border: 2px solid red;
1.1050    www      7472:   margin: 4px;
                   7473:   padding: 4px;
1.794     www      7474: }
                   7475: 
                   7476: .LC_disc_old_item {
1.911     bisitz   7477:   background: white;
1.1050    www      7478:   margin: 4px;
                   7479:   padding: 4px;
1.794     www      7480: }
                   7481: 
1.458     albertel 7482: table.LC_pastsubmission {
                   7483:   border: 1px solid black;
                   7484:   margin: 2px;
                   7485: }
                   7486: 
1.924     bisitz   7487: table#LC_menubuttons {
1.345     albertel 7488:   width: 100%;
                   7489:   background: $pgbg;
1.392     albertel 7490:   border: 2px;
1.402     albertel 7491:   border-collapse: separate;
1.803     bisitz   7492:   padding: 0;
1.345     albertel 7493: }
1.392     albertel 7494: 
1.801     tempelho 7495: table#LC_title_bar a {
                   7496:   color: $fontmenu;
                   7497: }
1.836     bisitz   7498: 
1.807     droeschl 7499: table#LC_title_bar {
1.819     tempelho 7500:   clear: both;
1.836     bisitz   7501:   display: none;
1.807     droeschl 7502: }
                   7503: 
1.795     www      7504: table#LC_title_bar,
1.933     droeschl 7505: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7506: table#LC_title_bar.LC_with_remote {
1.359     albertel 7507:   width: 100%;
1.392     albertel 7508:   border-color: $pgbg;
                   7509:   border-style: solid;
                   7510:   border-width: $border;
1.379     albertel 7511:   background: $pgbg;
1.801     tempelho 7512:   color: $fontmenu;
1.392     albertel 7513:   border-collapse: collapse;
1.803     bisitz   7514:   padding: 0;
1.819     tempelho 7515:   margin: 0;
1.359     albertel 7516: }
1.795     www      7517: 
1.933     droeschl 7518: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7519:     margin: 0;
                   7520:     padding: 0;
1.933     droeschl 7521:     position: relative;
                   7522:     list-style: none;
1.913     droeschl 7523: }
1.933     droeschl 7524: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7525:     display: inline;
                   7526: }
1.933     droeschl 7527: 
                   7528: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7529:     padding: 0;
1.933     droeschl 7530:     margin: 0;
                   7531:     float: left;
1.913     droeschl 7532: }
1.933     droeschl 7533: .LC_breadcrumb_tools_tools {
                   7534:     padding: 0;
                   7535:     margin: 0;
1.913     droeschl 7536:     float: right;
                   7537: }
                   7538: 
1.1240    raeburn  7539: .LC_placement_prog {
                   7540:     padding-right: 20px;
                   7541:     font-weight: bold;
                   7542:     font-size: 90%;
                   7543: }
                   7544: 
1.359     albertel 7545: table#LC_title_bar td {
                   7546:   background: $tabbg;
                   7547: }
1.795     www      7548: 
1.911     bisitz   7549: table#LC_menubuttons img {
1.803     bisitz   7550:   border: none;
1.346     albertel 7551: }
1.795     www      7552: 
1.842     droeschl 7553: .LC_breadcrumbs_component {
1.911     bisitz   7554:   float: right;
                   7555:   margin: 0 1em;
1.357     albertel 7556: }
1.842     droeschl 7557: .LC_breadcrumbs_component img {
1.911     bisitz   7558:   vertical-align: middle;
1.777     tempelho 7559: }
1.795     www      7560: 
1.1243    raeburn  7561: .LC_breadcrumbs_hoverable {
                   7562:   background: $sidebg;
                   7563: }
                   7564: 
1.383     albertel 7565: td.LC_table_cell_checkbox {
                   7566:   text-align: center;
                   7567: }
1.795     www      7568: 
                   7569: .LC_fontsize_small {
1.911     bisitz   7570:   font-size: 70%;
1.705     tempelho 7571: }
                   7572: 
1.844     bisitz   7573: #LC_breadcrumbs {
1.911     bisitz   7574:   clear:both;
                   7575:   background: $sidebg;
                   7576:   border-bottom: 1px solid $lg_border_color;
                   7577:   line-height: 2.5em;
1.933     droeschl 7578:   overflow: hidden;
1.911     bisitz   7579:   margin: 0;
                   7580:   padding: 0;
1.995     raeburn  7581:   text-align: left;
1.819     tempelho 7582: }
1.862     bisitz   7583: 
1.1098    bisitz   7584: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7585:   clear:both;
                   7586:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7587:   border: 1px solid $sidebg;
1.1098    bisitz   7588:   margin: 0 0 10px 0;
1.966     bisitz   7589:   padding: 3px;
1.995     raeburn  7590:   text-align: left;
1.822     bisitz   7591: }
                   7592: 
1.795     www      7593: .LC_fontsize_medium {
1.911     bisitz   7594:   font-size: 85%;
1.705     tempelho 7595: }
                   7596: 
1.795     www      7597: .LC_fontsize_large {
1.911     bisitz   7598:   font-size: 120%;
1.705     tempelho 7599: }
                   7600: 
1.346     albertel 7601: .LC_menubuttons_inline_text {
                   7602:   color: $font;
1.698     harmsja  7603:   font-size: 90%;
1.701     harmsja  7604:   padding-left:3px;
1.346     albertel 7605: }
                   7606: 
1.934     droeschl 7607: .LC_menubuttons_inline_text img{
                   7608:   vertical-align: middle;
                   7609: }
                   7610: 
1.1051    www      7611: li.LC_menubuttons_inline_text img {
1.951     onken    7612:   cursor:pointer;
1.1002    droeschl 7613:   text-decoration: none;
1.951     onken    7614: }
                   7615: 
1.526     www      7616: .LC_menubuttons_link {
                   7617:   text-decoration: none;
                   7618: }
1.795     www      7619: 
1.522     albertel 7620: .LC_menubuttons_category {
1.521     www      7621:   color: $font;
1.526     www      7622:   background: $pgbg;
1.521     www      7623:   font-size: larger;
                   7624:   font-weight: bold;
                   7625: }
                   7626: 
1.346     albertel 7627: td.LC_menubuttons_text {
1.911     bisitz   7628:   color: $font;
1.346     albertel 7629: }
1.706     harmsja  7630: 
1.346     albertel 7631: .LC_current_location {
                   7632:   background: $tabbg;
                   7633: }
1.795     www      7634: 
1.1286    raeburn  7635: td.LC_zero_height {
                   7636:   line-height: 0; 
                   7637:   cellpadding: 0;
                   7638: }
                   7639: 
1.938     bisitz   7640: table.LC_data_table {
1.347     albertel 7641:   border: 1px solid #000000;
1.402     albertel 7642:   border-collapse: separate;
1.426     albertel 7643:   border-spacing: 1px;
1.610     albertel 7644:   background: $pgbg;
1.347     albertel 7645: }
1.795     www      7646: 
1.422     albertel 7647: .LC_data_table_dense {
                   7648:   font-size: small;
                   7649: }
1.795     www      7650: 
1.507     raeburn  7651: table.LC_nested_outer {
                   7652:   border: 1px solid #000000;
1.589     raeburn  7653:   border-collapse: collapse;
1.803     bisitz   7654:   border-spacing: 0;
1.507     raeburn  7655:   width: 100%;
                   7656: }
1.795     www      7657: 
1.879     raeburn  7658: table.LC_innerpickbox,
1.507     raeburn  7659: table.LC_nested {
1.803     bisitz   7660:   border: none;
1.589     raeburn  7661:   border-collapse: collapse;
1.803     bisitz   7662:   border-spacing: 0;
1.507     raeburn  7663:   width: 100%;
                   7664: }
1.795     www      7665: 
1.911     bisitz   7666: table.LC_data_table tr th,
                   7667: table.LC_calendar tr th,
1.879     raeburn  7668: table.LC_prior_tries tr th,
                   7669: table.LC_innerpickbox tr th {
1.349     albertel 7670:   font-weight: bold;
                   7671:   background-color: $data_table_head;
1.801     tempelho 7672:   color:$fontmenu;
1.701     harmsja  7673:   font-size:90%;
1.347     albertel 7674: }
1.795     www      7675: 
1.879     raeburn  7676: table.LC_innerpickbox tr th,
                   7677: table.LC_innerpickbox tr td {
                   7678:   vertical-align: top;
                   7679: }
                   7680: 
1.711     raeburn  7681: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7682:   background-color: #CCCCCC;
1.711     raeburn  7683:   font-weight: bold;
                   7684:   text-align: left;
                   7685: }
1.795     www      7686: 
1.912     bisitz   7687: table.LC_data_table tr.LC_odd_row > td {
                   7688:   background-color: $data_table_light;
                   7689:   padding: 2px;
                   7690:   vertical-align: top;
                   7691: }
                   7692: 
1.809     bisitz   7693: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7694:   background-color: $data_table_light;
1.912     bisitz   7695:   vertical-align: top;
                   7696: }
                   7697: 
                   7698: table.LC_data_table tr.LC_even_row > td {
                   7699:   background-color: $data_table_dark;
1.425     albertel 7700:   padding: 2px;
1.900     bisitz   7701:   vertical-align: top;
1.347     albertel 7702: }
1.795     www      7703: 
1.809     bisitz   7704: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7705:   background-color: $data_table_dark;
1.900     bisitz   7706:   vertical-align: top;
1.347     albertel 7707: }
1.795     www      7708: 
1.425     albertel 7709: table.LC_data_table tr.LC_data_table_highlight td {
                   7710:   background-color: $data_table_darker;
                   7711: }
1.795     www      7712: 
1.639     raeburn  7713: table.LC_data_table tr td.LC_leftcol_header {
                   7714:   background-color: $data_table_head;
                   7715:   font-weight: bold;
                   7716: }
1.795     www      7717: 
1.451     albertel 7718: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7719: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7720:   font-weight: bold;
                   7721:   font-style: italic;
                   7722:   text-align: center;
                   7723:   padding: 8px;
1.347     albertel 7724: }
1.795     www      7725: 
1.1114    raeburn  7726: table.LC_data_table tr.LC_empty_row td,
                   7727: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7728:   background-color: $sidebg;
                   7729: }
                   7730: 
                   7731: table.LC_nested tr.LC_empty_row td {
                   7732:   background-color: #FFFFFF;
                   7733: }
                   7734: 
1.890     droeschl 7735: table.LC_caption {
                   7736: }
                   7737: 
1.507     raeburn  7738: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7739:   padding: 4ex
                   7740: }
1.795     www      7741: 
1.507     raeburn  7742: table.LC_nested_outer tr th {
                   7743:   font-weight: bold;
1.801     tempelho 7744:   color:$fontmenu;
1.507     raeburn  7745:   background-color: $data_table_head;
1.701     harmsja  7746:   font-size: small;
1.507     raeburn  7747:   border-bottom: 1px solid #000000;
                   7748: }
1.795     www      7749: 
1.507     raeburn  7750: table.LC_nested_outer tr td.LC_subheader {
                   7751:   background-color: $data_table_head;
                   7752:   font-weight: bold;
                   7753:   font-size: small;
                   7754:   border-bottom: 1px solid #000000;
                   7755:   text-align: right;
1.451     albertel 7756: }
1.795     www      7757: 
1.507     raeburn  7758: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7759:   background-color: #CCCCCC;
1.451     albertel 7760:   font-weight: bold;
                   7761:   font-size: small;
1.507     raeburn  7762:   text-align: center;
                   7763: }
1.795     www      7764: 
1.589     raeburn  7765: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7766: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7767:   text-align: left;
1.451     albertel 7768: }
1.795     www      7769: 
1.507     raeburn  7770: table.LC_nested td {
1.735     bisitz   7771:   background-color: #FFFFFF;
1.451     albertel 7772:   font-size: small;
1.507     raeburn  7773: }
1.795     www      7774: 
1.507     raeburn  7775: table.LC_nested_outer tr th.LC_right_item,
                   7776: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7777: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7778: table.LC_nested tr td.LC_right_item {
1.451     albertel 7779:   text-align: right;
                   7780: }
                   7781: 
1.507     raeburn  7782: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7783:   background-color: #EEEEEE;
1.451     albertel 7784: }
                   7785: 
1.473     raeburn  7786: table.LC_createuser {
                   7787: }
                   7788: 
                   7789: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7790:   font-size: small;
1.473     raeburn  7791: }
                   7792: 
                   7793: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7794:   background-color: #CCCCCC;
1.473     raeburn  7795:   font-weight: bold;
                   7796:   text-align: center;
                   7797: }
                   7798: 
1.349     albertel 7799: table.LC_calendar {
                   7800:   border: 1px solid #000000;
                   7801:   border-collapse: collapse;
1.917     raeburn  7802:   width: 98%;
1.349     albertel 7803: }
1.795     www      7804: 
1.349     albertel 7805: table.LC_calendar_pickdate {
                   7806:   font-size: xx-small;
                   7807: }
1.795     www      7808: 
1.349     albertel 7809: table.LC_calendar tr td {
                   7810:   border: 1px solid #000000;
                   7811:   vertical-align: top;
1.917     raeburn  7812:   width: 14%;
1.349     albertel 7813: }
1.795     www      7814: 
1.349     albertel 7815: table.LC_calendar tr td.LC_calendar_day_empty {
                   7816:   background-color: $data_table_dark;
                   7817: }
1.795     www      7818: 
1.779     bisitz   7819: table.LC_calendar tr td.LC_calendar_day_current {
                   7820:   background-color: $data_table_highlight;
1.777     tempelho 7821: }
1.795     www      7822: 
1.938     bisitz   7823: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7824:   background-color: $mail_new;
                   7825: }
1.795     www      7826: 
1.938     bisitz   7827: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7828:   background-color: $mail_new_hover;
                   7829: }
1.795     www      7830: 
1.938     bisitz   7831: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7832:   background-color: $mail_read;
                   7833: }
1.795     www      7834: 
1.938     bisitz   7835: /*
                   7836: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7837:   background-color: $mail_read_hover;
                   7838: }
1.938     bisitz   7839: */
1.795     www      7840: 
1.938     bisitz   7841: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7842:   background-color: $mail_replied;
                   7843: }
1.795     www      7844: 
1.938     bisitz   7845: /*
                   7846: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7847:   background-color: $mail_replied_hover;
                   7848: }
1.938     bisitz   7849: */
1.795     www      7850: 
1.938     bisitz   7851: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7852:   background-color: $mail_other;
                   7853: }
1.795     www      7854: 
1.938     bisitz   7855: /*
                   7856: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7857:   background-color: $mail_other_hover;
                   7858: }
1.938     bisitz   7859: */
1.494     raeburn  7860: 
1.777     tempelho 7861: table.LC_data_table tr > td.LC_browser_file,
                   7862: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7863:   background: #AAEE77;
1.389     albertel 7864: }
1.795     www      7865: 
1.777     tempelho 7866: table.LC_data_table tr > td.LC_browser_file_locked,
                   7867: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7868:   background: #FFAA99;
1.387     albertel 7869: }
1.795     www      7870: 
1.777     tempelho 7871: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7872:   background: #888888;
1.779     bisitz   7873: }
1.795     www      7874: 
1.777     tempelho 7875: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7876: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7877:   background: #F8F866;
1.777     tempelho 7878: }
1.795     www      7879: 
1.696     bisitz   7880: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7881:   background: #E0E8FF;
1.387     albertel 7882: }
1.696     bisitz   7883: 
1.707     bisitz   7884: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7885:   /* background: #77FF77; */
1.707     bisitz   7886: }
1.795     www      7887: 
1.707     bisitz   7888: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7889:   border-right: 8px solid #FFFF77;
1.707     bisitz   7890: }
1.795     www      7891: 
1.707     bisitz   7892: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7893:   border-right: 8px solid #FFAA77;
1.707     bisitz   7894: }
1.795     www      7895: 
1.707     bisitz   7896: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7897:   border-right: 8px solid #FF7777;
1.707     bisitz   7898: }
1.795     www      7899: 
1.707     bisitz   7900: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7901:   border-right: 8px solid #AAFF77;
1.707     bisitz   7902: }
1.795     www      7903: 
1.707     bisitz   7904: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7905:   border-right: 8px solid #11CC55;
1.707     bisitz   7906: }
                   7907: 
1.388     albertel 7908: span.LC_current_location {
1.701     harmsja  7909:   font-size:larger;
1.388     albertel 7910:   background: $pgbg;
                   7911: }
1.387     albertel 7912: 
1.1029    www      7913: span.LC_current_nav_location {
                   7914:   font-weight:bold;
                   7915:   background: $sidebg;
                   7916: }
                   7917: 
1.395     albertel 7918: span.LC_parm_menu_item {
                   7919:   font-size: larger;
                   7920: }
1.795     www      7921: 
1.395     albertel 7922: span.LC_parm_scope_all {
                   7923:   color: red;
                   7924: }
1.795     www      7925: 
1.395     albertel 7926: span.LC_parm_scope_folder {
                   7927:   color: green;
                   7928: }
1.795     www      7929: 
1.395     albertel 7930: span.LC_parm_scope_resource {
                   7931:   color: orange;
                   7932: }
1.795     www      7933: 
1.395     albertel 7934: span.LC_parm_part {
                   7935:   color: blue;
                   7936: }
1.795     www      7937: 
1.911     bisitz   7938: span.LC_parm_folder,
                   7939: span.LC_parm_symb {
1.395     albertel 7940:   font-size: x-small;
                   7941:   font-family: $mono;
                   7942:   color: #AAAAAA;
                   7943: }
                   7944: 
1.977     bisitz   7945: ul.LC_parm_parmlist li {
                   7946:   display: inline-block;
                   7947:   padding: 0.3em 0.8em;
                   7948:   vertical-align: top;
                   7949:   width: 150px;
                   7950:   border-top:1px solid $lg_border_color;
                   7951: }
                   7952: 
1.795     www      7953: td.LC_parm_overview_level_menu,
                   7954: td.LC_parm_overview_map_menu,
                   7955: td.LC_parm_overview_parm_selectors,
                   7956: td.LC_parm_overview_restrictions  {
1.396     albertel 7957:   border: 1px solid black;
                   7958:   border-collapse: collapse;
                   7959: }
1.795     www      7960: 
1.1285    raeburn  7961: span.LC_parm_recursive,
                   7962: td.LC_parm_recursive {
                   7963:   font-weight: bold;
                   7964:   font-size: smaller;
                   7965: }
                   7966: 
1.396     albertel 7967: table.LC_parm_overview_restrictions td {
                   7968:   border-width: 1px 4px 1px 4px;
                   7969:   border-style: solid;
                   7970:   border-color: $pgbg;
                   7971:   text-align: center;
                   7972: }
1.795     www      7973: 
1.396     albertel 7974: table.LC_parm_overview_restrictions th {
                   7975:   background: $tabbg;
                   7976:   border-width: 1px 4px 1px 4px;
                   7977:   border-style: solid;
                   7978:   border-color: $pgbg;
                   7979: }
1.795     www      7980: 
1.398     albertel 7981: table#LC_helpmenu {
1.803     bisitz   7982:   border: none;
1.398     albertel 7983:   height: 55px;
1.803     bisitz   7984:   border-spacing: 0;
1.398     albertel 7985: }
                   7986: 
                   7987: table#LC_helpmenu fieldset legend {
                   7988:   font-size: larger;
                   7989: }
1.795     www      7990: 
1.397     albertel 7991: table#LC_helpmenu_links {
                   7992:   width: 100%;
                   7993:   border: 1px solid black;
                   7994:   background: $pgbg;
1.803     bisitz   7995:   padding: 0;
1.397     albertel 7996:   border-spacing: 1px;
                   7997: }
1.795     www      7998: 
1.397     albertel 7999: table#LC_helpmenu_links tr td {
                   8000:   padding: 1px;
                   8001:   background: $tabbg;
1.399     albertel 8002:   text-align: center;
                   8003:   font-weight: bold;
1.397     albertel 8004: }
1.396     albertel 8005: 
1.795     www      8006: table#LC_helpmenu_links a:link,
                   8007: table#LC_helpmenu_links a:visited,
1.397     albertel 8008: table#LC_helpmenu_links a:active {
                   8009:   text-decoration: none;
                   8010:   color: $font;
                   8011: }
1.795     www      8012: 
1.397     albertel 8013: table#LC_helpmenu_links a:hover {
                   8014:   text-decoration: underline;
                   8015:   color: $vlink;
                   8016: }
1.396     albertel 8017: 
1.417     albertel 8018: .LC_chrt_popup_exists {
                   8019:   border: 1px solid #339933;
                   8020:   margin: -1px;
                   8021: }
1.795     www      8022: 
1.417     albertel 8023: .LC_chrt_popup_up {
                   8024:   border: 1px solid yellow;
                   8025:   margin: -1px;
                   8026: }
1.795     www      8027: 
1.417     albertel 8028: .LC_chrt_popup {
                   8029:   border: 1px solid #8888FF;
                   8030:   background: #CCCCFF;
                   8031: }
1.795     www      8032: 
1.421     albertel 8033: table.LC_pick_box {
                   8034:   border-collapse: separate;
                   8035:   background: white;
                   8036:   border: 1px solid black;
                   8037:   border-spacing: 1px;
                   8038: }
1.795     www      8039: 
1.421     albertel 8040: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   8041:   background: $sidebg;
1.421     albertel 8042:   font-weight: bold;
1.900     bisitz   8043:   text-align: left;
1.740     bisitz   8044:   vertical-align: top;
1.421     albertel 8045:   width: 184px;
                   8046:   padding: 8px;
                   8047: }
1.795     www      8048: 
1.579     raeburn  8049: table.LC_pick_box td.LC_pick_box_value {
                   8050:   text-align: left;
                   8051:   padding: 8px;
                   8052: }
1.795     www      8053: 
1.579     raeburn  8054: table.LC_pick_box td.LC_pick_box_select {
                   8055:   text-align: left;
                   8056:   padding: 8px;
                   8057: }
1.795     www      8058: 
1.424     albertel 8059: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8060:   padding: 0;
1.421     albertel 8061:   height: 1px;
                   8062:   background: black;
                   8063: }
1.795     www      8064: 
1.421     albertel 8065: table.LC_pick_box td.LC_pick_box_submit {
                   8066:   text-align: right;
                   8067: }
1.795     www      8068: 
1.579     raeburn  8069: table.LC_pick_box td.LC_evenrow_value {
                   8070:   text-align: left;
                   8071:   padding: 8px;
                   8072:   background-color: $data_table_light;
                   8073: }
1.795     www      8074: 
1.579     raeburn  8075: table.LC_pick_box td.LC_oddrow_value {
                   8076:   text-align: left;
                   8077:   padding: 8px;
                   8078:   background-color: $data_table_light;
                   8079: }
1.795     www      8080: 
1.579     raeburn  8081: span.LC_helpform_receipt_cat {
                   8082:   font-weight: bold;
                   8083: }
1.795     www      8084: 
1.424     albertel 8085: table.LC_group_priv_box {
                   8086:   background: white;
                   8087:   border: 1px solid black;
                   8088:   border-spacing: 1px;
                   8089: }
1.795     www      8090: 
1.424     albertel 8091: table.LC_group_priv_box td.LC_pick_box_title {
                   8092:   background: $tabbg;
                   8093:   font-weight: bold;
                   8094:   text-align: right;
                   8095:   width: 184px;
                   8096: }
1.795     www      8097: 
1.424     albertel 8098: table.LC_group_priv_box td.LC_groups_fixed {
                   8099:   background: $data_table_light;
                   8100:   text-align: center;
                   8101: }
1.795     www      8102: 
1.424     albertel 8103: table.LC_group_priv_box td.LC_groups_optional {
                   8104:   background: $data_table_dark;
                   8105:   text-align: center;
                   8106: }
1.795     www      8107: 
1.424     albertel 8108: table.LC_group_priv_box td.LC_groups_functionality {
                   8109:   background: $data_table_darker;
                   8110:   text-align: center;
                   8111:   font-weight: bold;
                   8112: }
1.795     www      8113: 
1.424     albertel 8114: table.LC_group_priv td {
                   8115:   text-align: left;
1.803     bisitz   8116:   padding: 0;
1.424     albertel 8117: }
                   8118: 
                   8119: .LC_navbuttons {
                   8120:   margin: 2ex 0ex 2ex 0ex;
                   8121: }
1.795     www      8122: 
1.423     albertel 8123: .LC_topic_bar {
                   8124:   font-weight: bold;
                   8125:   background: $tabbg;
1.918     wenzelju 8126:   margin: 1em 0em 1em 2em;
1.805     bisitz   8127:   padding: 3px;
1.918     wenzelju 8128:   font-size: 1.2em;
1.423     albertel 8129: }
1.795     www      8130: 
1.423     albertel 8131: .LC_topic_bar span {
1.918     wenzelju 8132:   left: 0.5em;
                   8133:   position: absolute;
1.423     albertel 8134:   vertical-align: middle;
1.918     wenzelju 8135:   font-size: 1.2em;
1.423     albertel 8136: }
1.795     www      8137: 
1.423     albertel 8138: table.LC_course_group_status {
                   8139:   margin: 20px;
                   8140: }
1.795     www      8141: 
1.423     albertel 8142: table.LC_status_selector td {
                   8143:   vertical-align: top;
                   8144:   text-align: center;
1.424     albertel 8145:   padding: 4px;
                   8146: }
1.795     www      8147: 
1.599     albertel 8148: div.LC_feedback_link {
1.616     albertel 8149:   clear: both;
1.829     kalberla 8150:   background: $sidebg;
1.779     bisitz   8151:   width: 100%;
1.829     kalberla 8152:   padding-bottom: 10px;
                   8153:   border: 1px $tabbg solid;
1.833     kalberla 8154:   height: 22px;
                   8155:   line-height: 22px;
                   8156:   padding-top: 5px;
                   8157: }
                   8158: 
                   8159: div.LC_feedback_link img {
                   8160:   height: 22px;
1.867     kalberla 8161:   vertical-align:middle;
1.829     kalberla 8162: }
                   8163: 
1.911     bisitz   8164: div.LC_feedback_link a {
1.829     kalberla 8165:   text-decoration: none;
1.489     raeburn  8166: }
1.795     www      8167: 
1.867     kalberla 8168: div.LC_comblock {
1.911     bisitz   8169:   display:inline;
1.867     kalberla 8170:   color:$font;
                   8171:   font-size:90%;
                   8172: }
                   8173: 
                   8174: div.LC_feedback_link div.LC_comblock {
                   8175:   padding-left:5px;
                   8176: }
                   8177: 
                   8178: div.LC_feedback_link div.LC_comblock a {
                   8179:   color:$font;
                   8180: }
                   8181: 
1.489     raeburn  8182: span.LC_feedback_link {
1.858     bisitz   8183:   /* background: $feedback_link_bg; */
1.599     albertel 8184:   font-size: larger;
                   8185: }
1.795     www      8186: 
1.599     albertel 8187: span.LC_message_link {
1.858     bisitz   8188:   /* background: $feedback_link_bg; */
1.599     albertel 8189:   font-size: larger;
                   8190:   position: absolute;
                   8191:   right: 1em;
1.489     raeburn  8192: }
1.421     albertel 8193: 
1.515     albertel 8194: table.LC_prior_tries {
1.524     albertel 8195:   border: 1px solid #000000;
                   8196:   border-collapse: separate;
                   8197:   border-spacing: 1px;
1.515     albertel 8198: }
1.523     albertel 8199: 
1.515     albertel 8200: table.LC_prior_tries td {
1.524     albertel 8201:   padding: 2px;
1.515     albertel 8202: }
1.523     albertel 8203: 
                   8204: .LC_answer_correct {
1.795     www      8205:   background: lightgreen;
                   8206:   color: darkgreen;
                   8207:   padding: 6px;
1.523     albertel 8208: }
1.795     www      8209: 
1.523     albertel 8210: .LC_answer_charged_try {
1.797     www      8211:   background: #FFAAAA;
1.795     www      8212:   color: darkred;
                   8213:   padding: 6px;
1.523     albertel 8214: }
1.795     www      8215: 
1.779     bisitz   8216: .LC_answer_not_charged_try,
1.523     albertel 8217: .LC_answer_no_grade,
                   8218: .LC_answer_late {
1.795     www      8219:   background: lightyellow;
1.523     albertel 8220:   color: black;
1.795     www      8221:   padding: 6px;
1.523     albertel 8222: }
1.795     www      8223: 
1.523     albertel 8224: .LC_answer_previous {
1.795     www      8225:   background: lightblue;
                   8226:   color: darkblue;
                   8227:   padding: 6px;
1.523     albertel 8228: }
1.795     www      8229: 
1.779     bisitz   8230: .LC_answer_no_message {
1.777     tempelho 8231:   background: #FFFFFF;
                   8232:   color: black;
1.795     www      8233:   padding: 6px;
1.779     bisitz   8234: }
1.795     www      8235: 
1.1334    raeburn  8236: .LC_answer_unknown,
                   8237: .LC_answer_warning {
1.779     bisitz   8238:   background: orange;
                   8239:   color: black;
1.795     www      8240:   padding: 6px;
1.777     tempelho 8241: }
1.795     www      8242: 
1.1446    raeburn  8243: .LC_prob_status {
1.1447    raeburn  8244:   margin-top: 5px;
1.1446    raeburn  8245:   padding-top: 0;
                   8246:   padding-left: 0;
                   8247:   padding-bottom: 0;
                   8248:   padding-right: 5px;
                   8249: }
                   8250: 
1.1448    raeburn  8251: .LC_mail_actions {
                   8252:   float: left;
                   8253:   padding: 0;
                   8254:   margin: 6px;
                   8255: }
                   8256: 
                   8257: .LC_vertical_line {
                   8258:   width: 1px;
                   8259:   background-color: black;
                   8260:   height: 4em;
                   8261:   float: left;
                   8262:   margin: 0;
                   8263:   padding: 0;
                   8264: }
                   8265: 
1.529     albertel 8266: span.LC_prior_numerical,
                   8267: span.LC_prior_string,
                   8268: span.LC_prior_custom,
                   8269: span.LC_prior_reaction,
                   8270: span.LC_prior_math {
1.925     bisitz   8271:   font-family: $mono;
1.523     albertel 8272:   white-space: pre;
                   8273: }
                   8274: 
1.525     albertel 8275: span.LC_prior_string {
1.925     bisitz   8276:   font-family: $mono;
1.525     albertel 8277:   white-space: pre;
                   8278: }
                   8279: 
1.523     albertel 8280: table.LC_prior_option {
                   8281:   width: 100%;
                   8282:   border-collapse: collapse;
                   8283: }
1.795     www      8284: 
1.911     bisitz   8285: table.LC_prior_rank,
1.795     www      8286: table.LC_prior_match {
1.528     albertel 8287:   border-collapse: collapse;
                   8288: }
1.795     www      8289: 
1.528     albertel 8290: table.LC_prior_option tr td,
                   8291: table.LC_prior_rank tr td,
                   8292: table.LC_prior_match tr td {
1.524     albertel 8293:   border: 1px solid #000000;
1.515     albertel 8294: }
                   8295: 
1.855     bisitz   8296: .LC_nobreak {
1.544     albertel 8297:   white-space: nowrap;
1.519     raeburn  8298: }
                   8299: 
1.576     raeburn  8300: span.LC_cusr_emph {
                   8301:   font-style: italic;
                   8302: }
                   8303: 
1.633     raeburn  8304: span.LC_cusr_subheading {
                   8305:   font-weight: normal;
                   8306:   font-size: 85%;
                   8307: }
                   8308: 
1.861     bisitz   8309: div.LC_docs_entry_move {
1.859     bisitz   8310:   border: 1px solid #BBBBBB;
1.545     albertel 8311:   background: #DDDDDD;
1.861     bisitz   8312:   width: 22px;
1.859     bisitz   8313:   padding: 1px;
                   8314:   margin: 0;
1.545     albertel 8315: }
                   8316: 
1.861     bisitz   8317: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8318: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8319:   font-size: x-small;
                   8320: }
1.795     www      8321: 
1.861     bisitz   8322: .LC_docs_entry_parameter {
                   8323:   white-space: nowrap;
                   8324: }
                   8325: 
1.544     albertel 8326: .LC_docs_copy {
1.545     albertel 8327:   color: #000099;
1.544     albertel 8328: }
1.795     www      8329: 
1.544     albertel 8330: .LC_docs_cut {
1.545     albertel 8331:   color: #550044;
1.544     albertel 8332: }
1.795     www      8333: 
1.544     albertel 8334: .LC_docs_rename {
1.545     albertel 8335:   color: #009900;
1.544     albertel 8336: }
1.795     www      8337: 
1.544     albertel 8338: .LC_docs_remove {
1.545     albertel 8339:   color: #990000;
                   8340: }
                   8341: 
1.1284    raeburn  8342: .LC_docs_alias {
                   8343:   color: #440055;  
                   8344: }
                   8345: 
1.1286    raeburn  8346: .LC_domprefs_email,
1.1284    raeburn  8347: .LC_docs_alias_name,
1.547     albertel 8348: .LC_docs_reinit_warn,
                   8349: .LC_docs_ext_edit {
                   8350:   font-size: x-small;
                   8351: }
                   8352: 
1.545     albertel 8353: table.LC_docs_adddocs td,
                   8354: table.LC_docs_adddocs th {
                   8355:   border: 1px solid #BBBBBB;
                   8356:   padding: 4px;
                   8357:   background: #DDDDDD;
1.543     albertel 8358: }
                   8359: 
1.584     albertel 8360: table.LC_sty_begin {
                   8361:   background: #BBFFBB;
                   8362: }
1.795     www      8363: 
1.584     albertel 8364: table.LC_sty_end {
                   8365:   background: #FFBBBB;
                   8366: }
                   8367: 
1.589     raeburn  8368: table.LC_double_column {
1.803     bisitz   8369:   border-width: 0;
1.589     raeburn  8370:   border-collapse: collapse;
                   8371:   width: 100%;
                   8372:   padding: 2px;
                   8373: }
                   8374: 
                   8375: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8376:   top: 2px;
1.589     raeburn  8377:   left: 2px;
                   8378:   width: 47%;
                   8379:   vertical-align: top;
                   8380: }
                   8381: 
                   8382: table.LC_double_column tr td.LC_right_col {
                   8383:   top: 2px;
1.779     bisitz   8384:   right: 2px;
1.589     raeburn  8385:   width: 47%;
                   8386:   vertical-align: top;
                   8387: }
                   8388: 
1.591     raeburn  8389: div.LC_left_float {
                   8390:   float: left;
                   8391:   padding-right: 5%;
1.597     albertel 8392:   padding-bottom: 4px;
1.591     raeburn  8393: }
                   8394: 
                   8395: div.LC_clear_float_header {
1.597     albertel 8396:   padding-bottom: 2px;
1.591     raeburn  8397: }
                   8398: 
                   8399: div.LC_clear_float_footer {
1.597     albertel 8400:   padding-top: 10px;
1.591     raeburn  8401:   clear: both;
                   8402: }
                   8403: 
1.597     albertel 8404: div.LC_grade_show_user {
1.941     bisitz   8405: /*  border-left: 5px solid $sidebg; */
                   8406:   border-top: 5px solid #000000;
                   8407:   margin: 50px 0 0 0;
1.936     bisitz   8408:   padding: 15px 0 5px 10px;
1.597     albertel 8409: }
1.795     www      8410: 
1.936     bisitz   8411: div.LC_grade_show_user_odd_row {
1.941     bisitz   8412: /*  border-left: 5px solid #000000; */
                   8413: }
                   8414: 
                   8415: div.LC_grade_show_user div.LC_Box {
                   8416:   margin-right: 50px;
1.597     albertel 8417: }
                   8418: 
                   8419: div.LC_grade_submissions,
                   8420: div.LC_grade_message_center,
1.936     bisitz   8421: div.LC_grade_info_links {
1.597     albertel 8422:   margin: 5px;
                   8423:   width: 99%;
                   8424:   background: #FFFFFF;
                   8425: }
1.795     www      8426: 
1.597     albertel 8427: div.LC_grade_submissions_header,
1.936     bisitz   8428: div.LC_grade_message_center_header {
1.705     tempelho 8429:   font-weight: bold;
                   8430:   font-size: large;
1.597     albertel 8431: }
1.795     www      8432: 
1.597     albertel 8433: div.LC_grade_submissions_body,
1.936     bisitz   8434: div.LC_grade_message_center_body {
1.597     albertel 8435:   border: 1px solid black;
                   8436:   width: 99%;
                   8437:   background: #FFFFFF;
                   8438: }
1.795     www      8439: 
1.613     albertel 8440: table.LC_scantron_action {
                   8441:   width: 100%;
                   8442: }
1.795     www      8443: 
1.613     albertel 8444: table.LC_scantron_action tr th {
1.698     harmsja  8445:   font-weight:bold;
                   8446:   font-style:normal;
1.613     albertel 8447: }
1.795     www      8448: 
1.779     bisitz   8449: .LC_edit_problem_header,
1.614     albertel 8450: div.LC_edit_problem_footer {
1.705     tempelho 8451:   font-weight: normal;
                   8452:   font-size:  medium;
1.602     albertel 8453:   margin: 2px;
1.1060    bisitz   8454:   background-color: $sidebg;
1.600     albertel 8455: }
1.795     www      8456: 
1.600     albertel 8457: div.LC_edit_problem_header,
1.602     albertel 8458: div.LC_edit_problem_header div,
1.614     albertel 8459: div.LC_edit_problem_footer,
                   8460: div.LC_edit_problem_footer div,
1.602     albertel 8461: div.LC_edit_problem_editxml_header,
                   8462: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8463:   z-index: 100;
1.600     albertel 8464: }
1.795     www      8465: 
1.600     albertel 8466: div.LC_edit_problem_header_title {
1.705     tempelho 8467:   font-weight: bold;
                   8468:   font-size: larger;
1.602     albertel 8469:   background: $tabbg;
                   8470:   padding: 3px;
1.1060    bisitz   8471:   margin: 0 0 5px 0;
1.602     albertel 8472: }
1.795     www      8473: 
1.602     albertel 8474: table.LC_edit_problem_header_title {
                   8475:   width: 100%;
1.600     albertel 8476:   background: $tabbg;
1.602     albertel 8477: }
                   8478: 
1.1205    golterma 8479: div.LC_edit_actionbar {
                   8480:     background-color: $sidebg;
1.1218    droeschl 8481:     margin: 0;
                   8482:     padding: 0;
                   8483:     line-height: 200%;
1.602     albertel 8484: }
1.795     www      8485: 
1.1218    droeschl 8486: div.LC_edit_actionbar div{
                   8487:     padding: 0;
                   8488:     margin: 0;
                   8489:     display: inline-block;
1.600     albertel 8490: }
1.795     www      8491: 
1.1124    bisitz   8492: .LC_edit_opt {
                   8493:   padding-left: 1em;
                   8494:   white-space: nowrap;
                   8495: }
                   8496: 
1.1152    golterma 8497: .LC_edit_problem_latexhelper{
                   8498:     text-align: right;
                   8499: }
                   8500: 
                   8501: #LC_edit_problem_colorful div{
                   8502:     margin-left: 40px;
                   8503: }
                   8504: 
1.1205    golterma 8505: #LC_edit_problem_codemirror div{
                   8506:     margin-left: 0px;
                   8507: }
                   8508: 
1.911     bisitz   8509: img.stift {
1.803     bisitz   8510:   border-width: 0;
                   8511:   vertical-align: middle;
1.677     riegler  8512: }
1.680     riegler  8513: 
1.923     bisitz   8514: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8515:   vertical-align: top;
1.777     tempelho 8516: }
1.795     www      8517: 
1.716     raeburn  8518: div.LC_createcourse {
1.911     bisitz   8519:   margin: 10px 10px 10px 10px;
1.716     raeburn  8520: }
                   8521: 
1.917     raeburn  8522: .LC_dccid {
1.1130    raeburn  8523:   float: right;
1.917     raeburn  8524:   margin: 0.2em 0 0 0;
                   8525:   padding: 0;
                   8526:   font-size: 90%;
                   8527:   display:none;
                   8528: }
                   8529: 
1.897     wenzelju 8530: ol.LC_primary_menu a:hover,
1.721     harmsja  8531: ol#LC_MenuBreadcrumbs a:hover,
                   8532: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8533: ul#LC_secondary_menu a:hover,
1.721     harmsja  8534: .LC_FormSectionClearButton input:hover
1.795     www      8535: ul.LC_TabContent   li:hover a {
1.952     onken    8536:   color:$button_hover;
1.911     bisitz   8537:   text-decoration:none;
1.693     droeschl 8538: }
                   8539: 
1.779     bisitz   8540: h1 {
1.911     bisitz   8541:   padding: 0;
                   8542:   line-height:130%;
1.693     droeschl 8543: }
1.698     harmsja  8544: 
1.911     bisitz   8545: h2,
                   8546: h3,
                   8547: h4,
                   8548: h5,
                   8549: h6 {
                   8550:   margin: 5px 0 5px 0;
                   8551:   padding: 0;
                   8552:   line-height:130%;
1.693     droeschl 8553: }
1.795     www      8554: 
                   8555: .LC_hcell {
1.911     bisitz   8556:   padding:3px 15px 3px 15px;
                   8557:   margin: 0;
                   8558:   background-color:$tabbg;
                   8559:   color:$fontmenu;
                   8560:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8561: }
1.795     www      8562: 
1.840     bisitz   8563: .LC_Box > .LC_hcell {
1.911     bisitz   8564:   margin: 0 -10px 10px -10px;
1.835     bisitz   8565: }
                   8566: 
1.721     harmsja  8567: .LC_noBorder {
1.911     bisitz   8568:   border: 0;
1.698     harmsja  8569: }
1.693     droeschl 8570: 
1.721     harmsja  8571: .LC_FormSectionClearButton input {
1.911     bisitz   8572:   background-color:transparent;
                   8573:   border: none;
                   8574:   cursor:pointer;
                   8575:   text-decoration:underline;
1.693     droeschl 8576: }
1.763     bisitz   8577: 
                   8578: .LC_help_open_topic {
1.911     bisitz   8579:   color: #FFFFFF;
                   8580:   background-color: #EEEEFF;
                   8581:   margin: 1px;
                   8582:   padding: 4px;
                   8583:   border: 1px solid #000033;
                   8584:   white-space: nowrap;
                   8585:   /* vertical-align: middle; */
1.759     neumanie 8586: }
1.693     droeschl 8587: 
1.911     bisitz   8588: dl,
                   8589: ul,
                   8590: div,
                   8591: fieldset {
                   8592:   margin: 10px 10px 10px 0;
                   8593:   /* overflow: hidden; */
1.693     droeschl 8594: }
1.795     www      8595: 
1.1404    raeburn  8596: fieldset#LC_selectuser {
                   8597:     margin: 0;
                   8598:     padding: 0;
                   8599: }
                   8600: 
1.1211    raeburn  8601: article.geogebraweb div {
                   8602:     margin: 0;
                   8603: }
                   8604: 
1.838     bisitz   8605: fieldset > legend {
1.911     bisitz   8606:   font-weight: bold;
                   8607:   padding: 0 5px 0 5px;
1.838     bisitz   8608: }
                   8609: 
1.813     bisitz   8610: #LC_nav_bar {
1.911     bisitz   8611:   float: left;
1.995     raeburn  8612:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8613:   margin: 0 0 2px 0;
1.807     droeschl 8614: }
                   8615: 
1.916     droeschl 8616: #LC_realm {
                   8617:   margin: 0.2em 0 0 0;
                   8618:   padding: 0;
                   8619:   font-weight: bold;
                   8620:   text-align: center;
1.995     raeburn  8621:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8622: }
                   8623: 
1.911     bisitz   8624: #LC_nav_bar em {
                   8625:   font-weight: bold;
                   8626:   font-style: normal;
1.807     droeschl 8627: }
                   8628: 
1.897     wenzelju 8629: ol.LC_primary_menu {
1.934     droeschl 8630:   margin: 0;
1.1076    raeburn  8631:   padding: 0;
1.807     droeschl 8632: }
                   8633: 
1.852     droeschl 8634: ol#LC_PathBreadcrumbs {
1.911     bisitz   8635:   margin: 0;
1.693     droeschl 8636: }
                   8637: 
1.897     wenzelju 8638: ol.LC_primary_menu li {
1.1076    raeburn  8639:   color: RGB(80, 80, 80);
                   8640:   vertical-align: middle;
                   8641:   text-align: left;
                   8642:   list-style: none;
1.1205    golterma 8643:   position: relative;
1.1076    raeburn  8644:   float: left;
1.1205    golterma 8645:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8646:   line-height: 1.5em;
1.1076    raeburn  8647: }
                   8648: 
1.1205    golterma 8649: ol.LC_primary_menu li a,
                   8650: ol.LC_primary_menu li p {
1.1076    raeburn  8651:   display: block;
                   8652:   margin: 0;
                   8653:   padding: 0 5px 0 10px;
                   8654:   text-decoration: none;
                   8655: }
                   8656: 
1.1205    golterma 8657: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8658:   display: inline-block;
                   8659:   width: 95%;
                   8660:   text-align: left;
                   8661: }
                   8662: 
                   8663: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8664:   display: inline-block;	
                   8665:   width: 5%;
                   8666:   float: right;
                   8667:   text-align: right;
                   8668:   font-size: 70%;
                   8669: }
                   8670: 
                   8671: ol.LC_primary_menu ul {
1.1076    raeburn  8672:   display: none;
1.1205    golterma 8673:   width: 15em;
1.1076    raeburn  8674:   background-color: $data_table_light;
1.1205    golterma 8675:   position: absolute;
                   8676:   top: 100%;
1.1076    raeburn  8677: }
                   8678: 
1.1205    golterma 8679: ol.LC_primary_menu ul ul {
                   8680:   left: 100%;
                   8681:   top: 0;
                   8682: }
                   8683: 
                   8684: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8685:   display: block;
                   8686:   position: absolute;
                   8687:   margin: 0;
                   8688:   padding: 0;
1.1078    raeburn  8689:   z-index: 2;
1.1076    raeburn  8690: }
                   8691: 
                   8692: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8693: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8694:   font-size: 90%;
1.911     bisitz   8695:   vertical-align: top;
1.1076    raeburn  8696:   float: none;
1.1079    raeburn  8697:   border-left: 1px solid black;
                   8698:   border-right: 1px solid black;
1.1205    golterma 8699: /* A dark bottom border to visualize different menu options; 
                   8700: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8701:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8702: }
                   8703: 
1.1205    golterma 8704: ol.LC_primary_menu li li p:hover {
                   8705:   color:$button_hover;
                   8706:   text-decoration:none;
                   8707:   background-color:$data_table_dark;
1.1076    raeburn  8708: }
                   8709: 
                   8710: ol.LC_primary_menu li li a:hover {
                   8711:    color:$button_hover;
                   8712:    background-color:$data_table_dark;
1.693     droeschl 8713: }
                   8714: 
1.1205    golterma 8715: /* Font-size equal to the size of the predecessors*/
                   8716: ol.LC_primary_menu li:hover li li {
                   8717:   font-size: 100%;
                   8718: }
                   8719: 
1.897     wenzelju 8720: ol.LC_primary_menu li img {
1.911     bisitz   8721:   vertical-align: bottom;
1.934     droeschl 8722:   height: 1.1em;
1.1077    raeburn  8723:   margin: 0.2em 0 0 0;
1.693     droeschl 8724: }
                   8725: 
1.897     wenzelju 8726: ol.LC_primary_menu a {
1.911     bisitz   8727:   color: RGB(80, 80, 80);
                   8728:   text-decoration: none;
1.693     droeschl 8729: }
1.795     www      8730: 
1.949     droeschl 8731: ol.LC_primary_menu a.LC_new_message {
                   8732:   font-weight:bold;
                   8733:   color: darkred;
                   8734: }
                   8735: 
1.975     raeburn  8736: ol.LC_docs_parameters {
                   8737:   margin-left: 0;
                   8738:   padding: 0;
                   8739:   list-style: none;
                   8740: }
                   8741: 
                   8742: ol.LC_docs_parameters li {
                   8743:   margin: 0;
                   8744:   padding-right: 20px;
                   8745:   display: inline;
                   8746: }
                   8747: 
1.976     raeburn  8748: ol.LC_docs_parameters li:before {
                   8749:   content: "\\002022 \\0020";
                   8750: }
                   8751: 
                   8752: li.LC_docs_parameters_title {
                   8753:   font-weight: bold;
                   8754: }
                   8755: 
                   8756: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8757:   content: "";
                   8758: }
                   8759: 
1.897     wenzelju 8760: ul#LC_secondary_menu {
1.1107    raeburn  8761:   clear: right;
1.911     bisitz   8762:   color: $fontmenu;
                   8763:   background: $tabbg;
                   8764:   list-style: none;
                   8765:   padding: 0;
                   8766:   margin: 0;
                   8767:   width: 100%;
1.995     raeburn  8768:   text-align: left;
1.1107    raeburn  8769:   float: left;
1.808     droeschl 8770: }
                   8771: 
1.897     wenzelju 8772: ul#LC_secondary_menu li {
1.911     bisitz   8773:   font-weight: bold;
                   8774:   line-height: 1.8em;
1.1107    raeburn  8775:   border-right: 1px solid black;
                   8776:   float: left;
                   8777: }
                   8778: 
                   8779: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8780:   background-color: $data_table_light;
                   8781: }
                   8782: 
                   8783: ul#LC_secondary_menu li a {
1.911     bisitz   8784:   padding: 0 0.8em;
1.1107    raeburn  8785: }
                   8786: 
                   8787: ul#LC_secondary_menu li ul {
                   8788:   display: none;
                   8789: }
                   8790: 
                   8791: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8792:   display: block;
                   8793:   position: absolute;
                   8794:   margin: 0;
                   8795:   padding: 0;
                   8796:   list-style:none;
                   8797:   float: none;
                   8798:   background-color: $data_table_light;
                   8799:   z-index: 2;
                   8800:   margin-left: -1px;
                   8801: }
                   8802: 
                   8803: ul#LC_secondary_menu li ul li {
                   8804:   font-size: 90%;
                   8805:   vertical-align: top;
                   8806:   border-left: 1px solid black;
1.911     bisitz   8807:   border-right: 1px solid black;
1.1119    raeburn  8808:   background-color: $data_table_light;
1.1107    raeburn  8809:   list-style:none;
                   8810:   float: none;
                   8811: }
                   8812: 
                   8813: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8814:   background-color: $data_table_dark;
1.807     droeschl 8815: }
                   8816: 
1.847     tempelho 8817: ul.LC_TabContent {
1.911     bisitz   8818:   display:block;
                   8819:   background: $sidebg;
                   8820:   border-bottom: solid 1px $lg_border_color;
                   8821:   list-style:none;
1.1020    raeburn  8822:   margin: -1px -10px 0 -10px;
1.911     bisitz   8823:   padding: 0;
1.693     droeschl 8824: }
                   8825: 
1.795     www      8826: ul.LC_TabContent li,
                   8827: ul.LC_TabContentBigger li {
1.911     bisitz   8828:   float:left;
1.741     harmsja  8829: }
1.795     www      8830: 
1.897     wenzelju 8831: ul#LC_secondary_menu li a {
1.911     bisitz   8832:   color: $fontmenu;
                   8833:   text-decoration: none;
1.693     droeschl 8834: }
1.795     www      8835: 
1.721     harmsja  8836: ul.LC_TabContent {
1.952     onken    8837:   min-height:20px;
1.721     harmsja  8838: }
1.795     www      8839: 
                   8840: ul.LC_TabContent li {
1.911     bisitz   8841:   vertical-align:middle;
1.959     onken    8842:   padding: 0 16px 0 10px;
1.911     bisitz   8843:   background-color:$tabbg;
                   8844:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8845:   border-left: solid 1px $font;
1.721     harmsja  8846: }
1.795     www      8847: 
1.847     tempelho 8848: ul.LC_TabContent .right {
1.911     bisitz   8849:   float:right;
1.847     tempelho 8850: }
                   8851: 
1.911     bisitz   8852: ul.LC_TabContent li a,
                   8853: ul.LC_TabContent li {
                   8854:   color:rgb(47,47,47);
                   8855:   text-decoration:none;
                   8856:   font-size:95%;
                   8857:   font-weight:bold;
1.952     onken    8858:   min-height:20px;
                   8859: }
                   8860: 
1.959     onken    8861: ul.LC_TabContent li a:hover,
                   8862: ul.LC_TabContent li a:focus {
1.952     onken    8863:   color: $button_hover;
1.959     onken    8864:   background:none;
                   8865:   outline:none;
1.952     onken    8866: }
                   8867: 
                   8868: ul.LC_TabContent li:hover {
                   8869:   color: $button_hover;
                   8870:   cursor:pointer;
1.721     harmsja  8871: }
1.795     www      8872: 
1.911     bisitz   8873: ul.LC_TabContent li.active {
1.952     onken    8874:   color: $font;
1.911     bisitz   8875:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8876:   border-bottom:solid 1px #FFFFFF;
                   8877:   cursor: default;
1.744     ehlerst  8878: }
1.795     www      8879: 
1.959     onken    8880: ul.LC_TabContent li.active a {
                   8881:   color:$font;
                   8882:   background:#FFFFFF;
                   8883:   outline: none;
                   8884: }
1.1047    raeburn  8885: 
                   8886: ul.LC_TabContent li.goback {
                   8887:   float: left;
                   8888:   border-left: none;
                   8889: }
                   8890: 
1.870     tempelho 8891: #maincoursedoc {
1.911     bisitz   8892:   clear:both;
1.870     tempelho 8893: }
                   8894: 
                   8895: ul.LC_TabContentBigger {
1.911     bisitz   8896:   display:block;
                   8897:   list-style:none;
                   8898:   padding: 0;
1.870     tempelho 8899: }
                   8900: 
1.795     www      8901: ul.LC_TabContentBigger li {
1.911     bisitz   8902:   vertical-align:bottom;
                   8903:   height: 30px;
                   8904:   font-size:110%;
                   8905:   font-weight:bold;
                   8906:   color: #737373;
1.841     tempelho 8907: }
                   8908: 
1.957     onken    8909: ul.LC_TabContentBigger li.active {
                   8910:   position: relative;
                   8911:   top: 1px;
                   8912: }
                   8913: 
1.870     tempelho 8914: ul.LC_TabContentBigger li a {
1.911     bisitz   8915:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8916:   height: 30px;
                   8917:   line-height: 30px;
                   8918:   text-align: center;
                   8919:   display: block;
                   8920:   text-decoration: none;
1.958     onken    8921:   outline: none;  
1.741     harmsja  8922: }
1.795     www      8923: 
1.870     tempelho 8924: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8925:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8926:   color:$font;
1.744     ehlerst  8927: }
1.795     www      8928: 
1.870     tempelho 8929: ul.LC_TabContentBigger li b {
1.911     bisitz   8930:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8931:   display: block;
                   8932:   float: left;
                   8933:   padding: 0 30px;
1.957     onken    8934:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8935: }
                   8936: 
1.956     onken    8937: ul.LC_TabContentBigger li:hover b {
                   8938:   color:$button_hover;
                   8939: }
                   8940: 
1.870     tempelho 8941: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8942:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8943:   color:$font;
1.957     onken    8944:   border: 0;
1.741     harmsja  8945: }
1.693     droeschl 8946: 
1.870     tempelho 8947: 
1.862     bisitz   8948: ul.LC_CourseBreadcrumbs {
                   8949:   background: $sidebg;
1.1020    raeburn  8950:   height: 2em;
1.862     bisitz   8951:   padding-left: 10px;
1.1020    raeburn  8952:   margin: 0;
1.862     bisitz   8953:   list-style-position: inside;
                   8954: }
                   8955: 
1.911     bisitz   8956: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8957: ol#LC_PathBreadcrumbs {
1.911     bisitz   8958:   padding-left: 10px;
                   8959:   margin: 0;
1.933     droeschl 8960:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8961: }
                   8962: 
1.911     bisitz   8963: ol#LC_MenuBreadcrumbs li,
                   8964: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8965: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8966:   display: inline;
1.933     droeschl 8967:   white-space: normal;  
1.693     droeschl 8968: }
                   8969: 
1.823     bisitz   8970: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8971: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8972:   text-decoration: none;
                   8973:   font-size:90%;
1.693     droeschl 8974: }
1.795     www      8975: 
1.969     droeschl 8976: ol#LC_MenuBreadcrumbs h1 {
                   8977:   display: inline;
                   8978:   font-size: 90%;
                   8979:   line-height: 2.5em;
                   8980:   margin: 0;
                   8981:   padding: 0;
                   8982: }
                   8983: 
1.795     www      8984: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8985:   text-decoration:none;
                   8986:   font-size:100%;
                   8987:   font-weight:bold;
1.693     droeschl 8988: }
1.795     www      8989: 
1.840     bisitz   8990: .LC_Box {
1.911     bisitz   8991:   border: solid 1px $lg_border_color;
                   8992:   padding: 0 10px 10px 10px;
1.746     neumanie 8993: }
1.795     www      8994: 
1.1020    raeburn  8995: .LC_DocsBox {
                   8996:   border: solid 1px $lg_border_color;
                   8997:   padding: 0 0 10px 10px;
                   8998: }
                   8999: 
1.795     www      9000: .LC_AboutMe_Image {
1.911     bisitz   9001:   float:left;
                   9002:   margin-right:10px;
1.747     neumanie 9003: }
1.795     www      9004: 
                   9005: .LC_Clear_AboutMe_Image {
1.911     bisitz   9006:   clear:left;
1.747     neumanie 9007: }
1.795     www      9008: 
1.721     harmsja  9009: dl.LC_ListStyleClean dt {
1.911     bisitz   9010:   padding-right: 5px;
                   9011:   display: table-header-group;
1.693     droeschl 9012: }
                   9013: 
1.721     harmsja  9014: dl.LC_ListStyleClean dd {
1.911     bisitz   9015:   display: table-row;
1.693     droeschl 9016: }
                   9017: 
1.721     harmsja  9018: .LC_ListStyleClean,
                   9019: .LC_ListStyleSimple,
                   9020: .LC_ListStyleNormal,
1.795     www      9021: .LC_ListStyleSpecial {
1.911     bisitz   9022:   /* display:block; */
                   9023:   list-style-position: inside;
                   9024:   list-style-type: none;
                   9025:   overflow: hidden;
                   9026:   padding: 0;
1.693     droeschl 9027: }
                   9028: 
1.721     harmsja  9029: .LC_ListStyleSimple li,
                   9030: .LC_ListStyleSimple dd,
                   9031: .LC_ListStyleNormal li,
                   9032: .LC_ListStyleNormal dd,
                   9033: .LC_ListStyleSpecial li,
1.795     www      9034: .LC_ListStyleSpecial dd {
1.911     bisitz   9035:   margin: 0;
                   9036:   padding: 5px 5px 5px 10px;
                   9037:   clear: both;
1.693     droeschl 9038: }
                   9039: 
1.721     harmsja  9040: .LC_ListStyleClean li,
                   9041: .LC_ListStyleClean dd {
1.911     bisitz   9042:   padding-top: 0;
                   9043:   padding-bottom: 0;
1.693     droeschl 9044: }
                   9045: 
1.721     harmsja  9046: .LC_ListStyleSimple dd,
1.795     www      9047: .LC_ListStyleSimple li {
1.911     bisitz   9048:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9049: }
                   9050: 
1.721     harmsja  9051: .LC_ListStyleSpecial li,
                   9052: .LC_ListStyleSpecial dd {
1.911     bisitz   9053:   list-style-type: none;
                   9054:   background-color: RGB(220, 220, 220);
                   9055:   margin-bottom: 4px;
1.693     droeschl 9056: }
                   9057: 
1.721     harmsja  9058: table.LC_SimpleTable {
1.911     bisitz   9059:   margin:5px;
                   9060:   border:solid 1px $lg_border_color;
1.795     www      9061: }
1.693     droeschl 9062: 
1.721     harmsja  9063: table.LC_SimpleTable tr {
1.911     bisitz   9064:   padding: 0;
                   9065:   border:solid 1px $lg_border_color;
1.693     droeschl 9066: }
1.795     www      9067: 
                   9068: table.LC_SimpleTable thead {
1.911     bisitz   9069:   background:rgb(220,220,220);
1.693     droeschl 9070: }
                   9071: 
1.721     harmsja  9072: div.LC_columnSection {
1.911     bisitz   9073:   display: block;
                   9074:   clear: both;
                   9075:   overflow: hidden;
                   9076:   margin: 0;
1.693     droeschl 9077: }
                   9078: 
1.721     harmsja  9079: div.LC_columnSection>* {
1.911     bisitz   9080:   float: left;
                   9081:   margin: 10px 20px 10px 0;
                   9082:   overflow:hidden;
1.693     droeschl 9083: }
1.721     harmsja  9084: 
1.795     www      9085: table em {
1.911     bisitz   9086:   font-weight: bold;
                   9087:   font-style: normal;
1.748     schulted 9088: }
1.795     www      9089: 
1.779     bisitz   9090: table.LC_tableBrowseRes,
1.795     www      9091: table.LC_tableOfContent {
1.911     bisitz   9092:   border:none;
                   9093:   border-spacing: 1px;
                   9094:   padding: 3px;
                   9095:   background-color: #FFFFFF;
                   9096:   font-size: 90%;
1.753     droeschl 9097: }
1.789     droeschl 9098: 
1.911     bisitz   9099: table.LC_tableOfContent {
                   9100:   border-collapse: collapse;
1.789     droeschl 9101: }
                   9102: 
1.771     droeschl 9103: table.LC_tableBrowseRes a,
1.768     schulted 9104: table.LC_tableOfContent a {
1.911     bisitz   9105:   background-color: transparent;
                   9106:   text-decoration: none;
1.753     droeschl 9107: }
                   9108: 
1.795     www      9109: table.LC_tableOfContent img {
1.911     bisitz   9110:   border: none;
                   9111:   height: 1.3em;
                   9112:   vertical-align: text-bottom;
                   9113:   margin-right: 0.3em;
1.753     droeschl 9114: }
1.757     schulted 9115: 
1.795     www      9116: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9117:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9118: }
                   9119: 
1.795     www      9120: a#LC_content_toolbar_everything {
1.911     bisitz   9121:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9122: }
                   9123: 
1.795     www      9124: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9125:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9126: }
                   9127: 
1.795     www      9128: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9129:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9130: }
                   9131: 
1.795     www      9132: a#LC_content_toolbar_changefolder {
1.911     bisitz   9133:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9134: }
                   9135: 
1.795     www      9136: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9137:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9138: }
                   9139: 
1.1043    raeburn  9140: a#LC_content_toolbar_edittoplevel {
                   9141:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9142: }
                   9143: 
1.1384    raeburn  9144: a#LC_content_toolbar_printout {
                   9145:   background-image:url(/res/adm/pages/printout.gif);
                   9146: }
                   9147: 
1.795     www      9148: ul#LC_toolbar li a:hover {
1.911     bisitz   9149:   background-position: bottom center;
1.757     schulted 9150: }
                   9151: 
1.795     www      9152: ul#LC_toolbar {
1.911     bisitz   9153:   padding: 0;
                   9154:   margin: 2px;
                   9155:   list-style:none;
1.1449    raeburn  9156:   display:inline;
1.911     bisitz   9157:   background-color:white;
1.1082    raeburn  9158:   overflow: auto;
1.757     schulted 9159: }
                   9160: 
1.795     www      9161: ul#LC_toolbar li {
1.911     bisitz   9162:   border:1px solid white;
                   9163:   padding: 0;
                   9164:   margin: 0;
                   9165:   float: left;
                   9166:   display:inline;
                   9167:   vertical-align:middle;
1.1082    raeburn  9168:   white-space: nowrap;
1.911     bisitz   9169: }
1.757     schulted 9170: 
1.783     amueller 9171: 
1.795     www      9172: a.LC_toolbarItem {
1.911     bisitz   9173:   display:block;
                   9174:   padding: 0;
                   9175:   margin: 0;
                   9176:   height: 32px;
                   9177:   width: 32px;
                   9178:   color:white;
                   9179:   border: none;
                   9180:   background-repeat:no-repeat;
                   9181:   background-color:transparent;
1.757     schulted 9182: }
                   9183: 
1.1449    raeburn  9184: .LC_navtools {
                   9185:   display: inline-block;
                   9186:   padding: 0;
                   9187:   margin: 2px;
                   9188:   vertical-align: middle;
                   9189: }
                   9190: 
1.915     droeschl 9191: ul.LC_funclist {
                   9192:     margin: 0;
                   9193:     padding: 0.5em 1em 0.5em 0;
                   9194: }
                   9195: 
1.933     droeschl 9196: ul.LC_funclist > li:first-child {
                   9197:     font-weight:bold; 
                   9198:     margin-left:0.8em;
                   9199: }
                   9200: 
1.915     droeschl 9201: ul.LC_funclist + ul.LC_funclist {
                   9202:     /* 
                   9203:        left border as a seperator if we have more than
                   9204:        one list 
                   9205:     */
                   9206:     border-left: 1px solid $sidebg;
                   9207:     /* 
                   9208:        this hides the left border behind the border of the 
                   9209:        outer box if element is wrapped to the next 'line' 
                   9210:     */
                   9211:     margin-left: -1px;
                   9212: }
                   9213: 
1.843     bisitz   9214: ul.LC_funclist li {
1.915     droeschl 9215:   display: inline;
1.782     bisitz   9216:   white-space: nowrap;
1.915     droeschl 9217:   margin: 0 0 0 25px;
                   9218:   line-height: 150%;
1.782     bisitz   9219: }
                   9220: 
1.974     wenzelju 9221: .LC_hidden {
                   9222:   display: none;
                   9223: }
                   9224: 
1.1030    www      9225: .LCmodal-overlay {
                   9226: 		position:fixed;
                   9227: 		top:0;
                   9228: 		right:0;
                   9229: 		bottom:0;
                   9230: 		left:0;
                   9231: 		height:100%;
                   9232: 		width:100%;
                   9233: 		margin:0;
                   9234: 		padding:0;
                   9235: 		background:#999;
                   9236: 		opacity:.75;
                   9237: 		filter: alpha(opacity=75);
                   9238: 		-moz-opacity: 0.75;
                   9239: 		z-index:101;
                   9240: }
                   9241: 
                   9242: * html .LCmodal-overlay {   
                   9243: 		position: absolute;
                   9244: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9245: }
                   9246: 
                   9247: .LCmodal-window {
                   9248: 		position:fixed;
                   9249: 		top:50%;
                   9250: 		left:50%;
                   9251: 		margin:0;
                   9252: 		padding:0;
                   9253: 		z-index:102;
                   9254: 	}
                   9255: 
                   9256: * html .LCmodal-window {
                   9257: 		position:absolute;
                   9258: }
                   9259: 
                   9260: .LCclose-window {
                   9261: 		position:absolute;
                   9262: 		width:32px;
                   9263: 		height:32px;
                   9264: 		right:8px;
                   9265: 		top:8px;
                   9266: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9267: 		text-indent:-99999px;
                   9268: 		overflow:hidden;
                   9269: 		cursor:pointer;
                   9270: }
                   9271: 
1.1369    raeburn  9272: .LCisDisabled {
                   9273:   cursor: not-allowed;
                   9274:   opacity: 0.5;
                   9275: }
                   9276: 
                   9277: a[aria-disabled="true"] {
                   9278:   color: currentColor;
                   9279:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9280:   pointer-events: none;
                   9281:   text-decoration: none;
                   9282: }
                   9283: 
1.1335    raeburn  9284: pre.LC_wordwrap {
                   9285:   white-space: pre-wrap;
                   9286:   white-space: -moz-pre-wrap;
                   9287:   white-space: -pre-wrap;
                   9288:   white-space: -o-pre-wrap;
                   9289:   word-wrap: break-word;
                   9290: }
                   9291: 
1.1100    raeburn  9292: /*
1.1231    damieng  9293:   styles used for response display
                   9294: */
                   9295: div.LC_radiofoil, div.LC_rankfoil {
                   9296:   margin: .5em 0em .5em 0em;
                   9297: }
                   9298: table.LC_itemgroup {
                   9299:   margin-top: 1em;
                   9300: }
                   9301: 
                   9302: /*
1.1100    raeburn  9303:   styles used by TTH when "Default set of options to pass to tth/m
                   9304:   when converting TeX" in course settings has been set
                   9305: 
                   9306:   option passed: -t
                   9307: 
                   9308: */
                   9309: 
                   9310: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9311: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9312: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9313: td div.norm {line-height:normal;}
                   9314: 
                   9315: /*
                   9316:   option passed -y3
                   9317: */
                   9318: 
                   9319: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9320: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9321: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9322: 
1.1230    damieng  9323: /*
                   9324:   sections with roles, for content only
                   9325: */
                   9326: section[class^="role-"] {
                   9327:   padding-left: 10px;
                   9328:   padding-right: 5px;
                   9329:   margin-top: 8px;
                   9330:   margin-bottom: 8px;
                   9331:   border: 1px solid #2A4;
                   9332:   border-radius: 5px;
                   9333:   box-shadow: 0px 1px 1px #BBB;
                   9334: }
                   9335: section[class^="role-"]>h1 {
                   9336:   position: relative;
                   9337:   margin: 0px;
                   9338:   padding-top: 10px;
                   9339:   padding-left: 40px;
                   9340: }
                   9341: section[class^="role-"]>h1:before {
                   9342:   position: absolute;
                   9343:   left: -5px;
                   9344:   top: 5px;
                   9345: }
                   9346: section.role-activity>h1:before {
                   9347:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9348: }
                   9349: section.role-advice>h1:before {
                   9350:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9351: }
                   9352: section.role-bibliography>h1:before {
                   9353:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9354: }
                   9355: section.role-citation>h1:before {
                   9356:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9357: }
                   9358: section.role-conclusion>h1:before {
                   9359:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9360: }
                   9361: section.role-definition>h1:before {
                   9362:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9363: }
                   9364: section.role-demonstration>h1:before {
                   9365:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9366: }
                   9367: section.role-example>h1:before {
                   9368:   content:url('/adm/daxe/images/section_icons/example.png');
                   9369: }
                   9370: section.role-explanation>h1:before {
                   9371:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9372: }
                   9373: section.role-introduction>h1:before {
                   9374:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9375: }
                   9376: section.role-method>h1:before {
                   9377:   content:url('/adm/daxe/images/section_icons/method.png');
                   9378: }
                   9379: section.role-more_information>h1:before {
                   9380:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9381: }
                   9382: section.role-objectives>h1:before {
                   9383:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9384: }
                   9385: section.role-prerequisites>h1:before {
                   9386:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9387: }
                   9388: section.role-remark>h1:before {
                   9389:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9390: }
                   9391: section.role-reminder>h1:before {
                   9392:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9393: }
                   9394: section.role-summary>h1:before {
                   9395:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9396: }
                   9397: section.role-syntax>h1:before {
                   9398:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9399: }
                   9400: section.role-warning>h1:before {
                   9401:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9402: }
                   9403: 
1.1269    raeburn  9404: #LC_minitab_header {
                   9405:   float:left;
                   9406:   width:100%;
                   9407:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9408:   font-size:93%;
                   9409:   line-height:normal;
                   9410:   margin: 0.5em 0 0.5em 0;
                   9411: }
                   9412: #LC_minitab_header ul {
                   9413:   margin:0;
                   9414:   padding:10px 10px 0;
                   9415:   list-style:none;
                   9416: }
                   9417: #LC_minitab_header li {
                   9418:   float:left;
                   9419:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9420:   margin:0;
                   9421:   padding:0 0 0 9px;
                   9422: }
                   9423: #LC_minitab_header a {
                   9424:   display:block;
                   9425:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9426:   padding:5px 15px 4px 6px;
                   9427: }
                   9428: #LC_minitab_header #LC_current_minitab {
                   9429:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9430: }
                   9431: #LC_minitab_header #LC_current_minitab a {
                   9432:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9433:   padding-bottom:5px;
                   9434: }
                   9435: 
                   9436: 
1.343     albertel 9437: END
                   9438: }
                   9439: 
1.306     albertel 9440: =pod
                   9441: 
                   9442: =item * &headtag()
                   9443: 
                   9444: Returns a uniform footer for LON-CAPA web pages.
                   9445: 
1.307     albertel 9446: Inputs: $title - optional title for the head
                   9447:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9448:         $args - optional arguments
1.319     albertel 9449:             force_register - if is true call registerurl so the remote is 
                   9450:                              informed
1.415     albertel 9451:             redirect       -> array ref of
                   9452:                                    1- seconds before redirect occurs
                   9453:                                    2- url to redirect to
                   9454:                                    3- whether the side effect should occur
1.315     albertel 9455:                            (side effect of setting 
                   9456:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9457:                                redirected to)
                   9458:                                    4- whether the redirect target should be
                   9459:                                       the opener of the current (pop-up)
                   9460:                                       window (side effect of setting
                   9461:                                       $env{'internal.head.to_opener'} to
                   9462:                                       1, if true.
1.1388    raeburn  9463:                                    5- whether encrypt check should be skipped
1.352     albertel 9464:             domain         -> force to color decorate a page for a specific
                   9465:                                domain
                   9466:             function       -> force usage of a specific rolish color scheme
                   9467:             bgcolor        -> override the default page bgcolor
1.460     albertel 9468:             no_auto_mt_title
                   9469:                            -> prevent &mt()ing the title arg
1.464     albertel 9470: 
1.306     albertel 9471: =cut
                   9472: 
                   9473: sub headtag {
1.313     albertel 9474:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9475:     
1.363     albertel 9476:     my $function = $args->{'function'} || &get_users_function();
                   9477:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9478:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9479:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9480:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9481: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9482: 		   #time(),
1.418     albertel 9483: 		   $env{'environment.color.timestamp'},
1.363     albertel 9484: 		   $function,$domain,$bgcolor);
                   9485: 
1.369     www      9486:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9487: 
1.308     albertel 9488:     my $result =
                   9489: 	'<head>'.
1.1160    raeburn  9490: 	&font_settings($args);
1.319     albertel 9491: 
1.1188    raeburn  9492:     my $inhibitprint;
                   9493:     if ($args->{'print_suppress'}) {
                   9494:         $inhibitprint = &print_suppression();
                   9495:     }
1.1064    raeburn  9496: 
1.1439    raeburn  9497:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9498: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9499:     }
1.962     droeschl 9500:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9501:         $result .= Apache::lonxml::display_title();
1.319     albertel 9502:     }
1.436     albertel 9503:     if (!$args->{'no_nav_bar'} 
                   9504: 	&& !$args->{'only_body'}
1.1438    raeburn  9505: 	&& !$args->{'frameset'}
                   9506: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9507: 	$result .= &help_menu_js($httphost);
1.1032    www      9508:         $result.=&modal_window();
1.1038    www      9509:         $result.=&togglebox_script();
1.1034    www      9510:         $result.=&wishlist_window();
1.1041    www      9511:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9512:     } else {
                   9513:         if ($args->{'add_modal'}) {
                   9514:            $result.=&modal_window();
                   9515:         }
                   9516:         if ($args->{'add_wishlist'}) {
                   9517:            $result.=&wishlist_window();
                   9518:         }
1.1038    www      9519:         if ($args->{'add_togglebox'}) {
                   9520:            $result.=&togglebox_script();
                   9521:         }
1.1041    www      9522:         if ($args->{'add_progressbar'}) {
                   9523:            $result.=&LCprogressbarUpdate_script();
                   9524:         }
1.436     albertel 9525:     }
1.314     albertel 9526:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9527: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9528:         if (!$skip_enc_check) {
                   9529:             $url = &Apache::lonenc::check_encrypt($url);
                   9530:         }
1.414     albertel 9531: 	if (!$inhibit_continue) {
                   9532: 	    $env{'internal.head.redirect'} = $url;
                   9533: 	}
1.1386    raeburn  9534: 	$result.=<<"ADDMETA";
1.313     albertel 9535: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9536: ADDMETA
                   9537:         if ($to_opener) {
                   9538:             $env{'internal.head.to_opener'} = 1;
                   9539:             my $dest = &js_escape($url);
                   9540:             my $timeout = int($time * 1000);
                   9541:             $result .=<<"ENDJS";
                   9542: <script type="text/javascript">
                   9543: // <![CDATA[
                   9544: function LC_To_Opener() {
                   9545:     var dest = '$dest';
                   9546:     if (dest != '') {
                   9547:         if (window.opener != null && !window.opener.closed) {
                   9548:             window.opener.location.href=dest;
                   9549:             window.close();
                   9550:         } else {
                   9551:             window.location.href=dest;
                   9552:         }
                   9553:     }
                   9554: }
                   9555: \$(document).ready(function () {
                   9556:     setTimeout('LC_To_Opener()',$timeout);
                   9557: });
                   9558: // ]]>
                   9559: </script>
                   9560: ENDJS
                   9561:         } else {
                   9562:             $result.=<<"ADDMETA";
1.344     albertel 9563: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9564: ADDMETA
1.1386    raeburn  9565:         }
1.1210    raeburn  9566:     } else {
                   9567:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9568:             my $requrl = $env{'request.uri'};
                   9569:             if ($requrl eq '') {
                   9570:                 $requrl = $ENV{'REQUEST_URI'};
                   9571:                 $requrl =~ s/\?.+$//;
                   9572:             }
                   9573:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9574:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9575:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9576:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9577:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9578:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9579:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9580:                     my ($offload,$offloadoth);
1.1210    raeburn  9581:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9582:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9583:                             $offload = 1;
1.1353    raeburn  9584:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9585:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9586:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9587:                                     $offloadoth = 1;
                   9588:                                     $dom_in_use = $env{'user.domain'};
                   9589:                                 }
                   9590:                             }
1.1340    raeburn  9591:                         }
                   9592:                     }
                   9593:                     unless ($offload) {
                   9594:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9595:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9596:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9597:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9598:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9599:                                         $offload = 1;
1.1352    raeburn  9600:                                         $offloadoth = 1;
1.1340    raeburn  9601:                                         $dom_in_use = $env{'user.domain'};
                   9602:                                     }
1.1210    raeburn  9603:                                 }
1.1340    raeburn  9604:                             }
                   9605:                         }
                   9606:                     }
                   9607:                     if ($offload) {
1.1358    raeburn  9608:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9609:                         if (($newserver eq '') && ($offloadoth)) {
                   9610:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9611:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9612:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9613:                             }
                   9614:                         }
1.1340    raeburn  9615:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9616:                             my $numsec = 5;
                   9617:                             my $timeout = $numsec * 1000;
                   9618:                             my ($newurl,$locknum,%locks,$msg);
                   9619:                             if ($env{'request.role.adv'}) {
                   9620:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9621:                             }
                   9622:                             my $disable_submit = 0;
                   9623:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9624:                                 $disable_submit = 1;
                   9625:                             }
                   9626:                             if ($locknum) {
                   9627:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9628:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9629:                                        join(", ",sort(values(%locks)))."\n";
                   9630:                                 if (&show_course()) {
                   9631:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9632:                                 } else {
                   9633:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9634:                                 }
1.1340    raeburn  9635:                             } else {
                   9636:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9637:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9638:                                 }
                   9639:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9640:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9641:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9642:                                     $newurl .= '&role='.$env{'request.role'};
                   9643:                                 }
                   9644:                                 if ($env{'request.symb'}) {
                   9645:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9646:                                     if ($shownsymb =~ m{^/enc/}) {
                   9647:                                         my $reqdmajor = 2;
                   9648:                                         my $reqdminor = 11;
                   9649:                                         my $reqdsubminor = 3;
                   9650:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9651:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9652:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9653:                                         if (($major eq '' && $minor eq '') ||
                   9654:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9655:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9656:                                              ($reqdsubminor > $subminor))))) {
                   9657:                                             undef($shownsymb);
                   9658:                                         }
1.1210    raeburn  9659:                                     }
1.1340    raeburn  9660:                                     if ($shownsymb) {
                   9661:                                         &js_escape(\$shownsymb);
                   9662:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9663:                                     }
1.1340    raeburn  9664:                                 } else {
                   9665:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9666:                                     &js_escape(\$shownurl);
                   9667:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9668:                                 }
1.1340    raeburn  9669:                             }
                   9670:                             &js_escape(\$msg);
                   9671:                             $result.=<<OFFLOAD
1.1210    raeburn  9672: <meta http-equiv="pragma" content="no-cache" />
                   9673: <script type="text/javascript">
1.1215    raeburn  9674: // <![CDATA[
1.1210    raeburn  9675: function LC_Offload_Now() {
                   9676:     var dest = "$newurl";
                   9677:     if (dest != '') {
                   9678:         window.location.href="$newurl";
                   9679:     }
                   9680: }
1.1214    raeburn  9681: \$(document).ready(function () {
                   9682:     window.alert('$msg');
                   9683:     if ($disable_submit) {
1.1210    raeburn  9684:         \$(".LC_hwk_submit").prop("disabled", true);
                   9685:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9686:     }
                   9687:     setTimeout('LC_Offload_Now()', $timeout);
                   9688: });
1.1215    raeburn  9689: // ]]>
1.1210    raeburn  9690: </script>
                   9691: OFFLOAD
                   9692:                         }
                   9693:                     }
                   9694:                 }
                   9695:             }
                   9696:         }
1.313     albertel 9697:     }
1.306     albertel 9698:     if (!defined($title)) {
                   9699: 	$title = 'The LearningOnline Network with CAPA';
                   9700:     }
1.460     albertel 9701:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9702:     if ($title =~ /^LON-CAPA\s+/) {
                   9703:         $result .= '<title> '.$title.'</title>';
                   9704:     } else {
                   9705:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9706:     }
                   9707:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9708:     if (!$args->{'frameset'}) {
                   9709:         $result .= ' /';
                   9710:     }
                   9711:     $result .= '>' 
1.1064    raeburn  9712:         .$inhibitprint
1.414     albertel 9713: 	.$head_extra;
1.1242    raeburn  9714:     my $clientmobile;
                   9715:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9716:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9717:     } else {
                   9718:         $clientmobile = $env{'browser.mobile'};
                   9719:     }
                   9720:     if ($clientmobile) {
1.1137    raeburn  9721:         $result .= '
1.1435    raeburn  9722: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9723: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9724:     }
1.1278    raeburn  9725:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9726:     return $result.'</head>';
1.306     albertel 9727: }
                   9728: 
                   9729: =pod
                   9730: 
1.340     albertel 9731: =item * &font_settings()
                   9732: 
                   9733: Returns neccessary <meta> to set the proper encoding
                   9734: 
1.1160    raeburn  9735: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9736: 
                   9737: =cut
                   9738: 
                   9739: sub font_settings {
1.1160    raeburn  9740:     my ($args) = @_;
1.340     albertel 9741:     my $headerstring='';
1.1160    raeburn  9742:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9743:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9744:         $headerstring.=
                   9745:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9746:         if (!$args->{'frameset'}) {
                   9747: 	    $headerstring.= ' /';
                   9748:         }
                   9749: 	$headerstring .= '>'."\n";
1.340     albertel 9750:     }
                   9751:     return $headerstring;
                   9752: }
                   9753: 
1.341     albertel 9754: =pod
                   9755: 
1.1064    raeburn  9756: =item * &print_suppression()
                   9757: 
                   9758: In course context returns css which causes the body to be blank when media="print",
                   9759: if printout generation is unavailable for the current resource.
                   9760: 
                   9761: This could be because:
                   9762: 
                   9763: (a) printstartdate is in the future
                   9764: 
                   9765: (b) printenddate is in the past
                   9766: 
                   9767: (c) there is an active exam block with "printout"
                   9768: functionality blocked
                   9769: 
                   9770: Users with pav, pfo or evb privileges are exempt.
                   9771: 
                   9772: Inputs: none
                   9773: 
                   9774: =cut
                   9775: 
                   9776: 
                   9777: sub print_suppression {
                   9778:     my $noprint;
                   9779:     if ($env{'request.course.id'}) {
                   9780:         my $scope = $env{'request.course.id'};
                   9781:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9782:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9783:             return;
                   9784:         }
                   9785:         if ($env{'request.course.sec'} ne '') {
                   9786:             $scope .= "/$env{'request.course.sec'}";
                   9787:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9788:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9789:                 return;
1.1064    raeburn  9790:             }
                   9791:         }
                   9792:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9793:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9794:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9795:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9796:         if ($blocked) {
                   9797:             my $checkrole = "cm./$cdom/$cnum";
                   9798:             if ($env{'request.course.sec'} ne '') {
                   9799:                 $checkrole .= "/$env{'request.course.sec'}";
                   9800:             }
                   9801:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9802:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9803:                 $noprint = 1;
                   9804:             }
                   9805:         }
                   9806:         unless ($noprint) {
                   9807:             my $symb = &Apache::lonnet::symbread();
                   9808:             if ($symb ne '') {
                   9809:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9810:                 if (ref($navmap)) {
                   9811:                     my $res = $navmap->getBySymb($symb);
                   9812:                     if (ref($res)) {
                   9813:                         if (!$res->resprintable()) {
                   9814:                             $noprint = 1;
                   9815:                         }
                   9816:                     }
                   9817:                 }
                   9818:             }
                   9819:         }
                   9820:         if ($noprint) {
                   9821:             return <<"ENDSTYLE";
                   9822: <style type="text/css" media="print">
                   9823:     body { display:none }
                   9824: </style>
                   9825: ENDSTYLE
                   9826:         }
                   9827:     }
                   9828:     return;
                   9829: }
                   9830: 
                   9831: =pod
                   9832: 
1.341     albertel 9833: =item * &xml_begin()
                   9834: 
                   9835: Returns the needed doctype and <html>
                   9836: 
                   9837: Inputs: none
                   9838: 
                   9839: =cut
                   9840: 
                   9841: sub xml_begin {
1.1168    raeburn  9842:     my ($is_frameset) = @_;
1.341     albertel 9843:     my $output='';
                   9844: 
                   9845:     if ($env{'browser.mathml'}) {
                   9846: 	$output='<?xml version="1.0"?>'
                   9847:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9848: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9849:             
                   9850: #	    .'<!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">] >'
                   9851: 	    .'<!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">'
                   9852:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9853: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9854:     } elsif ($is_frameset) {
                   9855:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9856:                 '<html>'."\n";
1.341     albertel 9857:     } else {
1.1168    raeburn  9858: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9859:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9860:     }
                   9861:     return $output;
                   9862: }
1.340     albertel 9863: 
                   9864: =pod
                   9865: 
1.306     albertel 9866: =item * &start_page()
                   9867: 
                   9868: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9869: 
1.648     raeburn  9870: Inputs:
                   9871: 
                   9872: =over 4
                   9873: 
                   9874: $title - optional title for the page
                   9875: 
                   9876: $head_extra - optional extra HTML to incude inside the <head>
                   9877: 
                   9878: $args - additional optional args supported are:
                   9879: 
                   9880: =over 8
                   9881: 
                   9882:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9883:                                     arg on
1.814     bisitz   9884:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9885:              add_entries    -> additional attributes to add to the  <body>
                   9886:              domain         -> force to color decorate a page for a 
1.317     albertel 9887:                                     specific domain
1.648     raeburn  9888:              function       -> force usage of a specific rolish color
1.317     albertel 9889:                                     scheme
1.648     raeburn  9890:              redirect       -> see &headtag()
                   9891:              bgcolor        -> override the default page bg color
                   9892:              js_ready       -> return a string ready for being used in 
1.317     albertel 9893:                                     a javascript writeln
1.648     raeburn  9894:              html_encode    -> return a string ready for being used in 
1.320     albertel 9895:                                     a html attribute
1.648     raeburn  9896:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9897:                                     $forcereg arg
1.648     raeburn  9898:              frameset       -> if true will start with a <frameset>
1.330     albertel 9899:                                     rather than <body>
1.648     raeburn  9900:              skip_phases    -> hash ref of 
1.338     albertel 9901:                                     head -> skip the <html><head> generation
                   9902:                                     body -> skip all <body> generation
1.648     raeburn  9903:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9904:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9905:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  9906:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9907:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9908:                                    to override those values, or add to them, specify the value to
                   9909:                                    include in the style attribute to include in the div tag by using
                   9910:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  9911:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9912:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9913:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9914:                                specific group
                   9915:              use_absolute   -> for request for external resource or syllabus, this
                   9916:                                will contain https://<hostname> if server uses
                   9917:                                https (as per hosts.tab), but request is for http
                   9918:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9919:              links_disabled -> Links in primary and secondary menus are disabled
                   9920:                                (Can enable them once page has loaded - see lonroles.pm
                   9921:                                for an example).
1.1380    raeburn  9922:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9923: 
1.648     raeburn  9924: =back
1.460     albertel 9925: 
1.648     raeburn  9926: =back
1.562     albertel 9927: 
1.306     albertel 9928: =cut
                   9929: 
                   9930: sub start_page {
1.309     albertel 9931:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9932:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9933: 
1.315     albertel 9934:     $env{'internal.start_page'}++;
1.1359    raeburn  9935:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9936: 
1.338     albertel 9937:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9938:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9939:     }
1.1316    raeburn  9940: 
                   9941:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9942:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9943:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9944:                 $args->{'no_primary_menu'} = 1;
                   9945:             }
                   9946:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9947:                 $args->{'no_inline_menu'} = 1;
                   9948:             }
                   9949:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9950:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9951:             }
                   9952:         } else {
                   9953:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9954:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9955:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9956:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9957:                     $args->{'no_primary_menu'} = 1;
                   9958:                 }
                   9959:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9960:                     $args->{'no_inline_menu'} = 1;
                   9961:                 }
                   9962:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9963:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9964:                 }
                   9965:             }
                   9966:         }
1.1316    raeburn  9967:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9968:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9969:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9970:     } elsif ($env{'request.course.id'}) {
                   9971:         my $expiretime=600;
                   9972:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9973:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9974:         }
                   9975:         my ($deeplinkmenu,$menuref);
                   9976:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9977:         if ($menucoll) {
                   9978:             if (ref($menuref) eq 'HASH') {
                   9979:                 %menu = %{$menuref};
                   9980:             }
                   9981:             if ($menu{'top'} eq 'n') {
                   9982:                 $args->{'no_primary_menu'} = 1;
                   9983:             }
                   9984:             if ($menu{'inline'} eq 'n') {
                   9985:                 unless (&Apache::lonnet::allowed('opa')) {
                   9986:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9987:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9988:                     my $crstype = &course_type();
                   9989:                     my $now = time;
                   9990:                     my $ccrole;
                   9991:                     if ($crstype eq 'Community') {
                   9992:                         $ccrole = 'co';
                   9993:                     } else {
                   9994:                         $ccrole = 'cc';
                   9995:                     }
                   9996:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9997:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9998:                         if ((($start) && ($start<0)) ||
                   9999:                             (($end) && ($end<$now))  ||
                   10000:                             (($start) && ($now<$start))) {
                   10001:                             $args->{'no_inline_menu'} = 1;
                   10002:                         }
                   10003:                     } else {
                   10004:                         $args->{'no_inline_menu'} = 1;
                   10005:                     }
                   10006:                 }
                   10007:             }
                   10008:         }
1.1316    raeburn  10009:     }
1.1359    raeburn  10010: 
1.1385    raeburn  10011:     my $showncrumbs;
1.338     albertel 10012:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10013: 	if ($args->{'frameset'}) {
                   10014: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10015: 						$args->{'add_entries'});
                   10016: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10017:         } else {
                   10018:             $result .=
                   10019:                 &bodytag($title, 
                   10020:                          $args->{'function'},       $args->{'add_entries'},
                   10021:                          $args->{'only_body'},      $args->{'domain'},
                   10022:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10023:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10024:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10025:                          \%menu,\$showncrumbs);
1.831     bisitz   10026:         }
1.330     albertel 10027:     }
1.338     albertel 10028: 
1.315     albertel 10029:     if ($args->{'js_ready'}) {
1.713     kaisler  10030: 		$result = &js_ready($result);
1.315     albertel 10031:     }
1.320     albertel 10032:     if ($args->{'html_encode'}) {
1.713     kaisler  10033: 		$result = &html_encode($result);
                   10034:     }
                   10035: 
1.813     bisitz   10036:     # Preparation for new and consistent functionlist at top of screen
                   10037:     # if ($args->{'functionlist'}) {
                   10038:     #            $result .= &build_functionlist();
                   10039:     #}
                   10040: 
1.964     droeschl 10041:     # Don't add anything more if only_body wanted or in const space
                   10042:     return $result if    $args->{'only_body'} 
                   10043:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10044: 
                   10045:     #Breadcrumbs
1.758     kaisler  10046:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10047:         unless ($showncrumbs) {
1.758     kaisler  10048: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10049: 		#if any br links exists, add them to the breadcrumbs
                   10050: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10051: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10052: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10053: 			}
                   10054: 		}
1.1096    raeburn  10055:                 # if @advtools array contains items add then to the breadcrumbs
                   10056:                 if (@advtools > 0) {
                   10057:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10058:                 }
1.1272    raeburn  10059:                 my $menulink;
                   10060:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10061:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10062:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10063:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10064:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10065:                      (!$env{'request.role.adv'}))) {
                   10066:                     $menulink = 0;
                   10067:                 } else {
                   10068:                     undef($menulink);
                   10069:                 }
1.1385    raeburn  10070:                 my $linkprotout;
                   10071:                 if ($env{'request.deeplink.login'}) {
                   10072:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10073:                     if ($linkprotout) {
                   10074:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10075:                     }
                   10076:                 }
1.758     kaisler  10077: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10078: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10079: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10080:                                                                        '',$menulink,'',
                   10081:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10082:                 } else {
1.1437    raeburn  10083: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10084:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10085: 		}
1.1385    raeburn  10086:         }
1.320     albertel 10087:     }
1.315     albertel 10088:     return $result;
1.306     albertel 10089: }
                   10090: 
                   10091: sub end_page {
1.315     albertel 10092:     my ($args) = @_;
                   10093:     $env{'internal.end_page'}++;
1.330     albertel 10094:     my $result;
1.335     albertel 10095:     if ($args->{'discussion'}) {
                   10096: 	my ($target,$parser);
                   10097: 	if (ref($args->{'discussion'})) {
                   10098: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10099: 				$args->{'discussion'}{'parser'});
                   10100: 	}
                   10101: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10102:     }
1.330     albertel 10103:     if ($args->{'frameset'}) {
                   10104: 	$result .= '</frameset>';
                   10105:     } else {
1.635     raeburn  10106: 	$result .= &endbodytag($args);
1.330     albertel 10107:     }
1.1080    raeburn  10108:     unless ($args->{'notbody'}) {
                   10109:         $result .= "\n</html>";
                   10110:     }
1.330     albertel 10111: 
1.315     albertel 10112:     if ($args->{'js_ready'}) {
1.317     albertel 10113: 	$result = &js_ready($result);
1.315     albertel 10114:     }
1.335     albertel 10115: 
1.320     albertel 10116:     if ($args->{'html_encode'}) {
                   10117: 	$result = &html_encode($result);
                   10118:     }
1.335     albertel 10119: 
1.315     albertel 10120:     return $result;
                   10121: }
                   10122: 
1.1359    raeburn  10123: sub menucoll_in_effect {
                   10124:     my ($menucoll,$deeplinkmenu,%menu);
                   10125:     if ($env{'request.course.id'}) {
                   10126:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10127:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10128:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10129:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10130:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10131:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10132:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10133:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10134:                     if (ref($navmap)) {
                   10135:                         $deeplink = $navmap->get_mapparam(undef,
                   10136:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10137:                                                           '0.deeplink');
1.1370    raeburn  10138:                     } else {
                   10139:                         $check_login_symb = 1;
1.1362    raeburn  10140:                     }
                   10141:                 } else {
1.1370    raeburn  10142:                     my $symb = &Apache::lonnet::symbread();
                   10143:                     if ($symb) {
                   10144:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10145:                     } else {
                   10146:                         $check_login_symb = 1;
                   10147:                     }
1.1362    raeburn  10148:                 }
                   10149:             } else {
1.1370    raeburn  10150:                 $check_login_symb = 1;
                   10151:             }
                   10152:             if ($check_login_symb) {
1.1362    raeburn  10153:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10154:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10155:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10156:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10157:                     if (ref($navmap)) {
                   10158:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10159:                     }
                   10160:                 } else {
                   10161:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10162:                 }
                   10163:             }
1.1359    raeburn  10164:             if ($deeplink ne '') {
1.1378    raeburn  10165:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10166:                 if ($display =~ /^\d+$/) {
                   10167:                     $deeplinkmenu = 1;
                   10168:                     $menucoll = $display;
                   10169:                 }
                   10170:             }
                   10171:         }
                   10172:         if ($menucoll) {
                   10173:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10174:         }
                   10175:     }
                   10176:     return ($menucoll,$deeplinkmenu,\%menu);
                   10177: }
                   10178: 
1.1362    raeburn  10179: sub deeplink_login_symb {
                   10180:     my ($cnum,$cdom) = @_;
                   10181:     my $login_symb;
                   10182:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10183:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10184:     }
                   10185:     return $login_symb;
                   10186: }
                   10187: 
                   10188: sub symb_from_tinyurl {
                   10189:     my ($url,$cnum,$cdom) = @_;
                   10190:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10191:         my $key = $1;
                   10192:         my ($tinyurl,$login);
                   10193:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10194:         if (defined($cached)) {
                   10195:             $tinyurl = $result;
                   10196:         } else {
                   10197:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10198:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10199:             if ($currtiny{$key} ne '') {
                   10200:                 $tinyurl = $currtiny{$key};
                   10201:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10202:             }
1.1364    raeburn  10203:         }
                   10204:         if ($tinyurl ne '') {
                   10205:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10206:             if (wantarray) {
                   10207:                 return ($cnumreq,$symb);
                   10208:             } elsif ($cnumreq eq $cnum) {
                   10209:                 return $symb;
1.1362    raeburn  10210:             }
                   10211:         }
                   10212:     }
1.1364    raeburn  10213:     if (wantarray) {
                   10214:         return ();
                   10215:     } else {
                   10216:         return;
                   10217:     }
1.1362    raeburn  10218: }
                   10219: 
1.1405    raeburn  10220: sub usable_exttools {
                   10221:     my %tooltypes;
                   10222:     if ($env{'request.course.id'}) {
                   10223:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10224:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10225:                %tooltypes = (
                   10226:                              crs => 1,
                   10227:                              dom => 1,
                   10228:                             );
                   10229:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10230:                $tooltypes{'crs'} = 1;
                   10231:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10232:                $tooltypes{'dom'} = 1;
                   10233:            }
                   10234:         } else {
                   10235:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10236:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10237:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10238:             if ($crstype eq '') {
                   10239:                 $crstype = 'course';
                   10240:             }
                   10241:             if ($crstype eq 'course') {
                   10242:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10243:                     $crstype = 'official';
                   10244:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10245:                     $crstype = 'textbook';
                   10246:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10247:                     $crstype = 'lti';
                   10248:                 } else {
                   10249:                     $crstype = 'unofficial';
                   10250:                 }
                   10251:             }
                   10252:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10253:             if ($domdefaults{$crstype.'domexttool'}) {
                   10254:                 $tooltypes{'dom'} = 1;
                   10255:             }
                   10256:             if ($domdefaults{$crstype.'exttool'}) {
                   10257:                 $tooltypes{'crs'} = 1;
                   10258:             }
                   10259:         }
                   10260:     }
                   10261:     return %tooltypes;
                   10262: }
                   10263: 
1.1034    www      10264: sub wishlist_window {
                   10265:     return(<<'ENDWISHLIST');
1.1046    raeburn  10266: <script type="text/javascript">
1.1034    www      10267: // <![CDATA[
                   10268: // <!-- BEGIN LON-CAPA Internal
                   10269: function set_wishlistlink(title, path) {
                   10270:     if (!title) {
                   10271:         title = document.title;
                   10272:         title = title.replace(/^LON-CAPA /,'');
                   10273:     }
1.1175    raeburn  10274:     title = encodeURIComponent(title);
1.1203    raeburn  10275:     title = title.replace("'","\\\'");
1.1034    www      10276:     if (!path) {
                   10277:         path = location.pathname;
                   10278:     }
1.1175    raeburn  10279:     path = encodeURIComponent(path);
1.1203    raeburn  10280:     path = path.replace("'","\\\'");
1.1034    www      10281:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10282:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10283: }
                   10284: // END LON-CAPA Internal -->
                   10285: // ]]>
                   10286: </script>
                   10287: ENDWISHLIST
                   10288: }
                   10289: 
1.1030    www      10290: sub modal_window {
                   10291:     return(<<'ENDMODAL');
1.1046    raeburn  10292: <script type="text/javascript">
1.1030    www      10293: // <![CDATA[
                   10294: // <!-- BEGIN LON-CAPA Internal
                   10295: var modalWindow = {
                   10296: 	parent:"body",
                   10297: 	windowId:null,
                   10298: 	content:null,
                   10299: 	width:null,
                   10300: 	height:null,
                   10301: 	close:function()
                   10302: 	{
                   10303: 	        $(".LCmodal-window").remove();
                   10304: 	        $(".LCmodal-overlay").remove();
                   10305: 	},
                   10306: 	open:function()
                   10307: 	{
                   10308: 		var modal = "";
                   10309: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10310: 		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;\">";
                   10311: 		modal += this.content;
                   10312: 		modal += "</div>";	
                   10313: 
                   10314: 		$(this.parent).append(modal);
                   10315: 
                   10316: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10317: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10318: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10319: 	}
                   10320: };
1.1140    raeburn  10321: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10322: 	{
1.1266    raeburn  10323:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10324: 		modalWindow.windowId = "myModal";
                   10325: 		modalWindow.width = width;
                   10326: 		modalWindow.height = height;
1.1196    raeburn  10327: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10328: 		modalWindow.open();
1.1208    raeburn  10329: 	};
1.1030    www      10330: // END LON-CAPA Internal -->
                   10331: // ]]>
                   10332: </script>
                   10333: ENDMODAL
                   10334: }
                   10335: 
                   10336: sub modal_link {
1.1140    raeburn  10337:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10338:     unless ($width) { $width=480; }
                   10339:     unless ($height) { $height=400; }
1.1031    www      10340:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10341:     unless ($transparency) { $transparency='true'; }
                   10342: 
1.1074    raeburn  10343:     my $target_attr;
                   10344:     if (defined($target)) {
                   10345:         $target_attr = 'target="'.$target.'"';
                   10346:     }
                   10347:     return <<"ENDLINK";
1.1336    raeburn  10348: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10349: ENDLINK
1.1030    www      10350: }
                   10351: 
1.1032    www      10352: sub modal_adhoc_script {
1.1365    raeburn  10353:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10354:     my $mathjax;
                   10355:     if ($possmathjax) {
                   10356:         $mathjax = <<'ENDJAX';
                   10357:                if (typeof MathJax == 'object') {
                   10358:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10359:                }
                   10360: ENDJAX
                   10361:     }
1.1032    www      10362:     return (<<ENDADHOC);
1.1046    raeburn  10363: <script type="text/javascript">
1.1032    www      10364: // <![CDATA[
                   10365:         var $funcname = function()
                   10366:         {
                   10367:                 modalWindow.windowId = "myModal";
                   10368:                 modalWindow.width = $width;
                   10369:                 modalWindow.height = $height;
                   10370:                 modalWindow.content = '$content';
                   10371:                 modalWindow.open();
1.1365    raeburn  10372:                 $mathjax
1.1032    www      10373:         };  
                   10374: // ]]>
                   10375: </script>
                   10376: ENDADHOC
                   10377: }
                   10378: 
1.1041    www      10379: sub modal_adhoc_inner {
1.1365    raeburn  10380:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10381:     my $innerwidth=$width-20;
                   10382:     $content=&js_ready(
1.1140    raeburn  10383:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10384:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10385:                  $content.
1.1041    www      10386:                  &end_scrollbox().
1.1140    raeburn  10387:                  &end_page()
1.1041    www      10388:              );
1.1365    raeburn  10389:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10390: }
                   10391: 
                   10392: sub modal_adhoc_window {
1.1365    raeburn  10393:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10394:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10395:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10396: }
                   10397: 
                   10398: sub modal_adhoc_launch {
                   10399:     my ($funcname,$width,$height,$content)=@_;
                   10400:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10401: <script type="text/javascript">
                   10402: // <![CDATA[
                   10403: $funcname();
                   10404: // ]]>
                   10405: </script>
                   10406: ENDLAUNCH
                   10407: }
                   10408: 
                   10409: sub modal_adhoc_close {
                   10410:     return (<<ENDCLOSE);
                   10411: <script type="text/javascript">
                   10412: // <![CDATA[
                   10413: modalWindow.close();
                   10414: // ]]>
                   10415: </script>
                   10416: ENDCLOSE
                   10417: }
                   10418: 
1.1038    www      10419: sub togglebox_script {
                   10420:    return(<<ENDTOGGLE);
                   10421: <script type="text/javascript"> 
                   10422: // <![CDATA[
                   10423: function LCtoggleDisplay(id,hidetext,showtext) {
                   10424:    link = document.getElementById(id + "link").childNodes[0];
                   10425:    with (document.getElementById(id).style) {
                   10426:       if (display == "none" ) {
                   10427:           display = "inline";
                   10428:           link.nodeValue = hidetext;
                   10429:         } else {
                   10430:           display = "none";
                   10431:           link.nodeValue = showtext;
                   10432:        }
                   10433:    }
                   10434: }
                   10435: // ]]>
                   10436: </script>
                   10437: ENDTOGGLE
                   10438: }
                   10439: 
1.1039    www      10440: sub start_togglebox {
                   10441:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10442:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10443:     unless ($showtext) { $showtext=&mt('show'); }
                   10444:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10445:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10446:     return &start_data_table().
                   10447:            &start_data_table_header_row().
                   10448:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10449:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10450:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10451:            &end_data_table_header_row().
                   10452:            '<tr id="'.$id.'" style="display:none""><td>';
                   10453: }
                   10454: 
                   10455: sub end_togglebox {
                   10456:     return '</td></tr>'.&end_data_table();
                   10457: }
                   10458: 
1.1041    www      10459: sub LCprogressbar_script {
1.1302    raeburn  10460:    my ($id,$number_to_do)=@_;
                   10461:    if ($number_to_do) {
                   10462:        return(<<ENDPROGRESS);
1.1041    www      10463: <script type="text/javascript">
                   10464: // <![CDATA[
1.1045    www      10465: \$('#progressbar$id').progressbar({
1.1041    www      10466:   value: 0,
                   10467:   change: function(event, ui) {
                   10468:     var newVal = \$(this).progressbar('option', 'value');
                   10469:     \$('.pblabel', this).text(LCprogressTxt);
                   10470:   }
                   10471: });
                   10472: // ]]>
                   10473: </script>
                   10474: ENDPROGRESS
1.1302    raeburn  10475:    } else {
                   10476:        return(<<ENDPROGRESS);
                   10477: <script type="text/javascript">
                   10478: // <![CDATA[
                   10479: \$('#progressbar$id').progressbar({
                   10480:   value: false,
                   10481:   create: function(event, ui) {
                   10482:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10483:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10484:   }
                   10485: });
                   10486: // ]]>
                   10487: </script>
                   10488: ENDPROGRESS
                   10489:    }
1.1041    www      10490: }
                   10491: 
                   10492: sub LCprogressbarUpdate_script {
                   10493:    return(<<ENDPROGRESSUPDATE);
                   10494: <style type="text/css">
                   10495: .ui-progressbar { position:relative; }
1.1302    raeburn  10496: .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      10497: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10498: </style>
                   10499: <script type="text/javascript">
                   10500: // <![CDATA[
1.1045    www      10501: var LCprogressTxt='---';
                   10502: 
1.1302    raeburn  10503: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10504:    LCprogressTxt=progresstext;
1.1302    raeburn  10505:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10506:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10507:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10508:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10509:    } else {
                   10510:        \$('#progressbar'+id).progressbar('value',percent);
                   10511:    }
1.1041    www      10512: }
                   10513: // ]]>
                   10514: </script>
                   10515: ENDPROGRESSUPDATE
                   10516: }
                   10517: 
1.1042    www      10518: my $LClastpercent;
1.1045    www      10519: my $LCidcnt;
                   10520: my $LCcurrentid;
1.1042    www      10521: 
1.1041    www      10522: sub LCprogressbar {
1.1302    raeburn  10523:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10524:     $LClastpercent=0;
1.1045    www      10525:     $LCidcnt++;
                   10526:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10527:     my ($starting,$content);
                   10528:     if ($number_to_do) {
                   10529:         $starting=&mt('Starting');
                   10530:         $content=(<<ENDPROGBAR);
                   10531: $preamble
1.1045    www      10532:   <div id="progressbar$LCcurrentid">
1.1041    www      10533:     <span class="pblabel">$starting</span>
                   10534:   </div>
                   10535: ENDPROGBAR
1.1302    raeburn  10536:     } else {
                   10537:         $starting=&mt('Loading...');
                   10538:         $LClastpercent='false';
                   10539:         $content=(<<ENDPROGBAR);
                   10540: $preamble
                   10541:   <div id="progressbar$LCcurrentid">
                   10542:       <div class="progress-label">$starting</div>
                   10543:   </div>
                   10544: ENDPROGBAR
                   10545:     }
                   10546:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10547: }
                   10548: 
                   10549: sub LCprogressbarUpdate {
1.1302    raeburn  10550:     my ($r,$val,$text,$number_to_do)=@_;
                   10551:     if ($number_to_do) {
                   10552:         unless ($val) { 
                   10553:             if ($LClastpercent) {
                   10554:                 $val=$LClastpercent;
                   10555:             } else {
                   10556:                 $val=0;
                   10557:             }
                   10558:         }
                   10559:         if ($val<0) { $val=0; }
                   10560:         if ($val>100) { $val=0; }
                   10561:         $LClastpercent=$val;
                   10562:         unless ($text) { $text=$val.'%'; }
                   10563:     } else {
                   10564:         $val = 'false';
1.1042    www      10565:     }
1.1041    www      10566:     $text=&js_ready($text);
1.1044    www      10567:     &r_print($r,<<ENDUPDATE);
1.1041    www      10568: <script type="text/javascript">
                   10569: // <![CDATA[
1.1302    raeburn  10570: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10571: // ]]>
                   10572: </script>
                   10573: ENDUPDATE
1.1035    www      10574: }
                   10575: 
1.1042    www      10576: sub LCprogressbarClose {
                   10577:     my ($r)=@_;
                   10578:     $LClastpercent=0;
1.1044    www      10579:     &r_print($r,<<ENDCLOSE);
1.1042    www      10580: <script type="text/javascript">
                   10581: // <![CDATA[
1.1045    www      10582: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10583: // ]]>
                   10584: </script>
                   10585: ENDCLOSE
1.1044    www      10586: }
                   10587: 
                   10588: sub r_print {
                   10589:     my ($r,$to_print)=@_;
                   10590:     if ($r) {
                   10591:       $r->print($to_print);
                   10592:       $r->rflush();
                   10593:     } else {
                   10594:       print($to_print);
                   10595:     }
1.1042    www      10596: }
                   10597: 
1.320     albertel 10598: sub html_encode {
                   10599:     my ($result) = @_;
                   10600: 
1.322     albertel 10601:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10602:     
                   10603:     return $result;
                   10604: }
1.1044    www      10605: 
1.317     albertel 10606: sub js_ready {
                   10607:     my ($result) = @_;
                   10608: 
1.323     albertel 10609:     $result =~ s/[\n\r]/ /xmsg;
                   10610:     $result =~ s/\\/\\\\/xmsg;
                   10611:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10612:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10613:     
                   10614:     return $result;
                   10615: }
                   10616: 
1.315     albertel 10617: sub validate_page {
                   10618:     if (  exists($env{'internal.start_page'})
1.316     albertel 10619: 	  &&     $env{'internal.start_page'} > 1) {
                   10620: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10621: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10622: 				 $ENV{'request.filename'});
1.315     albertel 10623:     }
                   10624:     if (  exists($env{'internal.end_page'})
1.316     albertel 10625: 	  &&     $env{'internal.end_page'} > 1) {
                   10626: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10627: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10628: 				 $env{'request.filename'});
1.315     albertel 10629:     }
                   10630:     if (     exists($env{'internal.start_page'})
                   10631: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10632: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10633: 				 $env{'request.filename'});
1.315     albertel 10634:     }
                   10635:     if (   ! exists($env{'internal.start_page'})
                   10636: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10637: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10638: 				 $env{'request.filename'});
1.315     albertel 10639:     }
1.306     albertel 10640: }
1.315     albertel 10641: 
1.996     www      10642: 
                   10643: sub start_scrollbox {
1.1140    raeburn  10644:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10645:     unless ($outerwidth) { $outerwidth='520px'; }
                   10646:     unless ($width) { $width='500px'; }
                   10647:     unless ($height) { $height='200px'; }
1.1075    raeburn  10648:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10649:     if ($id ne '') {
1.1140    raeburn  10650:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10651:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10652:     }
1.1075    raeburn  10653:     if ($bgcolor ne '') {
                   10654:         $tdcol = "background-color: $bgcolor;";
                   10655:     }
1.1137    raeburn  10656:     my $nicescroll_js;
                   10657:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10658:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10659:     }
                   10660:     return <<"END";
                   10661: $nicescroll_js
                   10662: 
                   10663: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10664: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10665: END
                   10666: }
                   10667: 
                   10668: sub end_scrollbox {
                   10669:     return '</div></td></tr></table>';
                   10670: }
                   10671: 
                   10672: sub nicescroll_javascript {
                   10673:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10674:     my %options;
                   10675:     if (ref($cursor) eq 'HASH') {
                   10676:         %options = %{$cursor};
                   10677:     }
                   10678:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10679:         $options{'railalign'} = 'left';
                   10680:     }
                   10681:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10682:         my $function  = &get_users_function();
                   10683:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10684:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10685:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10686:         }
1.1140    raeburn  10687:     }
                   10688:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10689:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10690:             $options{'cursoropacity'}='1.0';
                   10691:         }
1.1140    raeburn  10692:     } else {
                   10693:         $options{'cursoropacity'}='1.0';
                   10694:     }
                   10695:     if ($options{'cursorfixedheight'} eq 'none') {
                   10696:         delete($options{'cursorfixedheight'});
                   10697:     } else {
                   10698:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10699:     }
                   10700:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10701:         delete($options{'railoffset'});
                   10702:     }
                   10703:     my @niceoptions;
                   10704:     while (my($key,$value) = each(%options)) {
                   10705:         if ($value =~ /^\{.+\}$/) {
                   10706:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10707:         } else {
1.1140    raeburn  10708:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10709:         }
1.1140    raeburn  10710:     }
                   10711:     my $nicescroll_js = '
1.1137    raeburn  10712: $(document).ready(
1.1140    raeburn  10713:       function() {
                   10714:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10715:       }
1.1137    raeburn  10716: );
                   10717: ';
1.1140    raeburn  10718:     if ($framecheck) {
                   10719:         $nicescroll_js .= '
                   10720: function expand_div(caller) {
                   10721:     if (top === self) {
                   10722:         document.getElementById("'.$id.'").style.width = "auto";
                   10723:         document.getElementById("'.$id.'").style.height = "auto";
                   10724:     } else {
                   10725:         try {
                   10726:             if (parent.frames) {
                   10727:                 if (parent.frames.length > 1) {
                   10728:                     var framesrc = parent.frames[1].location.href;
                   10729:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10730:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10731:                         document.getElementById("'.$id.'").style.width = "auto";
                   10732:                         document.getElementById("'.$id.'").style.height = "auto";
                   10733:                     }
                   10734:                 }
                   10735:             }
                   10736:         } catch (e) {
                   10737:             return;
                   10738:         }
1.1137    raeburn  10739:     }
1.1140    raeburn  10740:     return;
1.996     www      10741: }
1.1140    raeburn  10742: ';
                   10743:     }
                   10744:     if ($needjsready) {
                   10745:         $nicescroll_js = '
                   10746: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10747:     } else {
                   10748:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10749:     }
                   10750:     return $nicescroll_js;
1.996     www      10751: }
                   10752: 
1.318     albertel 10753: sub simple_error_page {
1.1150    bisitz   10754:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10755:     my %displayargs;
1.1151    raeburn  10756:     if (ref($args) eq 'HASH') {
                   10757:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10758:         if ($args->{'only_body'}) {
                   10759:             $displayargs{'only_body'} = 1;
                   10760:         }
                   10761:         if ($args->{'no_nav_bar'}) {
                   10762:             $displayargs{'no_nav_bar'} = 1;
                   10763:         }
1.1151    raeburn  10764:     } else {
                   10765:         $msg = &mt($msg);
                   10766:     }
1.1150    bisitz   10767: 
1.318     albertel 10768:     my $page =
1.1304    raeburn  10769: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10770: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10771: 	&Apache::loncommon::end_page();
                   10772:     if (ref($r)) {
                   10773: 	$r->print($page);
1.327     albertel 10774: 	return;
1.318     albertel 10775:     }
                   10776:     return $page;
                   10777: }
1.347     albertel 10778: 
                   10779: {
1.610     albertel 10780:     my @row_count;
1.961     onken    10781: 
                   10782:     sub start_data_table_count {
                   10783:         unshift(@row_count, 0);
                   10784:         return;
                   10785:     }
                   10786: 
                   10787:     sub end_data_table_count {
                   10788:         shift(@row_count);
                   10789:         return;
                   10790:     }
                   10791: 
1.347     albertel 10792:     sub start_data_table {
1.1018    raeburn  10793: 	my ($add_class,$id) = @_;
1.422     albertel 10794: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10795:         my $table_id;
                   10796:         if (defined($id)) {
                   10797:             $table_id = ' id="'.$id.'"';
                   10798:         }
1.961     onken    10799: 	&start_data_table_count();
1.1018    raeburn  10800: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10801:     }
                   10802: 
                   10803:     sub end_data_table {
1.961     onken    10804: 	&end_data_table_count();
1.389     albertel 10805: 	return '</table>'."\n";;
1.347     albertel 10806:     }
                   10807: 
                   10808:     sub start_data_table_row {
1.974     wenzelju 10809: 	my ($add_class, $id) = @_;
1.610     albertel 10810: 	$row_count[0]++;
                   10811: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10812: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10813:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10814:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10815:     }
1.471     banghart 10816:     
                   10817:     sub continue_data_table_row {
1.974     wenzelju 10818: 	my ($add_class, $id) = @_;
1.610     albertel 10819: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10820: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10821:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10822:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10823:     }
1.347     albertel 10824: 
                   10825:     sub end_data_table_row {
1.389     albertel 10826: 	return '</tr>'."\n";;
1.347     albertel 10827:     }
1.367     www      10828: 
1.421     albertel 10829:     sub start_data_table_empty_row {
1.707     bisitz   10830: #	$row_count[0]++;
1.421     albertel 10831: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10832:     }
                   10833: 
                   10834:     sub end_data_table_empty_row {
                   10835: 	return '</tr>'."\n";;
                   10836:     }
                   10837: 
1.367     www      10838:     sub start_data_table_header_row {
1.389     albertel 10839: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10840:     }
                   10841: 
                   10842:     sub end_data_table_header_row {
1.389     albertel 10843: 	return '</tr>'."\n";;
1.367     www      10844:     }
1.890     droeschl 10845: 
                   10846:     sub data_table_caption {
                   10847:         my $caption = shift;
                   10848:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10849:     }
1.347     albertel 10850: }
                   10851: 
1.548     albertel 10852: =pod
                   10853: 
                   10854: =item * &inhibit_menu_check($arg)
                   10855: 
                   10856: Checks for a inhibitmenu state and generates output to preserve it
                   10857: 
                   10858: Inputs:         $arg - can be any of
                   10859:                      - undef - in which case the return value is a string 
                   10860:                                to add  into arguments list of a uri
                   10861:                      - 'input' - in which case the return value is a HTML
                   10862:                                  <form> <input> field of type hidden to
                   10863:                                  preserve the value
                   10864:                      - a url - in which case the return value is the url with
                   10865:                                the neccesary cgi args added to preserve the
                   10866:                                inhibitmenu state
                   10867:                      - a ref to a url - no return value, but the string is
                   10868:                                         updated to include the neccessary cgi
                   10869:                                         args to preserve the inhibitmenu state
                   10870: 
                   10871: =cut
                   10872: 
                   10873: sub inhibit_menu_check {
                   10874:     my ($arg) = @_;
                   10875:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10876:     if ($arg eq 'input') {
                   10877: 	if ($env{'form.inhibitmenu'}) {
                   10878: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10879: 	} else {
                   10880: 	    return
                   10881: 	}
                   10882:     }
                   10883:     if ($env{'form.inhibitmenu'}) {
                   10884: 	if (ref($arg)) {
                   10885: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10886: 	} elsif ($arg eq '') {
                   10887: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10888: 	} else {
                   10889: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10890: 	}
                   10891:     }
                   10892:     if (!ref($arg)) {
                   10893: 	return $arg;
                   10894:     }
                   10895: }
                   10896: 
1.251     albertel 10897: ###############################################
1.182     matthew  10898: 
                   10899: =pod
                   10900: 
1.549     albertel 10901: =back
                   10902: 
                   10903: =head1 User Information Routines
                   10904: 
                   10905: =over 4
                   10906: 
1.405     albertel 10907: =item * &get_users_function()
1.182     matthew  10908: 
                   10909: Used by &bodytag to determine the current users primary role.
                   10910: Returns either 'student','coordinator','admin', or 'author'.
                   10911: 
                   10912: =cut
                   10913: 
                   10914: ###############################################
                   10915: sub get_users_function {
1.815     tempelho 10916:     my $function = 'norole';
1.818     tempelho 10917:     if ($env{'request.role'}=~/^(st)/) {
                   10918:         $function='student';
                   10919:     }
1.907     raeburn  10920:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10921:         $function='coordinator';
                   10922:     }
1.258     albertel 10923:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10924:         $function='admin';
                   10925:     }
1.826     bisitz   10926:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10927:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10928:         $function='author';
                   10929:     }
                   10930:     return $function;
1.54      www      10931: }
1.99      www      10932: 
                   10933: ###############################################
                   10934: 
1.233     raeburn  10935: =pod
                   10936: 
1.821     raeburn  10937: =item * &show_course()
                   10938: 
                   10939: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10940: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10941: 
                   10942: Inputs:
                   10943: None
                   10944: 
                   10945: Outputs:
                   10946: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10947: 
                   10948: =cut
                   10949: 
                   10950: ###############################################
                   10951: sub show_course {
1.1408    raeburn  10952:     my ($udom,$uname) = @_;
                   10953:     if (($udom ne '') && ($uname ne '')) {
                   10954:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10955:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10956:                 return 0;
                   10957:             } else {
                   10958:                 return 1;
                   10959:             }
                   10960:         }
                   10961:     }
1.821     raeburn  10962:     my $course = !$env{'user.adv'};
                   10963:     if (!$env{'user.adv'}) {
                   10964:         foreach my $env (keys(%env)) {
                   10965:             next if ($env !~ m/^user\.priv\./);
                   10966:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10967:                 $course = 0;
                   10968:                 last;
                   10969:             }
                   10970:         }
                   10971:     }
                   10972:     return $course;
                   10973: }
                   10974: 
                   10975: ###############################################
                   10976: 
                   10977: =pod
                   10978: 
1.542     raeburn  10979: =item * &check_user_status()
1.274     raeburn  10980: 
                   10981: Determines current status of supplied role for a
                   10982: specific user. Roles can be active, previous or future.
                   10983: 
                   10984: Inputs: 
                   10985: user's domain, user's username, course's domain,
1.375     raeburn  10986: course's number, optional section ID.
1.274     raeburn  10987: 
                   10988: Outputs:
                   10989: role status: active, previous or future. 
                   10990: 
                   10991: =cut
                   10992: 
                   10993: sub check_user_status {
1.412     raeburn  10994:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10995:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10996:     my @uroles = keys(%userinfo);
1.274     raeburn  10997:     my $srchstr;
                   10998:     my $active_chk = 'none';
1.412     raeburn  10999:     my $now = time;
1.274     raeburn  11000:     if (@uroles > 0) {
1.908     raeburn  11001:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11002:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11003:         } else {
1.412     raeburn  11004:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11005:         }
                   11006:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11007:             my $role_end = 0;
                   11008:             my $role_start = 0;
                   11009:             $active_chk = 'active';
1.412     raeburn  11010:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11011:                 $role_end = $1;
                   11012:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11013:                     $role_start = $1;
1.274     raeburn  11014:                 }
                   11015:             }
                   11016:             if ($role_start > 0) {
1.412     raeburn  11017:                 if ($now < $role_start) {
1.274     raeburn  11018:                     $active_chk = 'future';
                   11019:                 }
                   11020:             }
                   11021:             if ($role_end > 0) {
1.412     raeburn  11022:                 if ($now > $role_end) {
1.274     raeburn  11023:                     $active_chk = 'previous';
                   11024:                 }
                   11025:             }
                   11026:         }
                   11027:     }
                   11028:     return $active_chk;
                   11029: }
                   11030: 
                   11031: ###############################################
                   11032: 
                   11033: =pod
                   11034: 
1.405     albertel 11035: =item * &get_sections()
1.233     raeburn  11036: 
                   11037: Determines all the sections for a course including
                   11038: sections with students and sections containing other roles.
1.419     raeburn  11039: Incoming parameters: 
                   11040: 
                   11041: 1. domain
                   11042: 2. course number 
                   11043: 3. reference to array containing roles for which sections should 
                   11044: be gathered (optional).
                   11045: 4. reference to array containing status types for which sections 
                   11046: should be gathered (optional).
                   11047: 
                   11048: If the third argument is undefined, sections are gathered for any role. 
                   11049: If the fourth argument is undefined, sections are gathered for any status.
                   11050: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11051:  
1.374     raeburn  11052: Returns section hash (keys are section IDs, values are
                   11053: number of users in each section), subject to the
1.419     raeburn  11054: optional roles filter, optional status filter 
1.233     raeburn  11055: 
                   11056: =cut
                   11057: 
                   11058: ###############################################
                   11059: sub get_sections {
1.419     raeburn  11060:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11061:     if (!defined($cdom) || !defined($cnum)) {
                   11062:         my $cid =  $env{'request.course.id'};
                   11063: 
                   11064: 	return if (!defined($cid));
                   11065: 
                   11066:         $cdom = $env{'course.'.$cid.'.domain'};
                   11067:         $cnum = $env{'course.'.$cid.'.num'};
                   11068:     }
                   11069: 
                   11070:     my %sectioncount;
1.419     raeburn  11071:     my $now = time;
1.240     albertel 11072: 
1.1118    raeburn  11073:     my $check_students = 1;
                   11074:     my $only_students = 0;
                   11075:     if (ref($possible_roles) eq 'ARRAY') {
                   11076:         if (grep(/^st$/,@{$possible_roles})) {
                   11077:             if (@{$possible_roles} == 1) {
                   11078:                 $only_students = 1;
                   11079:             }
                   11080:         } else {
                   11081:             $check_students = 0;
                   11082:         }
                   11083:     }
                   11084: 
                   11085:     if ($check_students) { 
1.276     albertel 11086: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11087: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11088: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11089:         my $start_index = &Apache::loncoursedata::CL_START();
                   11090:         my $end_index = &Apache::loncoursedata::CL_END();
                   11091:         my $status;
1.366     albertel 11092: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11093: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11094: 				                     $data->[$status_index],
                   11095:                                                      $data->[$start_index],
                   11096:                                                      $data->[$end_index]);
                   11097:             if ($stu_status eq 'Active') {
                   11098:                 $status = 'active';
                   11099:             } elsif ($end < $now) {
                   11100:                 $status = 'previous';
                   11101:             } elsif ($start > $now) {
                   11102:                 $status = 'future';
                   11103:             } 
                   11104: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11105:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11106:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11107: 		    $sectioncount{$section}++;
                   11108:                 }
1.240     albertel 11109: 	    }
                   11110: 	}
                   11111:     }
1.1118    raeburn  11112:     if ($only_students) {
                   11113:         return %sectioncount;
                   11114:     }
1.240     albertel 11115:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11116:     foreach my $user (sort(keys(%courseroles))) {
                   11117: 	if ($user !~ /^(\w{2})/) { next; }
                   11118: 	my ($role) = ($user =~ /^(\w{2})/);
                   11119: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11120: 	my ($section,$status);
1.240     albertel 11121: 	if ($role eq 'cr' &&
                   11122: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11123: 	    $section=$1;
                   11124: 	}
                   11125: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11126: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11127:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11128:         if ($end == -1 && $start == -1) {
                   11129:             next; #deleted role
                   11130:         }
                   11131:         if (!defined($possible_status)) { 
                   11132:             $sectioncount{$section}++;
                   11133:         } else {
                   11134:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11135:                 $status = 'active';
                   11136:             } elsif ($end < $now) {
                   11137:                 $status = 'future';
                   11138:             } elsif ($start > $now) {
                   11139:                 $status = 'previous';
                   11140:             }
                   11141:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11142:                 $sectioncount{$section}++;
                   11143:             }
                   11144:         }
1.233     raeburn  11145:     }
1.366     albertel 11146:     return %sectioncount;
1.233     raeburn  11147: }
                   11148: 
1.274     raeburn  11149: ###############################################
1.294     raeburn  11150: 
                   11151: =pod
1.405     albertel 11152: 
                   11153: =item * &get_course_users()
                   11154: 
1.275     raeburn  11155: Retrieves usernames:domains for users in the specified course
                   11156: with specific role(s), and access status. 
                   11157: 
                   11158: Incoming parameters:
1.277     albertel 11159: 1. course domain
                   11160: 2. course number
                   11161: 3. access status: users must have - either active, 
1.275     raeburn  11162: previous, future, or all.
1.277     albertel 11163: 4. reference to array of permissible roles
1.288     raeburn  11164: 5. reference to array of section restrictions (optional)
                   11165: 6. reference to results object (hash of hashes).
                   11166: 7. reference to optional userdata hash
1.609     raeburn  11167: 8. reference to optional statushash
1.630     raeburn  11168: 9. flag if privileged users (except those set to unhide in
                   11169:    course settings) should be excluded    
1.609     raeburn  11170: Keys of top level results hash are roles.
1.275     raeburn  11171: Keys of inner hashes are username:domain, with 
                   11172: values set to access type.
1.288     raeburn  11173: Optional userdata hash returns an array with arguments in the 
                   11174: same order as loncoursedata::get_classlist() for student data.
                   11175: 
1.609     raeburn  11176: Optional statushash returns
                   11177: 
1.288     raeburn  11178: Entries for end, start, section and status are blank because
                   11179: of the possibility of multiple values for non-student roles.
                   11180: 
1.275     raeburn  11181: =cut
1.405     albertel 11182: 
1.275     raeburn  11183: ###############################################
1.405     albertel 11184: 
1.275     raeburn  11185: sub get_course_users {
1.630     raeburn  11186:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11187:     my %idx = ();
1.419     raeburn  11188:     my %seclists;
1.288     raeburn  11189: 
                   11190:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11191:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11192:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11193:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11194:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11195:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11196:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11197:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11198: 
1.290     albertel 11199:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11200:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11201:         my $now = time;
1.277     albertel 11202:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11203:             my $match = 0;
1.412     raeburn  11204:             my $secmatch = 0;
1.419     raeburn  11205:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11206:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11207:             if ($section eq '') {
                   11208:                 $section = 'none';
                   11209:             }
1.291     albertel 11210:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11211:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11212:                     $secmatch = 1;
                   11213:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11214:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11215:                         $secmatch = 1;
                   11216:                     }
                   11217:                 } else {  
1.419     raeburn  11218: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11219: 		        $secmatch = 1;
                   11220:                     }
1.290     albertel 11221: 		}
1.412     raeburn  11222:                 if (!$secmatch) {
                   11223:                     next;
                   11224:                 }
1.419     raeburn  11225:             }
1.275     raeburn  11226:             if (defined($$types{'active'})) {
1.288     raeburn  11227:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11228:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11229:                     $match = 1;
1.275     raeburn  11230:                 }
                   11231:             }
                   11232:             if (defined($$types{'previous'})) {
1.609     raeburn  11233:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11234:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11235:                     $match = 1;
1.275     raeburn  11236:                 }
                   11237:             }
                   11238:             if (defined($$types{'future'})) {
1.609     raeburn  11239:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11240:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11241:                     $match = 1;
1.275     raeburn  11242:                 }
                   11243:             }
1.609     raeburn  11244:             if ($match) {
                   11245:                 push(@{$seclists{$student}},$section);
                   11246:                 if (ref($userdata) eq 'HASH') {
                   11247:                     $$userdata{$student} = $$classlist{$student};
                   11248:                 }
                   11249:                 if (ref($statushash) eq 'HASH') {
                   11250:                     $statushash->{$student}{'st'}{$section} = $status;
                   11251:                 }
1.288     raeburn  11252:             }
1.275     raeburn  11253:         }
                   11254:     }
1.412     raeburn  11255:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11256:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11257:         my $now = time;
1.609     raeburn  11258:         my %displaystatus = ( previous => 'Expired',
                   11259:                               active   => 'Active',
                   11260:                               future   => 'Future',
                   11261:                             );
1.1121    raeburn  11262:         my (%nothide,@possdoms);
1.630     raeburn  11263:         if ($hidepriv) {
                   11264:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11265:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11266:                 if ($user !~ /:/) {
                   11267:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11268:                 } else {
                   11269:                     $nothide{$user} = 1;
                   11270:                 }
                   11271:             }
1.1121    raeburn  11272:             my @possdoms = ($cdom);
                   11273:             if ($coursehash{'checkforpriv'}) {
                   11274:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11275:             }
1.630     raeburn  11276:         }
1.439     raeburn  11277:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11278:             my $match = 0;
1.412     raeburn  11279:             my $secmatch = 0;
1.439     raeburn  11280:             my $status;
1.412     raeburn  11281:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11282:             $user =~ s/:$//;
1.439     raeburn  11283:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11284:             if ($end == -1 || $start == -1) {
                   11285:                 next;
                   11286:             }
                   11287:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11288:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11289:                 my ($uname,$udom) = split(/:/,$user);
                   11290:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11291:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11292:                         $secmatch = 1;
                   11293:                     } elsif ($usec eq '') {
1.420     albertel 11294:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11295:                             $secmatch = 1;
                   11296:                         }
                   11297:                     } else {
                   11298:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11299:                             $secmatch = 1;
                   11300:                         }
                   11301:                     }
                   11302:                     if (!$secmatch) {
                   11303:                         next;
                   11304:                     }
1.288     raeburn  11305:                 }
1.419     raeburn  11306:                 if ($usec eq '') {
                   11307:                     $usec = 'none';
                   11308:                 }
1.275     raeburn  11309:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11310:                     if ($hidepriv) {
1.1121    raeburn  11311:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11312:                             (!$nothide{$uname.':'.$udom})) {
                   11313:                             next;
                   11314:                         }
                   11315:                     }
1.503     raeburn  11316:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11317:                         $status = 'previous';
                   11318:                     } elsif ($start > $now) {
                   11319:                         $status = 'future';
                   11320:                     } else {
                   11321:                         $status = 'active';
                   11322:                     }
1.277     albertel 11323:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11324:                         if ($status eq $type) {
1.420     albertel 11325:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11326:                                 push(@{$$users{$role}{$user}},$type);
                   11327:                             }
1.288     raeburn  11328:                             $match = 1;
                   11329:                         }
                   11330:                     }
1.419     raeburn  11331:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11332:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11333: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11334:                         }
1.420     albertel 11335:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11336:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11337:                         }
1.609     raeburn  11338:                         if (ref($statushash) eq 'HASH') {
                   11339:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11340:                         }
1.275     raeburn  11341:                     }
                   11342:                 }
                   11343:             }
                   11344:         }
1.290     albertel 11345:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11346:             if ((defined($cdom)) && (defined($cnum))) {
                   11347:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11348:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11349:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11350:                     next if ($owner eq '');
                   11351:                     my ($ownername,$ownerdom);
                   11352:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11353:                         $ownername = $1;
                   11354:                         $ownerdom = $2;
                   11355:                     } else {
                   11356:                         $ownername = $owner;
                   11357:                         $ownerdom = $cdom;
                   11358:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11359:                     }
                   11360:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11361:                     if (defined($userdata) && 
1.609     raeburn  11362: 			!exists($$userdata{$owner})) {
                   11363: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11364:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11365:                             push(@{$seclists{$owner}},'none');
                   11366:                         }
                   11367:                         if (ref($statushash) eq 'HASH') {
                   11368:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11369:                         }
1.290     albertel 11370: 		    }
1.279     raeburn  11371:                 }
                   11372:             }
                   11373:         }
1.419     raeburn  11374:         foreach my $user (keys(%seclists)) {
                   11375:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11376:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11377:         }
1.275     raeburn  11378:     }
                   11379:     return;
                   11380: }
                   11381: 
1.288     raeburn  11382: sub get_user_info {
                   11383:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11384:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11385: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11386:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11387:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11388:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11389:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11390:     return;
                   11391: }
1.275     raeburn  11392: 
1.472     raeburn  11393: ###############################################
                   11394: 
                   11395: =pod
                   11396: 
                   11397: =item * &get_user_quota()
                   11398: 
1.1134    raeburn  11399: Retrieves quota assigned for storage of user files.
                   11400: Default is to report quota for portfolio files.
1.472     raeburn  11401: 
                   11402: Incoming parameters:
                   11403: 1. user's username
                   11404: 2. user's domain
1.1134    raeburn  11405: 3. quota name - portfolio, author, or course
1.1136    raeburn  11406:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11407: 4. crstype - official, unofficial, textbook, placement or community, 
                   11408:    if quota name is course
1.472     raeburn  11409: 
                   11410: Returns:
1.1163    raeburn  11411: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11412: 2. (Optional) Type of setting: custom or default
                   11413:    (individually assigned or default for user's 
                   11414:    institutional status).
                   11415: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11416:    or student - types as defined in localenroll::inst_usertypes 
                   11417:    for user's domain, which determines default quota for user.
                   11418: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11419: 
                   11420: If a value has been stored in the user's environment, 
1.536     raeburn  11421: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11422: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11423: 
                   11424: =cut
                   11425: 
                   11426: ###############################################
                   11427: 
                   11428: 
                   11429: sub get_user_quota {
1.1136    raeburn  11430:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11431:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11432:     if (!defined($udom)) {
                   11433:         $udom = $env{'user.domain'};
                   11434:     }
                   11435:     if (!defined($uname)) {
                   11436:         $uname = $env{'user.name'};
                   11437:     }
                   11438:     if (($udom eq '' || $uname eq '') ||
                   11439:         ($udom eq 'public') && ($uname eq 'public')) {
                   11440:         $quota = 0;
1.536     raeburn  11441:         $quotatype = 'default';
                   11442:         $defquota = 0; 
1.472     raeburn  11443:     } else {
1.536     raeburn  11444:         my $inststatus;
1.1134    raeburn  11445:         if ($quotaname eq 'course') {
                   11446:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11447:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11448:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11449:             } else {
                   11450:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11451:                 $quota = $cenv{'internal.uploadquota'};
                   11452:             }
1.536     raeburn  11453:         } else {
1.1134    raeburn  11454:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11455:                 if ($quotaname eq 'author') {
                   11456:                     $quota = $env{'environment.authorquota'};
                   11457:                 } else {
                   11458:                     $quota = $env{'environment.portfolioquota'};
                   11459:                 }
                   11460:                 $inststatus = $env{'environment.inststatus'};
                   11461:             } else {
                   11462:                 my %userenv = 
                   11463:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11464:                                          'authorquota','inststatus'],$udom,$uname);
                   11465:                 my ($tmp) = keys(%userenv);
                   11466:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11467:                     if ($quotaname eq 'author') {
                   11468:                         $quota = $userenv{'authorquota'};
                   11469:                     } else {
                   11470:                         $quota = $userenv{'portfolioquota'};
                   11471:                     }
                   11472:                     $inststatus = $userenv{'inststatus'};
                   11473:                 } else {
                   11474:                     undef(%userenv);
                   11475:                 }
                   11476:             }
                   11477:         }
                   11478:         if ($quota eq '' || wantarray) {
                   11479:             if ($quotaname eq 'course') {
                   11480:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11481:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11482:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11483:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11484:                     $defquota = $domdefs{$crstype.'quota'};
                   11485:                 }
                   11486:                 if ($defquota eq '') {
                   11487:                     $defquota = 500;
                   11488:                 }
1.1134    raeburn  11489:             } else {
                   11490:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11491:             }
                   11492:             if ($quota eq '') {
                   11493:                 $quota = $defquota;
                   11494:                 $quotatype = 'default';
                   11495:             } else {
                   11496:                 $quotatype = 'custom';
                   11497:             }
1.472     raeburn  11498:         }
                   11499:     }
1.536     raeburn  11500:     if (wantarray) {
                   11501:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11502:     } else {
                   11503:         return $quota;
                   11504:     }
1.472     raeburn  11505: }
                   11506: 
                   11507: ###############################################
                   11508: 
                   11509: =pod
                   11510: 
                   11511: =item * &default_quota()
                   11512: 
1.536     raeburn  11513: Retrieves default quota assigned for storage of user portfolio files,
                   11514: given an (optional) user's institutional status.
1.472     raeburn  11515: 
                   11516: Incoming parameters:
1.1142    raeburn  11517: 
1.472     raeburn  11518: 1. domain
1.536     raeburn  11519: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11520:    status types (e.g., faculty, staff, student etc.)
                   11521:    which apply to the user for whom the default is being retrieved.
                   11522:    If the institutional status string in undefined, the domain
1.1134    raeburn  11523:    default quota will be returned.
                   11524: 3.  quota name - portfolio, author, or course
                   11525:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11526: 
                   11527: Returns:
1.1142    raeburn  11528: 
1.1163    raeburn  11529: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11530: 2. (Optional) institutional type which determined the value of the
                   11531:    default quota.
1.472     raeburn  11532: 
                   11533: If a value has been stored in the domain's configuration db,
                   11534: it will return that, otherwise it returns 20 (for backwards 
                   11535: compatibility with domains which have not set up a configuration
1.1163    raeburn  11536: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11537: 
1.536     raeburn  11538: If the user's status includes multiple types (e.g., staff and student),
                   11539: the largest default quota which applies to the user determines the
                   11540: default quota returned.
                   11541: 
1.472     raeburn  11542: =cut
                   11543: 
                   11544: ###############################################
                   11545: 
                   11546: 
                   11547: sub default_quota {
1.1134    raeburn  11548:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11549:     my ($defquota,$settingstatus);
                   11550:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11551:                                             ['quotas'],$udom);
1.1134    raeburn  11552:     my $key = 'defaultquota';
                   11553:     if ($quotaname eq 'author') {
                   11554:         $key = 'authorquota';
                   11555:     }
1.622     raeburn  11556:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11557:         if ($inststatus ne '') {
1.765     raeburn  11558:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11559:             foreach my $item (@statuses) {
1.1134    raeburn  11560:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11561:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11562:                         if ($defquota eq '') {
1.1134    raeburn  11563:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11564:                             $settingstatus = $item;
1.1134    raeburn  11565:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11566:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11567:                             $settingstatus = $item;
                   11568:                         }
                   11569:                     }
1.1134    raeburn  11570:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11571:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11572:                         if ($defquota eq '') {
                   11573:                             $defquota = $quotahash{'quotas'}{$item};
                   11574:                             $settingstatus = $item;
                   11575:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11576:                             $defquota = $quotahash{'quotas'}{$item};
                   11577:                             $settingstatus = $item;
                   11578:                         }
1.536     raeburn  11579:                     }
                   11580:                 }
                   11581:             }
                   11582:         }
                   11583:         if ($defquota eq '') {
1.1134    raeburn  11584:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11585:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11586:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11587:                 $defquota = $quotahash{'quotas'}{'default'};
                   11588:             }
1.536     raeburn  11589:             $settingstatus = 'default';
1.1139    raeburn  11590:             if ($defquota eq '') {
                   11591:                 if ($quotaname eq 'author') {
                   11592:                     $defquota = 500;
                   11593:                 }
                   11594:             }
1.536     raeburn  11595:         }
                   11596:     } else {
                   11597:         $settingstatus = 'default';
1.1134    raeburn  11598:         if ($quotaname eq 'author') {
                   11599:             $defquota = 500;
                   11600:         } else {
                   11601:             $defquota = 20;
                   11602:         }
1.536     raeburn  11603:     }
                   11604:     if (wantarray) {
                   11605:         return ($defquota,$settingstatus);
1.472     raeburn  11606:     } else {
1.536     raeburn  11607:         return $defquota;
1.472     raeburn  11608:     }
                   11609: }
                   11610: 
1.1135    raeburn  11611: ###############################################
                   11612: 
                   11613: =pod
                   11614: 
1.1136    raeburn  11615: =item * &excess_filesize_warning()
1.1135    raeburn  11616: 
                   11617: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11618: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11619: space to be exceeded.
1.1136    raeburn  11620: 
                   11621: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11622: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11623: 
1.1165    raeburn  11624: Inputs: 7 
1.1136    raeburn  11625: 1. username or coursenum
1.1135    raeburn  11626: 2. domain
1.1136    raeburn  11627: 3. context ('author' or 'course')
1.1135    raeburn  11628: 4. filename of file for which action is being requested
                   11629: 5. filesize (kB) of file
                   11630: 6. action being taken: copy or upload.
1.1237    raeburn  11631: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11632: 
                   11633: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11634:          otherwise return null.
                   11635: 
                   11636: =back
1.1135    raeburn  11637: 
                   11638: =cut
                   11639: 
1.1136    raeburn  11640: sub excess_filesize_warning {
1.1165    raeburn  11641:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11642:     my $current_disk_usage = 0;
1.1165    raeburn  11643:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11644:     if ($context eq 'author') {
                   11645:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11646:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11647:     } else {
                   11648:         foreach my $subdir ('docs','supplemental') {
                   11649:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11650:         }
                   11651:     }
1.1135    raeburn  11652:     $disk_quota = int($disk_quota * 1000);
                   11653:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11654:         return '<p class="LC_warning">'.
1.1135    raeburn  11655:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11656:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11657:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11658:                             $disk_quota,$current_disk_usage).
                   11659:                '</p>';
                   11660:     }
                   11661:     return;
                   11662: }
                   11663: 
                   11664: ###############################################
                   11665: 
                   11666: 
1.1136    raeburn  11667: 
                   11668: 
1.384     raeburn  11669: sub get_secgrprole_info {
                   11670:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11671:     my %sections_count = &get_sections($cdom,$cnum);
                   11672:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11673:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11674:     my @groups = sort(keys(%curr_groups));
                   11675:     my $allroles = [];
                   11676:     my $rolehash;
                   11677:     my $accesshash = {
                   11678:                      active => 'Currently has access',
                   11679:                      future => 'Will have future access',
                   11680:                      previous => 'Previously had access',
                   11681:                   };
                   11682:     if ($needroles) {
                   11683:         $rolehash = {'all' => 'all'};
1.385     albertel 11684:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11685: 	if (&Apache::lonnet::error(%user_roles)) {
                   11686: 	    undef(%user_roles);
                   11687: 	}
                   11688:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11689:             my ($role)=split(/\:/,$item,2);
                   11690:             if ($role eq 'cr') { next; }
                   11691:             if ($role =~ /^cr/) {
                   11692:                 $$rolehash{$role} = (split('/',$role))[3];
                   11693:             } else {
                   11694:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11695:             }
                   11696:         }
                   11697:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11698:             push(@{$allroles},$key);
                   11699:         }
                   11700:         push (@{$allroles},'st');
                   11701:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11702:     }
                   11703:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11704: }
                   11705: 
1.555     raeburn  11706: sub user_picker {
1.1279    raeburn  11707:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11708:     my $currdom = $dom;
1.1253    raeburn  11709:     my @alldoms = &Apache::lonnet::all_domains();
                   11710:     if (@alldoms == 1) {
                   11711:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11712:                                                ['directorysrch'],$alldoms[0]);
                   11713:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11714:         my $showdom = $domdesc;
                   11715:         if ($showdom eq '') {
                   11716:             $showdom = $dom;
                   11717:         }
                   11718:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11719:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11720:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11721:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11722:             }
                   11723:         }
                   11724:     }
1.555     raeburn  11725:     my %curr_selected = (
                   11726:                         srchin => 'dom',
1.580     raeburn  11727:                         srchby => 'lastname',
1.555     raeburn  11728:                       );
                   11729:     my $srchterm;
1.625     raeburn  11730:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11731:         if ($srch->{'srchby'} ne '') {
                   11732:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11733:         }
                   11734:         if ($srch->{'srchin'} ne '') {
                   11735:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11736:         }
                   11737:         if ($srch->{'srchtype'} ne '') {
                   11738:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11739:         }
                   11740:         if ($srch->{'srchdomain'} ne '') {
                   11741:             $currdom = $srch->{'srchdomain'};
                   11742:         }
                   11743:         $srchterm = $srch->{'srchterm'};
                   11744:     }
1.1222    damieng  11745:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11746:                     'usr'       => 'Search criteria',
1.563     raeburn  11747:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11748:                     'uname'     => 'username',
                   11749:                     'lastname'  => 'last name',
1.555     raeburn  11750:                     'lastfirst' => 'last name, first name',
1.558     albertel 11751:                     'crs'       => 'in this course',
1.576     raeburn  11752:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11753:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11754:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11755:                     'exact'     => 'is',
                   11756:                     'contains'  => 'contains',
1.569     raeburn  11757:                     'begins'    => 'begins with',
1.1222    damieng  11758:                                        );
                   11759:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11760:                     'youm'      => "You must include some text to search for.",
                   11761:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11762:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11763:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11764:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11765:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11766:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11767:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11768:                                        );
1.1222    damieng  11769:     &html_escape(\%html_lt);
                   11770:     &js_escape(\%js_lt);
1.1255    raeburn  11771:     my $domform;
1.1277    raeburn  11772:     my $allow_blank = 1;
1.1255    raeburn  11773:     if ($fixeddom) {
1.1277    raeburn  11774:         $allow_blank = 0;
                   11775:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11776:     } else {
1.1287    raeburn  11777:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11778:         my ($trusted,$untrusted);
1.1287    raeburn  11779:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11780:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11781:         } elsif ($context eq 'author') {
1.1288    raeburn  11782:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11783:         } elsif ($context eq 'domain') {
1.1288    raeburn  11784:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11785:         }
1.1288    raeburn  11786:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11787:     }
1.563     raeburn  11788:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11789: 
                   11790:     my @srchins = ('crs','dom','alc','instd');
                   11791: 
                   11792:     foreach my $option (@srchins) {
                   11793:         # FIXME 'alc' option unavailable until 
                   11794:         #       loncreateuser::print_user_query_page()
                   11795:         #       has been completed.
                   11796:         next if ($option eq 'alc');
1.880     raeburn  11797:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11798:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11799:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11800:         if ($curr_selected{'srchin'} eq $option) {
                   11801:             $srchinsel .= ' 
1.1222    damieng  11802:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11803:         } else {
                   11804:             $srchinsel .= '
1.1222    damieng  11805:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11806:         }
1.555     raeburn  11807:     }
1.563     raeburn  11808:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11809: 
                   11810:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11811:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11812:         if ($curr_selected{'srchby'} eq $option) {
                   11813:             $srchbysel .= '
1.1222    damieng  11814:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11815:         } else {
                   11816:             $srchbysel .= '
1.1222    damieng  11817:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11818:          }
                   11819:     }
                   11820:     $srchbysel .= "\n  </select>\n";
                   11821: 
                   11822:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11823:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11824:         if ($curr_selected{'srchtype'} eq $option) {
                   11825:             $srchtypesel .= '
1.1222    damieng  11826:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11827:         } else {
                   11828:             $srchtypesel .= '
1.1222    damieng  11829:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11830:         }
                   11831:     }
                   11832:     $srchtypesel .= "\n  </select>\n";
                   11833: 
1.558     albertel 11834:     my ($newuserscript,$new_user_create);
1.994     raeburn  11835:     my $context_dom = $env{'request.role.domain'};
                   11836:     if ($context eq 'requestcrs') {
                   11837:         if ($env{'form.coursedom'} ne '') { 
                   11838:             $context_dom = $env{'form.coursedom'};
                   11839:         }
                   11840:     }
1.556     raeburn  11841:     if ($forcenewuser) {
1.576     raeburn  11842:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11843:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11844:                 if ($cancreate) {
                   11845:                     $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>';
                   11846:                 } else {
1.799     bisitz   11847:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11848:                     my %usertypetext = (
                   11849:                         official   => 'institutional',
                   11850:                         unofficial => 'non-institutional',
                   11851:                     );
1.799     bisitz   11852:                     $new_user_create = '<p class="LC_warning">'
                   11853:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11854:                                       .' '
                   11855:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11856:                                           ,'<a href="'.$helplink.'">','</a>')
                   11857:                                       .'</p><br />';
1.627     raeburn  11858:                 }
1.576     raeburn  11859:             }
                   11860:         }
                   11861: 
1.556     raeburn  11862:         $newuserscript = <<"ENDSCRIPT";
                   11863: 
1.570     raeburn  11864: function setSearch(createnew,callingForm) {
1.556     raeburn  11865:     if (createnew == 1) {
1.570     raeburn  11866:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11867:             if (callingForm.srchby.options[i].value == 'uname') {
                   11868:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11869:             }
                   11870:         }
1.570     raeburn  11871:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11872:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11873: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11874:             }
                   11875:         }
1.570     raeburn  11876:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11877:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11878:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11879:             }
                   11880:         }
1.570     raeburn  11881:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11882:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11883:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11884:             }
                   11885:         }
                   11886:     }
                   11887: }
                   11888: ENDSCRIPT
1.558     albertel 11889: 
1.556     raeburn  11890:     }
                   11891: 
1.555     raeburn  11892:     my $output = <<"END_BLOCK";
1.556     raeburn  11893: <script type="text/javascript">
1.824     bisitz   11894: // <![CDATA[
1.570     raeburn  11895: function validateEntry(callingForm) {
1.558     albertel 11896: 
1.556     raeburn  11897:     var checkok = 1;
1.558     albertel 11898:     var srchin;
1.570     raeburn  11899:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11900: 	if ( callingForm.srchin[i].checked ) {
                   11901: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11902: 	}
                   11903:     }
                   11904: 
1.570     raeburn  11905:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11906:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11907:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11908:     var srchterm =  callingForm.srchterm.value;
                   11909:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11910:     var msg = "";
                   11911: 
                   11912:     if (srchterm == "") {
                   11913:         checkok = 0;
1.1222    damieng  11914:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11915:     }
                   11916: 
1.569     raeburn  11917:     if (srchtype== 'begins') {
                   11918:         if (srchterm.length < 2) {
                   11919:             checkok = 0;
1.1222    damieng  11920:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11921:         }
                   11922:     }
                   11923: 
1.556     raeburn  11924:     if (srchtype== 'contains') {
                   11925:         if (srchterm.length < 3) {
                   11926:             checkok = 0;
1.1222    damieng  11927:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11928:         }
                   11929:     }
                   11930:     if (srchin == 'instd') {
                   11931:         if (srchdomain == '') {
                   11932:             checkok = 0;
1.1222    damieng  11933:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11934:         }
                   11935:     }
                   11936:     if (srchin == 'dom') {
                   11937:         if (srchdomain == '') {
                   11938:             checkok = 0;
1.1222    damieng  11939:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11940:         }
                   11941:     }
                   11942:     if (srchby == 'lastfirst') {
                   11943:         if (srchterm.indexOf(",") == -1) {
                   11944:             checkok = 0;
1.1222    damieng  11945:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11946:         }
                   11947:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11948:             checkok = 0;
1.1222    damieng  11949:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11950:         }
                   11951:     }
                   11952:     if (checkok == 0) {
1.1222    damieng  11953:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11954:         return;
                   11955:     }
                   11956:     if (checkok == 1) {
1.570     raeburn  11957:         callingForm.submit();
1.556     raeburn  11958:     }
                   11959: }
                   11960: 
                   11961: $newuserscript
                   11962: 
1.824     bisitz   11963: // ]]>
1.556     raeburn  11964: </script>
1.558     albertel 11965: 
                   11966: $new_user_create
                   11967: 
1.555     raeburn  11968: END_BLOCK
1.558     albertel 11969: 
1.876     raeburn  11970:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11971:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11972:                $domform.
                   11973:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11974:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11975:                $srchbysel.
                   11976:                $srchtypesel. 
                   11977:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11978:                $srchinsel.
                   11979:                &Apache::lonhtmlcommon::row_closure(1). 
                   11980:                &Apache::lonhtmlcommon::end_pick_box().
                   11981:                '<br />';
1.1253    raeburn  11982:     return ($output,1);
1.555     raeburn  11983: }
                   11984: 
1.612     raeburn  11985: sub user_rule_check {
1.615     raeburn  11986:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11987:     my ($response,%inst_response);
1.612     raeburn  11988:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11989:         if (keys(%{$usershash}) > 1) {
                   11990:             my (%by_username,%by_id,%userdoms);
                   11991:             my $checkid; 
                   11992:             if (ref($checks) eq 'HASH') {
                   11993:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11994:                     $checkid = 1;
                   11995:                 }
                   11996:             }
                   11997:             foreach my $user (keys(%{$usershash})) {
                   11998:                 my ($uname,$udom) = split(/:/,$user);
                   11999:                 if ($checkid) {
                   12000:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12001:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12002:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12003:                             $userdoms{$udom} = 1;
1.1227    raeburn  12004:                             if (ref($inst_results) eq 'HASH') {
                   12005:                                 $inst_results->{$uname.':'.$udom} = {};
                   12006:                             }
1.1226    raeburn  12007:                         }
                   12008:                     }
                   12009:                 } else {
                   12010:                     $by_username{$udom}{$uname} = 1;
                   12011:                     $userdoms{$udom} = 1;
1.1227    raeburn  12012:                     if (ref($inst_results) eq 'HASH') {
                   12013:                         $inst_results->{$uname.':'.$udom} = {};
                   12014:                     }
1.1226    raeburn  12015:                 }
                   12016:             }
                   12017:             foreach my $udom (keys(%userdoms)) {
                   12018:                 if (!$got_rules->{$udom}) {
                   12019:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12020:                                                              ['usercreation'],$udom);
                   12021:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12022:                         foreach my $item ('username','id') {
                   12023:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12024:                                 $$curr_rules{$udom}{$item} =
                   12025:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12026:                             }
                   12027:                         }
                   12028:                     }
                   12029:                     $got_rules->{$udom} = 1;
                   12030:                 }
1.612     raeburn  12031:             }
1.1226    raeburn  12032:             if ($checkid) {
                   12033:                 foreach my $udom (keys(%by_id)) {
                   12034:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12035:                     if ($outcome eq 'ok') {
1.1227    raeburn  12036:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12037:                             my $uname = $by_id{$udom}{$id};
                   12038:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12039:                         }
1.1226    raeburn  12040:                         if (ref($results) eq 'HASH') {
                   12041:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12042:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12043:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12044:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12045:                                 }
1.1226    raeburn  12046:                             }
                   12047:                         }
                   12048:                     }
1.612     raeburn  12049:                 }
1.615     raeburn  12050:             } else {
1.1226    raeburn  12051:                 foreach my $udom (keys(%by_username)) {
                   12052:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12053:                     if ($outcome eq 'ok') {
1.1227    raeburn  12054:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12055:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12056:                         }
1.1226    raeburn  12057:                         if (ref($results) eq 'HASH') {
                   12058:                             foreach my $uname (keys(%{$results})) {
                   12059:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12060:                             }
                   12061:                         }
                   12062:                     }
                   12063:                 }
1.612     raeburn  12064:             }
1.1226    raeburn  12065:         } elsif (keys(%{$usershash}) == 1) {
                   12066:             my $user = (keys(%{$usershash}))[0];
                   12067:             my ($uname,$udom) = split(/:/,$user);
                   12068:             if (($udom ne '') && ($uname ne '')) {
                   12069:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12070:                     if (ref($checks) eq 'HASH') {
                   12071:                         if (defined($checks->{'username'})) {
                   12072:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12073:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12074:                         } elsif (defined($checks->{'id'})) {
                   12075:                             if ($usershash->{$user}->{'id'} ne '') {
                   12076:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12077:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12078:                                                                   $usershash->{$user}->{'id'});
                   12079:                             } else {
                   12080:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12081:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12082:                             }
1.585     raeburn  12083:                         }
1.1226    raeburn  12084:                     } else {
                   12085:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12086:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12087:                        return;
                   12088:                     }
                   12089:                     if (!$got_rules->{$udom}) {
                   12090:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12091:                                                                  ['usercreation'],$udom);
                   12092:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12093:                             foreach my $item ('username','id') {
                   12094:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12095:                                    $$curr_rules{$udom}{$item} = 
                   12096:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12097:                                 }
                   12098:                             }
                   12099:                         }
                   12100:                         $got_rules->{$udom} = 1;
1.585     raeburn  12101:                     }
                   12102:                 }
1.1226    raeburn  12103:             } else {
                   12104:                 return;
                   12105:             }
                   12106:         } else {
                   12107:             return;
                   12108:         }
                   12109:         foreach my $user (keys(%{$usershash})) {
                   12110:             my ($uname,$udom) = split(/:/,$user);
                   12111:             next if (($udom eq '') || ($uname eq ''));
                   12112:             my $id;
1.1227    raeburn  12113:             if (ref($inst_results) eq 'HASH') {
                   12114:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12115:                     $id = $inst_results->{$user}->{'id'};
                   12116:                 }
                   12117:             }
                   12118:             if ($id eq '') { 
                   12119:                 if (ref($usershash->{$user})) {
                   12120:                     $id = $usershash->{$user}->{'id'};
                   12121:                 }
1.585     raeburn  12122:             }
1.612     raeburn  12123:             foreach my $item (keys(%{$checks})) {
                   12124:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12125:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12126:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12127:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12128:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12129:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12130:                                 if ($rule_check{$rule}) {
                   12131:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12132:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12133:                                         if (ref($inst_results) eq 'HASH') {
                   12134:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12135:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12136:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12137:                                                 } elsif ($item eq 'id') {
                   12138:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12139:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12140:                                                     }
1.615     raeburn  12141:                                                 }
1.612     raeburn  12142:                                             }
                   12143:                                         }
1.615     raeburn  12144:                                     }
                   12145:                                     last;
1.585     raeburn  12146:                                 }
                   12147:                             }
                   12148:                         }
                   12149:                     }
                   12150:                 }
                   12151:             }
                   12152:         }
                   12153:     }
1.612     raeburn  12154:     return;
                   12155: }
                   12156: 
                   12157: sub user_rule_formats {
                   12158:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12159:     my %text = ( 
                   12160:                  'username' => 'Usernames',
                   12161:                  'id'       => 'IDs',
                   12162:                );
                   12163:     my $output;
                   12164:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12165:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12166:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12167:             $output = '<br />'.
                   12168:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12169:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12170:                       ' <ul>';
1.612     raeburn  12171:             foreach my $rule (@{$ruleorder}) {
                   12172:                 if (ref($curr_rules) eq 'ARRAY') {
                   12173:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12174:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12175:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12176:                                         $rules->{$rule}{'desc'}.'</li>';
                   12177:                         }
                   12178:                     }
                   12179:                 }
                   12180:             }
                   12181:             $output .= '</ul>';
                   12182:         }
                   12183:     }
                   12184:     return $output;
                   12185: }
                   12186: 
                   12187: sub instrule_disallow_msg {
1.615     raeburn  12188:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12189:     my $response;
                   12190:     my %text = (
                   12191:                   item   => 'username',
                   12192:                   items  => 'usernames',
                   12193:                   match  => 'matches',
                   12194:                   do     => 'does',
                   12195:                   action => 'a username',
                   12196:                   one    => 'one',
                   12197:                );
                   12198:     if ($count > 1) {
                   12199:         $text{'item'} = 'usernames';
                   12200:         $text{'match'} ='match';
                   12201:         $text{'do'} = 'do';
                   12202:         $text{'action'} = 'usernames',
                   12203:         $text{'one'} = 'ones';
                   12204:     }
                   12205:     if ($checkitem eq 'id') {
                   12206:         $text{'items'} = 'IDs';
                   12207:         $text{'item'} = 'ID';
                   12208:         $text{'action'} = 'an ID';
1.615     raeburn  12209:         if ($count > 1) {
                   12210:             $text{'item'} = 'IDs';
                   12211:             $text{'action'} = 'IDs';
                   12212:         }
1.612     raeburn  12213:     }
1.674     bisitz   12214:     $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  12215:     if ($mode eq 'upload') {
                   12216:         if ($checkitem eq 'username') {
                   12217:             $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'}.");
                   12218:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12219:             $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  12220:         }
1.669     raeburn  12221:     } elsif ($mode eq 'selfcreate') {
                   12222:         if ($checkitem eq 'id') {
                   12223:             $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.");
                   12224:         }
1.615     raeburn  12225:     } else {
                   12226:         if ($checkitem eq 'username') {
                   12227:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12228:         } elsif ($checkitem eq 'id') {
                   12229:             $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.");
                   12230:         }
1.612     raeburn  12231:     }
                   12232:     return $response;
1.585     raeburn  12233: }
                   12234: 
1.624     raeburn  12235: sub personal_data_fieldtitles {
                   12236:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12237:                         id => 'Student/Employee ID',
                   12238:                         permanentemail => 'E-mail address',
                   12239:                         lastname => 'Last Name',
                   12240:                         firstname => 'First Name',
                   12241:                         middlename => 'Middle Name',
                   12242:                         generation => 'Generation',
                   12243:                         gen => 'Generation',
1.765     raeburn  12244:                         inststatus => 'Affiliation',
1.624     raeburn  12245:                    );
                   12246:     return %fieldtitles;
                   12247: }
                   12248: 
1.642     raeburn  12249: sub sorted_inst_types {
                   12250:     my ($dom) = @_;
1.1185    raeburn  12251:     my ($usertypes,$order);
                   12252:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12253:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12254:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12255:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12256:     } else {
                   12257:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12258:     }
1.642     raeburn  12259:     my $othertitle = &mt('All users');
                   12260:     if ($env{'request.course.id'}) {
1.668     raeburn  12261:         $othertitle  = &mt('Any users');
1.642     raeburn  12262:     }
                   12263:     my @types;
                   12264:     if (ref($order) eq 'ARRAY') {
                   12265:         @types = @{$order};
                   12266:     }
                   12267:     if (@types == 0) {
                   12268:         if (ref($usertypes) eq 'HASH') {
                   12269:             @types = sort(keys(%{$usertypes}));
                   12270:         }
                   12271:     }
                   12272:     if (keys(%{$usertypes}) > 0) {
                   12273:         $othertitle = &mt('Other users');
                   12274:     }
                   12275:     return ($othertitle,$usertypes,\@types);
                   12276: }
                   12277: 
1.645     raeburn  12278: sub get_institutional_codes {
1.1361    raeburn  12279:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12280: # Get complete list of course sections to update
                   12281:     my @currsections = ();
                   12282:     my @currxlists = ();
1.1361    raeburn  12283:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12284:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12285:     my $crskey = $crs.':'.$coursecode;
                   12286:     @{$unclutteredsec{$crskey}} = ();
                   12287:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12288: 
                   12289:     if ($$settings{'internal.sectionnums'} ne '') {
                   12290:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12291:     }
                   12292: 
                   12293:     if ($$settings{'internal.crosslistings'} ne '') {
                   12294:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12295:     }
                   12296: 
                   12297:     if (@currxlists > 0) {
1.1361    raeburn  12298:         foreach my $xl (@currxlists) {
                   12299:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12300:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12301:                     push(@{$allcourses},$1);
1.645     raeburn  12302:                     $$LC_code{$1} = $2;
                   12303:                 }
                   12304:             }
                   12305:         }
                   12306:     }
1.1361    raeburn  12307: 
1.645     raeburn  12308:     if (@currsections > 0) {
1.1361    raeburn  12309:         foreach my $sec (@currsections) {
                   12310:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12311:                 my $instsec = $1;
1.645     raeburn  12312:                 my $lc_sec = $2;
1.1361    raeburn  12313:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12314:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12315:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12316:                 }
                   12317:             }
                   12318:         }
                   12319:     }
                   12320: 
                   12321:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12322:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12323:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12324:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12325:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12326:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12327:                     push(@{$allcourses},$sec);
1.1361    raeburn  12328:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12329:                 }
                   12330:             }
                   12331:         }
                   12332:     }
                   12333:     return;
                   12334: }
                   12335: 
1.971     raeburn  12336: sub get_standard_codeitems {
                   12337:     return ('Year','Semester','Department','Number','Section');
                   12338: }
                   12339: 
1.112     bowersj2 12340: =pod
                   12341: 
1.780     raeburn  12342: =head1 Slot Helpers
                   12343: 
                   12344: =over 4
                   12345: 
                   12346: =item * sorted_slots()
                   12347: 
1.1040    raeburn  12348: Sorts an array of slot names in order of an optional sort key,
                   12349: default sort is by slot start time (earliest first). 
1.780     raeburn  12350: 
                   12351: Inputs:
                   12352: 
                   12353: =over 4
                   12354: 
                   12355: slotsarr  - Reference to array of unsorted slot names.
                   12356: 
                   12357: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12358: 
1.1040    raeburn  12359: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12360: 
1.549     albertel 12361: =back
                   12362: 
1.780     raeburn  12363: Returns:
                   12364: 
                   12365: =over 4
                   12366: 
1.1040    raeburn  12367: sorted   - An array of slot names sorted by a specified sort key 
                   12368:            (default sort key is start time of the slot).
1.780     raeburn  12369: 
                   12370: =back
                   12371: 
                   12372: =cut
                   12373: 
                   12374: 
                   12375: sub sorted_slots {
1.1040    raeburn  12376:     my ($slotsarr,$slots,$sortkey) = @_;
                   12377:     if ($sortkey eq '') {
                   12378:         $sortkey = 'starttime';
                   12379:     }
1.780     raeburn  12380:     my @sorted;
                   12381:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12382:         @sorted =
                   12383:             sort {
                   12384:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12385:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12386:                      }
                   12387:                      if (ref($slots->{$a})) { return -1;}
                   12388:                      if (ref($slots->{$b})) { return 1;}
                   12389:                      return 0;
                   12390:                  } @{$slotsarr};
                   12391:     }
                   12392:     return @sorted;
                   12393: }
                   12394: 
1.1040    raeburn  12395: =pod
                   12396: 
                   12397: =item * get_future_slots()
                   12398: 
                   12399: Inputs:
                   12400: 
                   12401: =over 4
                   12402: 
                   12403: cnum - course number
                   12404: 
                   12405: cdom - course domain
                   12406: 
                   12407: now - current UNIX time
                   12408: 
                   12409: symb - optional symb
                   12410: 
                   12411: =back
                   12412: 
                   12413: Returns:
                   12414: 
                   12415: =over 4
                   12416: 
                   12417: sorted_reservable - ref to array of student_schedulable slots currently 
                   12418:                     reservable, ordered by end date of reservation period.
                   12419: 
                   12420: reservable_now - ref to hash of student_schedulable slots currently
                   12421:                  reservable.
                   12422: 
                   12423:     Keys in inner hash are:
                   12424:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12425:     (b) endreserve: end date of reservation period.
                   12426:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12427:         selected.
1.1040    raeburn  12428: 
                   12429: sorted_future - ref to array of student_schedulable slots reservable in
                   12430:                 the future, ordered by start date of reservation period.
                   12431: 
                   12432: future_reservable - ref to hash of student_schedulable slots reservable
                   12433:                     in the future.
                   12434: 
                   12435:     Keys in inner hash are:
                   12436:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12437:     (b) startreserve: start date of reservation period.
                   12438:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12439:         selected.
1.1040    raeburn  12440: 
                   12441: =back
                   12442: 
                   12443: =cut
                   12444: 
                   12445: sub get_future_slots {
                   12446:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12447:     my $map;
                   12448:     if ($symb) {
                   12449:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12450:     }
1.1040    raeburn  12451:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12452:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12453:     foreach my $slot (keys(%slots)) {
                   12454:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12455:         if ($symb) {
1.1229    raeburn  12456:             if ($slots{$slot}->{'symb'} ne '') {
                   12457:                 my $canuse;
                   12458:                 my %oksymbs;
                   12459:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12460:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12461:                 if ($oksymbs{$symb}) {
                   12462:                     $canuse = 1;
                   12463:                 } else {
                   12464:                     foreach my $item (@slotsymbs) {
                   12465:                         if ($item =~ /\.(page|sequence)$/) {
                   12466:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12467:                             if (($map ne '') && ($map eq $sloturl)) {
                   12468:                                 $canuse = 1;
                   12469:                                 last;
                   12470:                             }
                   12471:                         }
                   12472:                     }
                   12473:                 }
                   12474:                 next unless ($canuse);
                   12475:             }
1.1040    raeburn  12476:         }
                   12477:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12478:             ($slots{$slot}->{'endtime'} > $now)) {
                   12479:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12480:                 my $userallowed = 0;
                   12481:                 if ($slots{$slot}->{'allowedsections'}) {
                   12482:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12483:                     if (!defined($env{'request.role.sec'})
                   12484:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12485:                         $userallowed=1;
                   12486:                     } else {
                   12487:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12488:                             $userallowed=1;
                   12489:                         }
                   12490:                     }
                   12491:                     unless ($userallowed) {
                   12492:                         if (defined($env{'request.course.groups'})) {
                   12493:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12494:                             foreach my $group (@groups) {
                   12495:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12496:                                     $userallowed=1;
                   12497:                                     last;
                   12498:                                 }
                   12499:                             }
                   12500:                         }
                   12501:                     }
                   12502:                 }
                   12503:                 if ($slots{$slot}->{'allowedusers'}) {
                   12504:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12505:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12506:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12507:                         $userallowed = 1;
                   12508:                     }
                   12509:                 }
                   12510:                 next unless($userallowed);
                   12511:             }
                   12512:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12513:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12514:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12515:             my $uniqueperiod;
                   12516:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12517:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12518:             }
1.1040    raeburn  12519:             if (($startreserve < $now) &&
                   12520:                 (!$endreserve || $endreserve > $now)) {
                   12521:                 my $lastres = $endreserve;
                   12522:                 if (!$lastres) {
                   12523:                     $lastres = $slots{$slot}->{'starttime'};
                   12524:                 }
                   12525:                 $reservable_now{$slot} = {
                   12526:                                            symb       => $symb,
1.1250    raeburn  12527:                                            endreserve => $lastres,
                   12528:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12529:                                          };
                   12530:             } elsif (($startreserve > $now) &&
                   12531:                      (!$endreserve || $endreserve > $startreserve)) {
                   12532:                 $future_reservable{$slot} = {
                   12533:                                               symb         => $symb,
1.1250    raeburn  12534:                                               startreserve => $startreserve,
                   12535:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12536:                                             };
                   12537:             }
                   12538:         }
                   12539:     }
                   12540:     my @unsorted_reservable = keys(%reservable_now);
                   12541:     if (@unsorted_reservable > 0) {
                   12542:         @sorted_reservable = 
                   12543:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12544:     }
                   12545:     my @unsorted_future = keys(%future_reservable);
                   12546:     if (@unsorted_future > 0) {
                   12547:         @sorted_future =
                   12548:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12549:     }
                   12550:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12551: }
1.780     raeburn  12552: 
                   12553: =pod
                   12554: 
1.1057    foxr     12555: =back
                   12556: 
1.549     albertel 12557: =head1 HTTP Helpers
                   12558: 
                   12559: =over 4
                   12560: 
1.648     raeburn  12561: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12562: 
1.258     albertel 12563: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12564: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12565: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12566: 
                   12567: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12568: $possible_names is an ref to an array of form element names.  As an example:
                   12569: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12570: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12571: 
                   12572: =cut
1.1       albertel 12573: 
1.6       albertel 12574: sub get_unprocessed_cgi {
1.25      albertel 12575:   my ($query,$possible_names)= @_;
1.26      matthew  12576:   # $Apache::lonxml::debug=1;
1.356     albertel 12577:   foreach my $pair (split(/&/,$query)) {
                   12578:     my ($name, $value) = split(/=/,$pair);
1.369     www      12579:     $name = &unescape($name);
1.25      albertel 12580:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12581:       $value =~ tr/+/ /;
                   12582:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12583:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12584:     }
1.16      harris41 12585:   }
1.6       albertel 12586: }
                   12587: 
1.112     bowersj2 12588: =pod
                   12589: 
1.648     raeburn  12590: =item * &cacheheader() 
1.112     bowersj2 12591: 
                   12592: returns cache-controlling header code
                   12593: 
                   12594: =cut
                   12595: 
1.7       albertel 12596: sub cacheheader {
1.258     albertel 12597:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12598:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12599:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12600:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12601:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12602:     return $output;
1.7       albertel 12603: }
                   12604: 
1.112     bowersj2 12605: =pod
                   12606: 
1.648     raeburn  12607: =item * &no_cache($r) 
1.112     bowersj2 12608: 
                   12609: specifies header code to not have cache
                   12610: 
                   12611: =cut
                   12612: 
1.9       albertel 12613: sub no_cache {
1.216     albertel 12614:     my ($r) = @_;
                   12615:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12616: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12617:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12618:     $r->no_cache(1);
                   12619:     $r->header_out("Expires" => $date);
                   12620:     $r->header_out("Pragma" => "no-cache");
1.123     www      12621: }
                   12622: 
                   12623: sub content_type {
1.181     albertel 12624:     my ($r,$type,$charset) = @_;
1.299     foxr     12625:     if ($r) {
                   12626: 	#  Note that printout.pl calls this with undef for $r.
                   12627: 	&no_cache($r);
                   12628:     }
1.258     albertel 12629:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12630:     unless ($charset) {
                   12631: 	$charset=&Apache::lonlocal::current_encoding;
                   12632:     }
                   12633:     if ($charset) { $type.='; charset='.$charset; }
                   12634:     if ($r) {
                   12635: 	$r->content_type($type);
                   12636:     } else {
                   12637: 	print("Content-type: $type\n\n");
                   12638:     }
1.9       albertel 12639: }
1.25      albertel 12640: 
1.112     bowersj2 12641: =pod
                   12642: 
1.648     raeburn  12643: =item * &add_to_env($name,$value) 
1.112     bowersj2 12644: 
1.258     albertel 12645: adds $name to the %env hash with value
1.112     bowersj2 12646: $value, if $name already exists, the entry is converted to an array
                   12647: reference and $value is added to the array.
                   12648: 
                   12649: =cut
                   12650: 
1.25      albertel 12651: sub add_to_env {
                   12652:   my ($name,$value)=@_;
1.258     albertel 12653:   if (defined($env{$name})) {
                   12654:     if (ref($env{$name})) {
1.25      albertel 12655:       #already have multiple values
1.258     albertel 12656:       push(@{ $env{$name} },$value);
1.25      albertel 12657:     } else {
                   12658:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12659:       my $first=$env{$name};
                   12660:       undef($env{$name});
                   12661:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12662:     }
                   12663:   } else {
1.258     albertel 12664:     $env{$name}=$value;
1.25      albertel 12665:   }
1.31      albertel 12666: }
1.149     albertel 12667: 
                   12668: =pod
                   12669: 
1.648     raeburn  12670: =item * &get_env_multiple($name) 
1.149     albertel 12671: 
1.258     albertel 12672: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12673: values may be defined and end up as an array ref.
                   12674: 
                   12675: returns an array of values
                   12676: 
                   12677: =cut
                   12678: 
                   12679: sub get_env_multiple {
                   12680:     my ($name) = @_;
                   12681:     my @values;
1.258     albertel 12682:     if (defined($env{$name})) {
1.149     albertel 12683:         # exists is it an array
1.258     albertel 12684:         if (ref($env{$name})) {
                   12685:             @values=@{ $env{$name} };
1.149     albertel 12686:         } else {
1.258     albertel 12687:             $values[0]=$env{$name};
1.149     albertel 12688:         }
                   12689:     }
                   12690:     return(@values);
                   12691: }
                   12692: 
1.1249    damieng  12693: # Looks at given dependencies, and returns something depending on the context.
                   12694: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12695: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12696: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12697: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12698: # $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.
                   12699: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12700: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12701: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12702: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12703: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12704: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12705: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12706: # @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)
                   12707: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12708: sub ask_for_embedded_content {
1.1249    damieng  12709:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12710:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12711:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12712:         %currsubfile,%unused,$rem);
1.1071    raeburn  12713:     my $counter = 0;
                   12714:     my $numnew = 0;
1.987     raeburn  12715:     my $numremref = 0;
                   12716:     my $numinvalid = 0;
                   12717:     my $numpathchg = 0;
                   12718:     my $numexisting = 0;
1.1071    raeburn  12719:     my $numunused = 0;
                   12720:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12721:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12722:     my $heading = &mt('Upload embedded files');
                   12723:     my $buttontext = &mt('Upload');
                   12724: 
1.1249    damieng  12725:     # fills these variables based on the context:
                   12726:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12727:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12728:     if ($env{'request.course.id'}) {
1.1123    raeburn  12729:         if ($actionurl eq '/adm/dependencies') {
                   12730:             $navmap = Apache::lonnavmaps::navmap->new();
                   12731:         }
                   12732:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12733:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12734:     }
1.1123    raeburn  12735:     if (($actionurl eq '/adm/portfolio') || 
                   12736:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12737:         my $current_path='/';
                   12738:         if ($env{'form.currentpath'}) {
                   12739:             $current_path = $env{'form.currentpath'};
                   12740:         }
                   12741:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12742:             $udom = $cdom;
                   12743:             $uname = $cnum;
1.984     raeburn  12744:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12745:         } else {
                   12746:             $udom = $env{'user.domain'};
                   12747:             $uname = $env{'user.name'};
                   12748:             $url = '/userfiles/portfolio';
                   12749:         }
1.987     raeburn  12750:         $toplevel = $url.'/';
1.984     raeburn  12751:         $url .= $current_path;
                   12752:         $getpropath = 1;
1.987     raeburn  12753:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12754:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12755:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12756:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12757:         $toplevel = $url;
1.984     raeburn  12758:         if ($rest ne '') {
1.987     raeburn  12759:             $url .= $rest;
                   12760:         }
                   12761:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12762:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12763:             $url = $args->{'docs_url'};
                   12764:             $toplevel = $url;
1.1084    raeburn  12765:             if ($args->{'context'} eq 'paste') {
                   12766:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12767:                 ($path) = 
                   12768:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12769:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12770:                 $fileloc =~ s{^/}{};
                   12771:             }
1.1071    raeburn  12772:         }
1.1084    raeburn  12773:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12774:         if ($env{'request.course.id'} ne '') {
                   12775:             if (ref($args) eq 'HASH') {
                   12776:                 $url = $args->{'docs_url'};
                   12777:                 $title = $args->{'docs_title'};
1.1126    raeburn  12778:                 $toplevel = $url; 
                   12779:                 unless ($toplevel =~ m{^/}) {
                   12780:                     $toplevel = "/$url";
                   12781:                 }
1.1085    raeburn  12782:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12783:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12784:                     $path = $1;
                   12785:                 } else {
                   12786:                     ($path) =
                   12787:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12788:                 }
1.1195    raeburn  12789:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12790:                     $fileloc = $toplevel;
                   12791:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12792:                     my ($udom,$uname,$fname) =
                   12793:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12794:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12795:                 } else {
                   12796:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12797:                 }
1.1071    raeburn  12798:                 $fileloc =~ s{^/}{};
                   12799:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12800:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12801:             }
1.987     raeburn  12802:         }
1.1123    raeburn  12803:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12804:         $udom = $cdom;
                   12805:         $uname = $cnum;
                   12806:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12807:         $toplevel = $url;
                   12808:         $path = $url;
                   12809:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12810:         $fileloc =~ s{^/}{};
1.987     raeburn  12811:     }
1.1249    damieng  12812:     
                   12813:     # parses the dependency paths to get some info
                   12814:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12815:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12816:     # (will be completed later)
                   12817:     # $mapping:
                   12818:     #   for external URLs: external URL -> external URL
                   12819:     #   for relative paths: clean path -> original path
                   12820:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12821:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12822:     foreach my $file (keys(%{$allfiles})) {
                   12823:         my $embed_file;
                   12824:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12825:             $embed_file = $1;
                   12826:         } else {
                   12827:             $embed_file = $file;
                   12828:         }
1.1158    raeburn  12829:         my ($absolutepath,$cleaned_file);
                   12830:         if ($embed_file =~ m{^\w+://}) {
                   12831:             $cleaned_file = $embed_file;
1.1147    raeburn  12832:             $newfiles{$cleaned_file} = 1;
                   12833:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12834:         } else {
1.1158    raeburn  12835:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12836:             if ($embed_file =~ m{^/}) {
                   12837:                 $absolutepath = $embed_file;
                   12838:             }
1.1147    raeburn  12839:             if ($cleaned_file =~ m{/}) {
                   12840:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12841:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12842:                 my $item = $fname;
                   12843:                 if ($path ne '') {
                   12844:                     $item = $path.'/'.$fname;
                   12845:                     $subdependencies{$path}{$fname} = 1;
                   12846:                 } else {
                   12847:                     $dependencies{$item} = 1;
                   12848:                 }
                   12849:                 if ($absolutepath) {
                   12850:                     $mapping{$item} = $absolutepath;
                   12851:                 } else {
                   12852:                     $mapping{$item} = $embed_file;
                   12853:                 }
                   12854:             } else {
                   12855:                 $dependencies{$embed_file} = 1;
                   12856:                 if ($absolutepath) {
1.1147    raeburn  12857:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12858:                 } else {
1.1147    raeburn  12859:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12860:                 }
                   12861:             }
1.984     raeburn  12862:         }
                   12863:     }
1.1249    damieng  12864:     
                   12865:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12866:     # and lists
                   12867:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12868:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12869:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12870:     #                                    the path had to be cleaned up
                   12871:     # $existing: hash clean path -> 1 if the file exists
                   12872:     # $numexisting: number of keys in $existing
                   12873:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12874:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12875:     #                                      dependency subdirectories that are
                   12876:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12877:     my $dirptr = 16384;
1.984     raeburn  12878:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12879:         $currsubfile{$path} = {};
1.1123    raeburn  12880:         if (($actionurl eq '/adm/portfolio') || 
                   12881:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12882:             my ($sublistref,$listerror) =
                   12883:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12884:             if (ref($sublistref) eq 'ARRAY') {
                   12885:                 foreach my $line (@{$sublistref}) {
                   12886:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12887:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12888:                 }
1.984     raeburn  12889:             }
1.987     raeburn  12890:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12891:             if (opendir(my $dir,$url.'/'.$path)) {
                   12892:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12893:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12894:             }
1.1084    raeburn  12895:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12896:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12897:                   ($args->{'context'} eq 'paste')) ||
                   12898:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12899:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12900:                 my $dir;
                   12901:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12902:                     $dir = $fileloc;
                   12903:                 } else {
                   12904:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12905:                 }
1.1071    raeburn  12906:                 if ($dir ne '') {
                   12907:                     my ($sublistref,$listerror) =
                   12908:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12909:                     if (ref($sublistref) eq 'ARRAY') {
                   12910:                         foreach my $line (@{$sublistref}) {
                   12911:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12912:                                 undef,$mtime)=split(/\&/,$line,12);
                   12913:                             unless (($testdir&$dirptr) ||
                   12914:                                     ($file_name =~ /^\.\.?$/)) {
                   12915:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12916:                             }
                   12917:                         }
                   12918:                     }
                   12919:                 }
1.984     raeburn  12920:             }
                   12921:         }
                   12922:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12923:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12924:                 my $item = $path.'/'.$file;
                   12925:                 unless ($mapping{$item} eq $item) {
                   12926:                     $pathchanges{$item} = 1;
                   12927:                 }
                   12928:                 $existing{$item} = 1;
                   12929:                 $numexisting ++;
                   12930:             } else {
                   12931:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12932:             }
                   12933:         }
1.1071    raeburn  12934:         if ($actionurl eq '/adm/dependencies') {
                   12935:             foreach my $path (keys(%currsubfile)) {
                   12936:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12937:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12938:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12939:                              next if (($rem ne '') &&
                   12940:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12941:                                        (ref($navmap) &&
                   12942:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12943:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12944:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12945:                              $unused{$path.'/'.$file} = 1; 
                   12946:                          }
                   12947:                     }
                   12948:                 }
                   12949:             }
                   12950:         }
1.984     raeburn  12951:     }
1.1249    damieng  12952:     
                   12953:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12954:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12955:     my %currfile;
1.1123    raeburn  12956:     if (($actionurl eq '/adm/portfolio') ||
                   12957:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12958:         my ($dirlistref,$listerror) =
                   12959:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12960:         if (ref($dirlistref) eq 'ARRAY') {
                   12961:             foreach my $line (@{$dirlistref}) {
                   12962:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12963:                 $currfile{$file_name} = 1;
                   12964:             }
1.984     raeburn  12965:         }
1.987     raeburn  12966:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12967:         if (opendir(my $dir,$url)) {
1.987     raeburn  12968:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12969:             map {$currfile{$_} = 1;} @dir_list;
                   12970:         }
1.1084    raeburn  12971:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12972:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12973:               ($args->{'context'} eq 'paste')) ||
                   12974:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12975:         if ($env{'request.course.id'} ne '') {
                   12976:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12977:             if ($dir ne '') {
                   12978:                 my ($dirlistref,$listerror) =
                   12979:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12980:                 if (ref($dirlistref) eq 'ARRAY') {
                   12981:                     foreach my $line (@{$dirlistref}) {
                   12982:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12983:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12984:                         unless (($testdir&$dirptr) ||
                   12985:                                 ($file_name =~ /^\.\.?$/)) {
                   12986:                             $currfile{$file_name} = [$size,$mtime];
                   12987:                         }
                   12988:                     }
                   12989:                 }
                   12990:             }
                   12991:         }
1.984     raeburn  12992:     }
1.1249    damieng  12993:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12994:     # are not in subdirectories, using $currfile
1.984     raeburn  12995:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12996:         if (exists($currfile{$file})) {
1.987     raeburn  12997:             unless ($mapping{$file} eq $file) {
                   12998:                 $pathchanges{$file} = 1;
                   12999:             }
                   13000:             $existing{$file} = 1;
                   13001:             $numexisting ++;
                   13002:         } else {
1.984     raeburn  13003:             $newfiles{$file} = 1;
                   13004:         }
                   13005:     }
1.1071    raeburn  13006:     foreach my $file (keys(%currfile)) {
                   13007:         unless (($file eq $filename) ||
                   13008:                 ($file eq $filename.'.bak') ||
                   13009:                 ($dependencies{$file})) {
1.1085    raeburn  13010:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13011:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13012:                     next if (($rem ne '') &&
                   13013:                              (($env{"httpref.$rem".$file} ne '') ||
                   13014:                               (ref($navmap) &&
                   13015:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13016:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13017:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13018:                 }
1.1085    raeburn  13019:             }
1.1071    raeburn  13020:             $unused{$file} = 1;
                   13021:         }
                   13022:     }
1.1249    damieng  13023:     
                   13024:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13025:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13026:         ($args->{'context'} eq 'paste')) {
                   13027:         $counter = scalar(keys(%existing));
                   13028:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13029:         return ($output,$counter,$numpathchg,\%existing);
                   13030:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13031:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13032:         $counter = scalar(keys(%existing));
                   13033:         $numpathchg = scalar(keys(%pathchanges));
                   13034:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13035:     }
1.1249    damieng  13036:     
                   13037:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13038:     
                   13039:     # $upload_output: missing dependencies (with upload form)
                   13040:     # $modify_output: uploaded dependencies (in use)
                   13041:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13042:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13043:         if ($actionurl eq '/adm/dependencies') {
                   13044:             next if ($embed_file =~ m{^\w+://});
                   13045:         }
1.660     raeburn  13046:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13047:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13048:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13049:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13050:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13051:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13052:         }
1.1123    raeburn  13053:         $upload_output .= '</td>';
1.1071    raeburn  13054:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13055:             $upload_output.='<td align="right">'.
                   13056:                             '<span class="LC_info LC_fontsize_medium">'.
                   13057:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13058:             $numremref++;
1.660     raeburn  13059:         } elsif ($args->{'error_on_invalid_names'}
                   13060:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13061:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13062:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13063:             $numinvalid++;
1.660     raeburn  13064:         } else {
1.1123    raeburn  13065:             $upload_output .= '<td>'.
                   13066:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13067:                                                      $embed_file,\%mapping,
1.1071    raeburn  13068:                                                      $allfiles,$codebase,'upload');
                   13069:             $counter ++;
                   13070:             $numnew ++;
1.987     raeburn  13071:         }
                   13072:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13073:     }
                   13074:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13075:         if ($actionurl eq '/adm/dependencies') {
                   13076:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13077:             $modify_output .= &start_data_table_row().
                   13078:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13079:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13080:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13081:                               '<td>'.$size.'</td>'.
                   13082:                               '<td>'.$mtime.'</td>'.
                   13083:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13084:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13085:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13086:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13087:                               &embedded_file_element('upload_embedded',$counter,
                   13088:                                                      $embed_file,\%mapping,
                   13089:                                                      $allfiles,$codebase,'modify').
                   13090:                               '</div></td>'.
                   13091:                               &end_data_table_row()."\n";
                   13092:             $counter ++;
                   13093:         } else {
                   13094:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13095:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13096:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13097:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13098:                               &Apache::loncommon::end_data_table_row()."\n";
                   13099:         }
                   13100:     }
                   13101:     my $delidx = $counter;
                   13102:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13103:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13104:         $delete_output .= &start_data_table_row().
                   13105:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13106:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13107:                           '<td>'.$size.'</td>'.
                   13108:                           '<td>'.$mtime.'</td>'.
                   13109:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13110:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13111:                           &embedded_file_element('upload_embedded',$delidx,
                   13112:                                                  $oldfile,\%mapping,$allfiles,
                   13113:                                                  $codebase,'delete').'</td>'.
                   13114:                           &end_data_table_row()."\n"; 
                   13115:         $numunused ++;
                   13116:         $delidx ++;
1.987     raeburn  13117:     }
                   13118:     if ($upload_output) {
                   13119:         $upload_output = &start_data_table().
                   13120:                          $upload_output.
                   13121:                          &end_data_table()."\n";
                   13122:     }
1.1071    raeburn  13123:     if ($modify_output) {
                   13124:         $modify_output = &start_data_table().
                   13125:                          &start_data_table_header_row().
                   13126:                          '<th>'.&mt('File').'</th>'.
                   13127:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13128:                          '<th>'.&mt('Modified').'</th>'.
                   13129:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13130:                          &end_data_table_header_row().
                   13131:                          $modify_output.
                   13132:                          &end_data_table()."\n";
                   13133:     }
                   13134:     if ($delete_output) {
                   13135:         $delete_output = &start_data_table().
                   13136:                          &start_data_table_header_row().
                   13137:                          '<th>'.&mt('File').'</th>'.
                   13138:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13139:                          '<th>'.&mt('Modified').'</th>'.
                   13140:                          '<th>'.&mt('Delete?').'</th>'.
                   13141:                          &end_data_table_header_row().
                   13142:                          $delete_output.
                   13143:                          &end_data_table()."\n";
                   13144:     }
1.987     raeburn  13145:     my $applies = 0;
                   13146:     if ($numremref) {
                   13147:         $applies ++;
                   13148:     }
                   13149:     if ($numinvalid) {
                   13150:         $applies ++;
                   13151:     }
                   13152:     if ($numexisting) {
                   13153:         $applies ++;
                   13154:     }
1.1071    raeburn  13155:     if ($counter || $numunused) {
1.987     raeburn  13156:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13157:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13158:                   $state.'<h3>'.$heading.'</h3>'; 
                   13159:         if ($actionurl eq '/adm/dependencies') {
                   13160:             if ($numnew) {
                   13161:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13162:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13163:                            $upload_output.'<br />'."\n";
                   13164:             }
                   13165:             if ($numexisting) {
                   13166:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13167:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13168:                            $modify_output.'<br />'."\n";
                   13169:                            $buttontext = &mt('Save changes');
                   13170:             }
                   13171:             if ($numunused) {
                   13172:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13173:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13174:                            $delete_output.'<br />'."\n";
                   13175:                            $buttontext = &mt('Save changes');
                   13176:             }
                   13177:         } else {
                   13178:             $output .= $upload_output.'<br />'."\n";
                   13179:         }
                   13180:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13181:                    $counter.'" />'."\n";
                   13182:         if ($actionurl eq '/adm/dependencies') { 
                   13183:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13184:                        $numnew.'" />'."\n";
                   13185:         } elsif ($actionurl eq '') {
1.987     raeburn  13186:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13187:         }
                   13188:     } elsif ($applies) {
                   13189:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13190:         if ($applies > 1) {
                   13191:             $output .=  
1.1123    raeburn  13192:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13193:             if ($numremref) {
                   13194:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13195:             }
                   13196:             if ($numinvalid) {
                   13197:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13198:             }
                   13199:             if ($numexisting) {
                   13200:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13201:             }
                   13202:             $output .= '</ul><br />';
                   13203:         } elsif ($numremref) {
                   13204:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13205:         } elsif ($numinvalid) {
                   13206:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13207:         } elsif ($numexisting) {
                   13208:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13209:         }
                   13210:         $output .= $upload_output.'<br />';
                   13211:     }
                   13212:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13213:     $chgcount = $counter;
1.987     raeburn  13214:     if (keys(%pathchanges) > 0) {
                   13215:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13216:             if ($counter) {
1.987     raeburn  13217:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13218:                                                   $embed_file,\%mapping,
1.1071    raeburn  13219:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13220:             } else {
                   13221:                 $pathchange_output .= 
                   13222:                     &start_data_table_row().
                   13223:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13224:                     $chgcount.'" checked="checked" /></td>'.
                   13225:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13226:                     '<td>'.$embed_file.
                   13227:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13228:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13229:                     '</td>'.&end_data_table_row();
1.660     raeburn  13230:             }
1.987     raeburn  13231:             $numpathchg ++;
                   13232:             $chgcount ++;
1.660     raeburn  13233:         }
                   13234:     }
1.1127    raeburn  13235:     if (($counter) || ($numunused)) {
1.987     raeburn  13236:         if ($numpathchg) {
                   13237:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13238:                        $numpathchg.'" />'."\n";
                   13239:         }
                   13240:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13241:             ($actionurl eq '/adm/imsimport')) {
                   13242:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13243:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13244:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13245:         } elsif ($actionurl eq '/adm/dependencies') {
                   13246:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13247:         }
1.1123    raeburn  13248:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13249:     } elsif ($numpathchg) {
                   13250:         my %pathchange = ();
                   13251:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13252:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13253:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13254:         }
1.987     raeburn  13255:     }
1.1071    raeburn  13256:     return ($output,$counter,$numpathchg);
1.987     raeburn  13257: }
                   13258: 
1.1147    raeburn  13259: =pod
                   13260: 
                   13261: =item * clean_path($name)
                   13262: 
                   13263: Performs clean-up of directories, subdirectories and filename in an
                   13264: embedded object, referenced in an HTML file which is being uploaded
                   13265: to a course or portfolio, where 
                   13266: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13267: checked.
                   13268: 
                   13269: Clean-up is similar to replacements in lonnet::clean_filename()
                   13270: except each / between sub-directory and next level is preserved.
                   13271: 
                   13272: =cut
                   13273: 
                   13274: sub clean_path {
                   13275:     my ($embed_file) = @_;
                   13276:     $embed_file =~s{^/+}{};
                   13277:     my @contents;
                   13278:     if ($embed_file =~ m{/}) {
                   13279:         @contents = split(/\//,$embed_file);
                   13280:     } else {
                   13281:         @contents = ($embed_file);
                   13282:     }
                   13283:     my $lastidx = scalar(@contents)-1;
                   13284:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13285:         $contents[$i]=~s{\\}{/}g;
                   13286:         $contents[$i]=~s/\s+/\_/g;
                   13287:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13288:         if ($i == $lastidx) {
                   13289:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13290:         }
                   13291:     }
                   13292:     if ($lastidx > 0) {
                   13293:         return join('/',@contents);
                   13294:     } else {
                   13295:         return $contents[0];
                   13296:     }
                   13297: }
                   13298: 
1.987     raeburn  13299: sub embedded_file_element {
1.1071    raeburn  13300:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13301:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13302:                    (ref($codebase) eq 'HASH'));
                   13303:     my $output;
1.1071    raeburn  13304:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13305:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13306:     }
                   13307:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13308:                &escape($embed_file).'" />';
                   13309:     unless (($context eq 'upload_embedded') && 
                   13310:             ($mapping->{$embed_file} eq $embed_file)) {
                   13311:         $output .='
                   13312:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13313:     }
                   13314:     my $attrib;
                   13315:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13316:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13317:     }
                   13318:     $output .=
                   13319:         "\n\t\t".
                   13320:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13321:         $attrib.'" />';
                   13322:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13323:         $output .=
                   13324:             "\n\t\t".
                   13325:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13326:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13327:     }
1.987     raeburn  13328:     return $output;
1.660     raeburn  13329: }
                   13330: 
1.1071    raeburn  13331: sub get_dependency_details {
                   13332:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13333:     my ($size,$mtime,$showsize,$showmtime);
                   13334:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13335:         if ($embed_file =~ m{/}) {
                   13336:             my ($path,$fname) = split(/\//,$embed_file);
                   13337:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13338:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13339:             }
                   13340:         } else {
                   13341:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13342:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13343:             }
                   13344:         }
                   13345:         $showsize = $size/1024.0;
                   13346:         $showsize = sprintf("%.1f",$showsize);
                   13347:         if ($mtime > 0) {
                   13348:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13349:         }
                   13350:     }
                   13351:     return ($showsize,$showmtime);
                   13352: }
                   13353: 
                   13354: sub ask_embedded_js {
                   13355:     return <<"END";
                   13356: <script type="text/javascript"">
                   13357: // <![CDATA[
                   13358: function toggleBrowse(counter) {
                   13359:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13360:     var fileid = document.getElementById('embedded_item_'+counter);
                   13361:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13362:     if (chkboxid.checked == true) {
                   13363:         uploaddivid.style.display='block';
                   13364:     } else {
                   13365:         uploaddivid.style.display='none';
                   13366:         fileid.value = '';
                   13367:     }
                   13368: }
                   13369: // ]]>
                   13370: </script>
                   13371: 
                   13372: END
                   13373: }
                   13374: 
1.661     raeburn  13375: sub upload_embedded {
                   13376:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13377:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13378:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13379:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13380:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13381:         my $orig_uploaded_filename =
                   13382:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13383:         foreach my $type ('orig','ref','attrib','codebase') {
                   13384:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13385:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13386:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13387:             }
                   13388:         }
1.661     raeburn  13389:         my ($path,$fname) =
                   13390:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13391:         # no path, whole string is fname
                   13392:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13393:         $fname = &Apache::lonnet::clean_filename($fname);
                   13394:         # See if there is anything left
                   13395:         next if ($fname eq '');
                   13396: 
                   13397:         # Check if file already exists as a file or directory.
                   13398:         my ($state,$msg);
                   13399:         if ($context eq 'portfolio') {
                   13400:             my $port_path = $dirpath;
                   13401:             if ($group ne '') {
                   13402:                 $port_path = "groups/$group/$port_path";
                   13403:             }
1.987     raeburn  13404:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13405:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13406:                                               $dir_root,$port_path,$disk_quota,
                   13407:                                               $current_disk_usage,$uname,$udom);
                   13408:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13409:                 || $state eq 'file_locked') {
1.661     raeburn  13410:                 $output .= $msg;
                   13411:                 next;
                   13412:             }
                   13413:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13414:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13415:             if ($state eq 'exists') {
                   13416:                 $output .= $msg;
                   13417:                 next;
                   13418:             }
                   13419:         }
                   13420:         # Check if extension is valid
                   13421:         if (($fname =~ /\.(\w+)$/) &&
                   13422:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13423:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13424:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13425:             next;
                   13426:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13427:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13428:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13429:             next;
                   13430:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13431:             $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  13432:             next;
                   13433:         }
                   13434:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13435:         my $subdir = $path;
                   13436:         $subdir =~ s{/+$}{};
1.661     raeburn  13437:         if ($context eq 'portfolio') {
1.984     raeburn  13438:             my $result;
                   13439:             if ($state eq 'existingfile') {
                   13440:                 $result=
                   13441:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13442:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13443:             } else {
1.984     raeburn  13444:                 $result=
                   13445:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13446:                                                     $dirpath.
1.1123    raeburn  13447:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13448:                 if ($result !~ m|^/uploaded/|) {
                   13449:                     $output .= '<span class="LC_error">'
                   13450:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13451:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13452:                                .'</span><br />';
                   13453:                     next;
                   13454:                 } else {
1.987     raeburn  13455:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13456:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13457:                 }
1.661     raeburn  13458:             }
1.1123    raeburn  13459:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13460:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13461:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13462:             my $result =
1.1126    raeburn  13463:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13464:             if ($result !~ m|^/uploaded/|) {
                   13465:                 $output .= '<span class="LC_error">'
                   13466:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13467:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13468:                            .'</span><br />';
                   13469:                     next;
                   13470:             } else {
                   13471:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13472:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13473:                 if ($context eq 'syllabus') {
                   13474:                     &Apache::lonnet::make_public_indefinitely($result);
                   13475:                 }
1.987     raeburn  13476:             }
1.661     raeburn  13477:         } else {
                   13478: # Save the file
                   13479:             my $target = $env{'form.embedded_item_'.$i};
                   13480:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13481:             my $dest = $fullpath.$fname;
                   13482:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13483:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13484:             my $count;
                   13485:             my $filepath = $dir_root;
1.1027    raeburn  13486:             foreach my $subdir (@parts) {
                   13487:                 $filepath .= "/$subdir";
                   13488:                 if (!-e $filepath) {
1.661     raeburn  13489:                     mkdir($filepath,0770);
                   13490:                 }
                   13491:             }
                   13492:             my $fh;
                   13493:             if (!open($fh,'>'.$dest)) {
                   13494:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13495:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13496:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13497:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13498:                            '</span><br />';
                   13499:             } else {
                   13500:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13501:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13502:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13503:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13504:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13505:                               '</span><br />';
                   13506:                 } else {
1.987     raeburn  13507:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13508:                                $url.'</span>').'<br />';
                   13509:                     unless ($context eq 'testbank') {
                   13510:                         $footer .= &mt('View embedded file: [_1]',
                   13511:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13512:                     }
                   13513:                 }
                   13514:                 close($fh);
                   13515:             }
                   13516:         }
                   13517:         if ($env{'form.embedded_ref_'.$i}) {
                   13518:             $pathchange{$i} = 1;
                   13519:         }
                   13520:     }
                   13521:     if ($output) {
                   13522:         $output = '<p>'.$output.'</p>';
                   13523:     }
                   13524:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13525:     $returnflag = 'ok';
1.1071    raeburn  13526:     my $numpathchgs = scalar(keys(%pathchange));
                   13527:     if ($numpathchgs > 0) {
1.987     raeburn  13528:         if ($context eq 'portfolio') {
                   13529:             $output .= '<p>'.&mt('or').'</p>';
                   13530:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13531:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13532:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13533:             $returnflag = 'modify_orightml';
                   13534:         }
                   13535:     }
1.1071    raeburn  13536:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13537: }
                   13538: 
                   13539: sub modify_html_form {
                   13540:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13541:     my $end = 0;
                   13542:     my $modifyform;
                   13543:     if ($context eq 'upload_embedded') {
                   13544:         return unless (ref($pathchange) eq 'HASH');
                   13545:         if ($env{'form.number_embedded_items'}) {
                   13546:             $end += $env{'form.number_embedded_items'};
                   13547:         }
                   13548:         if ($env{'form.number_pathchange_items'}) {
                   13549:             $end += $env{'form.number_pathchange_items'};
                   13550:         }
                   13551:         if ($end) {
                   13552:             for (my $i=0; $i<$end; $i++) {
                   13553:                 if ($i < $env{'form.number_embedded_items'}) {
                   13554:                     next unless($pathchange->{$i});
                   13555:                 }
                   13556:                 $modifyform .=
                   13557:                     &start_data_table_row().
                   13558:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13559:                     'checked="checked" /></td>'.
                   13560:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13561:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13562:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13563:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13564:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13565:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13566:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13567:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13568:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13569:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13570:                     &end_data_table_row();
1.1071    raeburn  13571:             }
1.987     raeburn  13572:         }
                   13573:     } else {
                   13574:         $modifyform = $pathchgtable;
                   13575:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13576:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13577:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13578:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13579:         }
                   13580:     }
                   13581:     if ($modifyform) {
1.1071    raeburn  13582:         if ($actionurl eq '/adm/dependencies') {
                   13583:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13584:         }
1.987     raeburn  13585:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13586:                '<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".
                   13587:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13588:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13589:                '</ol></p>'."\n".'<p>'.
                   13590:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13591:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13592:                &start_data_table()."\n".
                   13593:                &start_data_table_header_row().
                   13594:                '<th>'.&mt('Change?').'</th>'.
                   13595:                '<th>'.&mt('Current reference').'</th>'.
                   13596:                '<th>'.&mt('Required reference').'</th>'.
                   13597:                &end_data_table_header_row()."\n".
                   13598:                $modifyform.
                   13599:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13600:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13601:                '</form>'."\n";
                   13602:     }
                   13603:     return;
                   13604: }
                   13605: 
                   13606: sub modify_html_refs {
1.1123    raeburn  13607:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13608:     my $container;
                   13609:     if ($context eq 'portfolio') {
                   13610:         $container = $env{'form.container'};
                   13611:     } elsif ($context eq 'coursedoc') {
                   13612:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13613:     } elsif ($context eq 'manage_dependencies') {
                   13614:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13615:         $container = "/$container";
1.1123    raeburn  13616:     } elsif ($context eq 'syllabus') {
                   13617:         $container = $url;
1.987     raeburn  13618:     } else {
1.1027    raeburn  13619:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13620:     }
                   13621:     my (%allfiles,%codebase,$output,$content);
                   13622:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13623:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13624:         if (wantarray) {
                   13625:             return ('',0,0); 
                   13626:         } else {
                   13627:             return;
                   13628:         }
                   13629:     }
                   13630:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13631:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13632:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13633:             if (wantarray) {
                   13634:                 return ('',0,0);
                   13635:             } else {
                   13636:                 return;
                   13637:             }
                   13638:         } 
1.987     raeburn  13639:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13640:         if ($content eq '-1') {
                   13641:             if (wantarray) {
                   13642:                 return ('',0,0);
                   13643:             } else {
                   13644:                 return;
                   13645:             }
                   13646:         }
1.987     raeburn  13647:     } else {
1.1071    raeburn  13648:         unless ($container =~ /^\Q$dir_root\E/) {
                   13649:             if (wantarray) {
                   13650:                 return ('',0,0);
                   13651:             } else {
                   13652:                 return;
                   13653:             }
                   13654:         } 
1.1317    raeburn  13655:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13656:             $content = join('', <$fh>);
                   13657:             close($fh);
                   13658:         } else {
1.1071    raeburn  13659:             if (wantarray) {
                   13660:                 return ('',0,0);
                   13661:             } else {
                   13662:                 return;
                   13663:             }
1.987     raeburn  13664:         }
                   13665:     }
                   13666:     my ($count,$codebasecount) = (0,0);
                   13667:     my $mm = new File::MMagic;
                   13668:     my $mime_type = $mm->checktype_contents($content);
                   13669:     if ($mime_type eq 'text/html') {
                   13670:         my $parse_result = 
                   13671:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13672:                                                     \%codebase,\$content);
                   13673:         if ($parse_result eq 'ok') {
                   13674:             foreach my $i (@changes) {
                   13675:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13676:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13677:                 if ($allfiles{$ref}) {
                   13678:                     my $newname =  $orig;
                   13679:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13680:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13681:                     if ($attrib_regexp =~ /:/) {
                   13682:                         $attrib_regexp =~ s/\:/|/g;
                   13683:                     }
                   13684:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13685:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13686:                         $count += $numchg;
1.1123    raeburn  13687:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13688:                         delete($allfiles{$ref});
1.987     raeburn  13689:                     }
                   13690:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13691:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13692:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13693:                         $codebasecount ++;
                   13694:                     }
                   13695:                 }
                   13696:             }
1.1123    raeburn  13697:             my $skiprewrites;
1.987     raeburn  13698:             if ($count || $codebasecount) {
                   13699:                 my $saveresult;
1.1071    raeburn  13700:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13701:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13702:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13703:                     if ($url eq $container) {
                   13704:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13705:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13706:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13707:                                             $fname.'</span>').'</p>';
1.987     raeburn  13708:                     } else {
                   13709:                          $output = '<p class="LC_error">'.
                   13710:                                    &mt('Error: update failed for: [_1].',
                   13711:                                    '<span class="LC_filename">'.
                   13712:                                    $container.'</span>').'</p>';
                   13713:                     }
1.1123    raeburn  13714:                     if ($context eq 'syllabus') {
                   13715:                         unless ($saveresult eq 'ok') {
                   13716:                             $skiprewrites = 1;
                   13717:                         }
                   13718:                     }
1.987     raeburn  13719:                 } else {
1.1317    raeburn  13720:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13721:                         print $fh $content;
                   13722:                         close($fh);
                   13723:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13724:                                   $count,'<span class="LC_filename">'.
                   13725:                                   $container.'</span>').'</p>';
1.661     raeburn  13726:                     } else {
1.987     raeburn  13727:                          $output = '<p class="LC_error">'.
                   13728:                                    &mt('Error: could not update [_1].',
                   13729:                                    '<span class="LC_filename">'.
                   13730:                                    $container.'</span>').'</p>';
1.661     raeburn  13731:                     }
                   13732:                 }
                   13733:             }
1.1123    raeburn  13734:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13735:                 my ($actionurl,$state);
                   13736:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13737:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13738:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13739:                                               \%codebase,
                   13740:                                               {'context' => 'rewrites',
                   13741:                                                'ignore_remote_references' => 1,});
                   13742:                 if (ref($mapping) eq 'HASH') {
                   13743:                     my $rewrites = 0;
                   13744:                     foreach my $key (keys(%{$mapping})) {
                   13745:                         next if ($key =~ m{^https?://});
                   13746:                         my $ref = $mapping->{$key};
                   13747:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13748:                         my $attrib;
                   13749:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13750:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13751:                         }
                   13752:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13753:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13754:                             $rewrites += $numchg;
                   13755:                         }
                   13756:                     }
                   13757:                     if ($rewrites) {
                   13758:                         my $saveresult; 
                   13759:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13760:                         if ($url eq $container) {
                   13761:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13762:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13763:                                             $count,'<span class="LC_filename">'.
                   13764:                                             $fname.'</span>').'</p>';
                   13765:                         } else {
                   13766:                             $output .= '<p class="LC_error">'.
                   13767:                                        &mt('Error: could not update links in [_1].',
                   13768:                                        '<span class="LC_filename">'.
                   13769:                                        $container.'</span>').'</p>';
                   13770: 
                   13771:                         }
                   13772:                     }
                   13773:                 }
                   13774:             }
1.987     raeburn  13775:         } else {
                   13776:             &logthis('Failed to parse '.$container.
                   13777:                      ' to modify references: '.$parse_result);
1.661     raeburn  13778:         }
                   13779:     }
1.1071    raeburn  13780:     if (wantarray) {
                   13781:         return ($output,$count,$codebasecount);
                   13782:     } else {
                   13783:         return $output;
                   13784:     }
1.661     raeburn  13785: }
                   13786: 
                   13787: sub check_for_existing {
                   13788:     my ($path,$fname,$element) = @_;
                   13789:     my ($state,$msg);
                   13790:     if (-d $path.'/'.$fname) {
                   13791:         $state = 'exists';
                   13792:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13793:     } elsif (-e $path.'/'.$fname) {
                   13794:         $state = 'exists';
                   13795:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13796:     }
                   13797:     if ($state eq 'exists') {
                   13798:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13799:     }
                   13800:     return ($state,$msg);
                   13801: }
                   13802: 
                   13803: sub check_for_upload {
                   13804:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13805:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13806:     my $filesize = length($env{'form.'.$element});
                   13807:     if (!$filesize) {
                   13808:         my $msg = '<span class="LC_error">'.
                   13809:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13810:                       '<span class="LC_filename">'.$fname.'</span>',
                   13811:                       $filesize).'<br />'.
1.1007    raeburn  13812:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13813:                   '</span>';
                   13814:         return ('zero_bytes',$msg);
                   13815:     }
                   13816:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13817:     my $getpropath = 1;
1.1021    raeburn  13818:     my ($dirlistref,$listerror) =
                   13819:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13820:     my $found_file = 0;
                   13821:     my $locked_file = 0;
1.991     raeburn  13822:     my @lockers;
                   13823:     my $navmap;
                   13824:     if ($env{'request.course.id'}) {
                   13825:         $navmap = Apache::lonnavmaps::navmap->new();
                   13826:     }
1.1021    raeburn  13827:     if (ref($dirlistref) eq 'ARRAY') {
                   13828:         foreach my $line (@{$dirlistref}) {
                   13829:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13830:             if ($file_name eq $fname){
                   13831:                 $file_name = $path.$file_name;
                   13832:                 if ($group ne '') {
                   13833:                     $file_name = $group.$file_name;
                   13834:                 }
                   13835:                 $found_file = 1;
                   13836:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13837:                     foreach my $lock (@lockers) {
                   13838:                         if (ref($lock) eq 'ARRAY') {
                   13839:                             my ($symb,$crsid) = @{$lock};
                   13840:                             if ($crsid eq $env{'request.course.id'}) {
                   13841:                                 if (ref($navmap)) {
                   13842:                                     my $res = $navmap->getBySymb($symb);
                   13843:                                     foreach my $part (@{$res->parts()}) { 
                   13844:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13845:                                         unless (($slot_status == $res->RESERVED) ||
                   13846:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13847:                                             $locked_file = 1;
                   13848:                                         }
1.991     raeburn  13849:                                     }
1.1021    raeburn  13850:                                 } else {
                   13851:                                     $locked_file = 1;
1.991     raeburn  13852:                                 }
                   13853:                             } else {
                   13854:                                 $locked_file = 1;
                   13855:                             }
                   13856:                         }
1.1021    raeburn  13857:                    }
                   13858:                 } else {
                   13859:                     my @info = split(/\&/,$rest);
                   13860:                     my $currsize = $info[6]/1000;
                   13861:                     if ($currsize < $filesize) {
                   13862:                         my $extra = $filesize - $currsize;
                   13863:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13864:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13865:                                       &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   13866:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13867:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13868:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13869:                             return ('will_exceed_quota',$msg);
                   13870:                         }
1.984     raeburn  13871:                     }
                   13872:                 }
1.661     raeburn  13873:             }
                   13874:         }
                   13875:     }
                   13876:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13877:         my $msg = '<p class="LC_warning">'.
                   13878:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13879:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13880:         return ('will_exceed_quota',$msg);
                   13881:     } elsif ($found_file) {
                   13882:         if ($locked_file) {
1.1179    bisitz   13883:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13884:             $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   13885:             $msg .= '</p>';
1.661     raeburn  13886:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13887:             return ('file_locked',$msg);
                   13888:         } else {
1.1179    bisitz   13889:             my $msg = '<p class="LC_error">';
1.984     raeburn  13890:             $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   13891:             $msg .= '</p>';
1.984     raeburn  13892:             return ('existingfile',$msg);
1.661     raeburn  13893:         }
                   13894:     }
                   13895: }
                   13896: 
1.987     raeburn  13897: sub check_for_traversal {
                   13898:     my ($path,$url,$toplevel) = @_;
                   13899:     my @parts=split(/\//,$path);
                   13900:     my $cleanpath;
                   13901:     my $fullpath = $url;
                   13902:     for (my $i=0;$i<@parts;$i++) {
                   13903:         next if ($parts[$i] eq '.');
                   13904:         if ($parts[$i] eq '..') {
                   13905:             $fullpath =~ s{([^/]+/)$}{};
                   13906:         } else {
                   13907:             $fullpath .= $parts[$i].'/';
                   13908:         }
                   13909:     }
                   13910:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13911:         $cleanpath = $1;
                   13912:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13913:         my $curr_toprel = $1;
                   13914:         my @parts = split(/\//,$curr_toprel);
                   13915:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13916:         my @urlparts = split(/\//,$url_toprel);
                   13917:         my $doubledots;
                   13918:         my $startdiff = -1;
                   13919:         for (my $i=0; $i<@urlparts; $i++) {
                   13920:             if ($startdiff == -1) {
                   13921:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13922:                     $startdiff = $i;
                   13923:                     $doubledots .= '../';
                   13924:                 }
                   13925:             } else {
                   13926:                 $doubledots .= '../';
                   13927:             }
                   13928:         }
                   13929:         if ($startdiff > -1) {
                   13930:             $cleanpath = $doubledots;
                   13931:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13932:                 $cleanpath .= $parts[$i].'/';
                   13933:             }
                   13934:         }
                   13935:     }
                   13936:     $cleanpath =~ s{(/)$}{};
                   13937:     return $cleanpath;
                   13938: }
1.31      albertel 13939: 
1.1053    raeburn  13940: sub is_archive_file {
                   13941:     my ($mimetype) = @_;
                   13942:     if (($mimetype eq 'application/octet-stream') ||
                   13943:         ($mimetype eq 'application/x-stuffit') ||
                   13944:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13945:         return 1;
                   13946:     }
                   13947:     return;
                   13948: }
                   13949: 
                   13950: sub decompress_form {
1.1065    raeburn  13951:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13952:     my %lt = &Apache::lonlocal::texthash (
                   13953:         this => 'This file is an archive file.',
1.1067    raeburn  13954:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13955:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13956:         youm => 'You may wish to extract its contents.',
                   13957:         extr => 'Extract contents',
1.1067    raeburn  13958:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13959:         proa => 'Process automatically?',
1.1053    raeburn  13960:         yes  => 'Yes',
                   13961:         no   => 'No',
1.1067    raeburn  13962:         fold => 'Title for folder containing movie',
                   13963:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13964:     );
1.1065    raeburn  13965:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13966:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13967:     my $info = &list_archive_contents($fileloc,\@paths);
                   13968:     if (@paths) {
                   13969:         foreach my $path (@paths) {
                   13970:             $path =~ s{^/}{};
1.1067    raeburn  13971:             if ($path =~ m{^([^/]+)/$}) {
                   13972:                 $topdir = $1;
                   13973:             }
1.1065    raeburn  13974:             if ($path =~ m{^([^/]+)/}) {
                   13975:                 $toplevel{$1} = $path;
                   13976:             } else {
                   13977:                 $toplevel{$path} = $path;
                   13978:             }
                   13979:         }
                   13980:     }
1.1067    raeburn  13981:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13982:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13983:                         "$topdir/media/",
                   13984:                         "$topdir/media/$topdir.mp4",
                   13985:                         "$topdir/media/FirstFrame.png",
                   13986:                         "$topdir/media/player.swf",
                   13987:                         "$topdir/media/swfobject.js",
                   13988:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13989:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13990:                          "$topdir/$topdir.mp4",
                   13991:                          "$topdir/$topdir\_config.xml",
                   13992:                          "$topdir/$topdir\_controller.swf",
                   13993:                          "$topdir/$topdir\_embed.css",
                   13994:                          "$topdir/$topdir\_First_Frame.png",
                   13995:                          "$topdir/$topdir\_player.html",
                   13996:                          "$topdir/$topdir\_Thumbnails.png",
                   13997:                          "$topdir/playerProductInstall.swf",
                   13998:                          "$topdir/scripts/",
                   13999:                          "$topdir/scripts/config_xml.js",
                   14000:                          "$topdir/scripts/handlebars.js",
                   14001:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14002:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14003:                          "$topdir/scripts/modernizr.js",
                   14004:                          "$topdir/scripts/player-min.js",
                   14005:                          "$topdir/scripts/swfobject.js",
                   14006:                          "$topdir/skins/",
                   14007:                          "$topdir/skins/configuration_express.xml",
                   14008:                          "$topdir/skins/express_show/",
                   14009:                          "$topdir/skins/express_show/player-min.css",
                   14010:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14011:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14012:                          "$topdir/$topdir.mp4",
                   14013:                          "$topdir/$topdir\_config.xml",
                   14014:                          "$topdir/$topdir\_controller.swf",
                   14015:                          "$topdir/$topdir\_embed.css",
                   14016:                          "$topdir/$topdir\_First_Frame.png",
                   14017:                          "$topdir/$topdir\_player.html",
                   14018:                          "$topdir/$topdir\_Thumbnails.png",
                   14019:                          "$topdir/playerProductInstall.swf",
                   14020:                          "$topdir/scripts/",
                   14021:                          "$topdir/scripts/config_xml.js",
                   14022:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14023:                          "$topdir/skins/",
                   14024:                          "$topdir/skins/configuration_express.xml",
                   14025:                          "$topdir/skins/express_show/",
                   14026:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14027:                          "$topdir/skins/express_show/spritesheet.png",
                   14028:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14029:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14030:         if (@diffs == 0) {
1.1164    raeburn  14031:             $is_camtasia = 6;
                   14032:         } else {
1.1197    raeburn  14033:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14034:             if (@diffs == 0) {
                   14035:                 $is_camtasia = 8;
1.1197    raeburn  14036:             } else {
                   14037:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14038:                 if (@diffs == 0) {
                   14039:                     $is_camtasia = 8;
                   14040:                 }
1.1164    raeburn  14041:             }
1.1067    raeburn  14042:         }
                   14043:     }
                   14044:     my $output;
                   14045:     if ($is_camtasia) {
                   14046:         $output = <<"ENDCAM";
                   14047: <script type="text/javascript" language="Javascript">
                   14048: // <![CDATA[
                   14049: 
                   14050: function camtasiaToggle() {
                   14051:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14052:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14053:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14054:                 document.getElementById('camtasia_titles').style.display='block';
                   14055:             } else {
                   14056:                 document.getElementById('camtasia_titles').style.display='none';
                   14057:             }
                   14058:         }
                   14059:     }
                   14060:     return;
                   14061: }
                   14062: 
                   14063: // ]]>
                   14064: </script>
                   14065: <p>$lt{'camt'}</p>
                   14066: ENDCAM
1.1065    raeburn  14067:     } else {
1.1067    raeburn  14068:         $output = '<p>'.$lt{'this'};
                   14069:         if ($info eq '') {
                   14070:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14071:         } else {
                   14072:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14073:                        '<div><pre>'.$info.'</pre></div>';
                   14074:         }
1.1065    raeburn  14075:     }
1.1067    raeburn  14076:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14077:     my $duplicates;
                   14078:     my $num = 0;
                   14079:     if (ref($dirlist) eq 'ARRAY') {
                   14080:         foreach my $item (@{$dirlist}) {
                   14081:             if (ref($item) eq 'ARRAY') {
                   14082:                 if (exists($toplevel{$item->[0]})) {
                   14083:                     $duplicates .= 
                   14084:                         &start_data_table_row().
                   14085:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14086:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14087:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14088:                         'value="1" />'.&mt('Yes').'</label>'.
                   14089:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14090:                         '<td>'.$item->[0].'</td>';
                   14091:                     if ($item->[2]) {
                   14092:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14093:                     } else {
                   14094:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14095:                     }
                   14096:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14097:                                    '<td>'.
                   14098:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14099:                                    '</td>'.
                   14100:                                    &end_data_table_row();
                   14101:                     $num ++;
                   14102:                 }
                   14103:             }
                   14104:         }
                   14105:     }
                   14106:     my $itemcount;
                   14107:     if (@paths > 0) {
                   14108:         $itemcount = scalar(@paths);
                   14109:     } else {
                   14110:         $itemcount = 1;
                   14111:     }
1.1067    raeburn  14112:     if ($is_camtasia) {
                   14113:         $output .= $lt{'auto'}.'<br />'.
                   14114:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14115:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14116:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14117:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14118:                    $lt{'no'}.'</label></span><br />'.
                   14119:                    '<div id="camtasia_titles" style="display:block">'.
                   14120:                    &Apache::lonhtmlcommon::start_pick_box().
                   14121:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14122:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14123:                    &Apache::lonhtmlcommon::row_closure().
                   14124:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14125:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14126:                    &Apache::lonhtmlcommon::row_closure(1).
                   14127:                    &Apache::lonhtmlcommon::end_pick_box().
                   14128:                    '</div>';
                   14129:     }
1.1065    raeburn  14130:     $output .= 
                   14131:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14132:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14133:         "\n";
1.1065    raeburn  14134:     if ($duplicates ne '') {
                   14135:         $output .= '<p><span class="LC_warning">'.
                   14136:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14137:                    &start_data_table().
                   14138:                    &start_data_table_header_row().
                   14139:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14140:                    '<th>'.&mt('Name').'</th>'.
                   14141:                    '<th>'.&mt('Type').'</th>'.
                   14142:                    '<th>'.&mt('Size').'</th>'.
                   14143:                    '<th>'.&mt('Last modified').'</th>'.
                   14144:                    &end_data_table_header_row().
                   14145:                    $duplicates.
                   14146:                    &end_data_table().
                   14147:                    '</p>';
                   14148:     }
1.1067    raeburn  14149:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14150:     if (ref($hiddenelements) eq 'HASH') {
                   14151:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14152:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14153:         }
                   14154:     }
                   14155:     $output .= <<"END";
1.1067    raeburn  14156: <br />
1.1053    raeburn  14157: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14158: </form>
                   14159: $noextract
                   14160: END
                   14161:     return $output;
                   14162: }
                   14163: 
1.1065    raeburn  14164: sub decompression_utility {
                   14165:     my ($program) = @_;
                   14166:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14167:     my $location;
                   14168:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14169:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14170:                          '/usr/sbin/') {
                   14171:             if (-x $dir.$program) {
                   14172:                 $location = $dir.$program;
                   14173:                 last;
                   14174:             }
                   14175:         }
                   14176:     }
                   14177:     return $location;
                   14178: }
                   14179: 
                   14180: sub list_archive_contents {
                   14181:     my ($file,$pathsref) = @_;
                   14182:     my (@cmd,$output);
                   14183:     my $needsregexp;
                   14184:     if ($file =~ /\.zip$/) {
                   14185:         @cmd = (&decompression_utility('unzip'),"-l");
                   14186:         $needsregexp = 1;
                   14187:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14188:              ($file =~ /\.tgz$/)) {
                   14189:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14190:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14191:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14192:     } elsif ($file =~ m|\.tar$|) {
                   14193:         @cmd = (&decompression_utility('tar'),"-tf");
                   14194:     }
                   14195:     if (@cmd) {
                   14196:         undef($!);
                   14197:         undef($@);
                   14198:         if (open(my $fh,"-|", @cmd, $file)) {
                   14199:             while (my $line = <$fh>) {
                   14200:                 $output .= $line;
                   14201:                 chomp($line);
                   14202:                 my $item;
                   14203:                 if ($needsregexp) {
                   14204:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14205:                 } else {
                   14206:                     $item = $line;
                   14207:                 }
                   14208:                 if ($item ne '') {
                   14209:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14210:                         push(@{$pathsref},$item);
                   14211:                     } 
                   14212:                 }
                   14213:             }
                   14214:             close($fh);
                   14215:         }
                   14216:     }
                   14217:     return $output;
                   14218: }
                   14219: 
1.1053    raeburn  14220: sub decompress_uploaded_file {
                   14221:     my ($file,$dir) = @_;
                   14222:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14223:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14224:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14225:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14226:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14227:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14228:     my $decompressed = $env{'cgi.decompressed'};
                   14229:     &Apache::lonnet::delenv('cgi.file');
                   14230:     &Apache::lonnet::delenv('cgi.dir');
                   14231:     &Apache::lonnet::delenv('cgi.decompressed');
                   14232:     return ($decompressed,$result);
                   14233: }
                   14234: 
1.1055    raeburn  14235: sub process_decompression {
                   14236:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14237:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14238:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14239:                &mt('Unexpected file path.').'</p>'."\n";
                   14240:     }
                   14241:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14242:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14243:                &mt('Unexpected course context.').'</p>'."\n";
                   14244:     }
1.1293    raeburn  14245:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14246:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14247:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14248:     }
1.1055    raeburn  14249:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14250:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14251:         $error = &mt('Filename not a supported archive file type.').
                   14252:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14253:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14254:     } else {
                   14255:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14256:         if ($docuhome eq 'no_host') {
                   14257:             $error = &mt('Could not determine home server for course.');
                   14258:         } else {
                   14259:             my @ids=&Apache::lonnet::current_machine_ids();
                   14260:             my $currdir = "$dir_root/$destination";
                   14261:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14262:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14263:                        "$dir_root/$destination";
                   14264:             } else {
                   14265:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14266:                        "$dir_root/$docudom/$docuname/$destination";
                   14267:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14268:                     $error = &mt('Archive file not found.');
                   14269:                 }
                   14270:             }
1.1065    raeburn  14271:             my (@to_overwrite,@to_skip);
                   14272:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14273:                 my $total = $env{'form.archive_overwrite_total'};
                   14274:                 for (my $i=0; $i<$total; $i++) {
                   14275:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14276:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14277:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14278:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14279:                     }
                   14280:                 }
                   14281:             }
                   14282:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14283:             my $numoverwrite = scalar(@to_overwrite);
                   14284:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14285:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14286:             } elsif ($dir eq '') {
1.1055    raeburn  14287:                 $error = &mt('Directory containing archive file unavailable.');
                   14288:             } elsif (!$error) {
1.1065    raeburn  14289:                 my ($decompressed,$display);
1.1292    raeburn  14290:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14291:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14292:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14293:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14294:                         ($decompressed,$display) = 
                   14295:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14296:                         foreach my $item (@to_skip) {
                   14297:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14298:                                 if (-f "$dir/$tempdir/$item") { 
                   14299:                                     unlink("$dir/$tempdir/$item");
                   14300:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14301:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14302:                                 }
                   14303:                             }
                   14304:                         }
                   14305:                         foreach my $item (@to_overwrite) {
                   14306:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14307:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14308:                                     if (-f "$dir/$item") {
                   14309:                                         unlink("$dir/$item");
                   14310:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14311:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14312:                                     }
                   14313:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14314:                                 }
1.1065    raeburn  14315:                             }
                   14316:                         }
1.1292    raeburn  14317:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14318:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14319:                         }
1.1065    raeburn  14320:                     }
                   14321:                 } else {
                   14322:                     ($decompressed,$display) = 
                   14323:                         &decompress_uploaded_file($file,$dir);
                   14324:                 }
1.1055    raeburn  14325:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14326:                     $output = '<p class="LC_info">'.
                   14327:                               &mt('Files extracted successfully from archive.').
                   14328:                               '</p>'."\n";
1.1055    raeburn  14329:                     my ($warning,$result,@contents);
                   14330:                     my ($newdirlistref,$newlisterror) =
                   14331:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14332:                                                  $docuname,1);
                   14333:                     my (%is_dir,%changes,@newitems);
                   14334:                     my $dirptr = 16384;
1.1065    raeburn  14335:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14336:                         foreach my $dir_line (@{$newdirlistref}) {
                   14337:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14338:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14339:                                 push(@newitems,$item);
                   14340:                                 if ($dirptr&$testdir) {
                   14341:                                     $is_dir{$item} = 1;
                   14342:                                 }
                   14343:                                 $changes{$item} = 1;
                   14344:                             }
                   14345:                         }
                   14346:                     }
                   14347:                     if (keys(%changes) > 0) {
                   14348:                         foreach my $item (sort(@newitems)) {
                   14349:                             if ($changes{$item}) {
                   14350:                                 push(@contents,$item);
                   14351:                             }
                   14352:                         }
                   14353:                     }
                   14354:                     if (@contents > 0) {
1.1067    raeburn  14355:                         my $wantform;
                   14356:                         unless ($env{'form.autoextract_camtasia'}) {
                   14357:                             $wantform = 1;
                   14358:                         }
1.1056    raeburn  14359:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14360:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14361:                                                                 $currdir,\%is_dir,
                   14362:                                                                 \%children,\%parent,
1.1056    raeburn  14363:                                                                 \@contents,\%dirorder,
                   14364:                                                                 \%titles,$wantform);
1.1055    raeburn  14365:                         if ($datatable ne '') {
                   14366:                             $output .= &archive_options_form('decompressed',$datatable,
                   14367:                                                              $count,$hiddenelem);
1.1065    raeburn  14368:                             my $startcount = 6;
1.1055    raeburn  14369:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14370:                                                            \%titles,\%children);
1.1055    raeburn  14371:                         }
1.1067    raeburn  14372:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14373:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14374:                             my %displayed;
                   14375:                             my $total = 1;
                   14376:                             $env{'form.archive_directory'} = [];
                   14377:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14378:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14379:                                 $path =~ s{/$}{};
                   14380:                                 my $item;
                   14381:                                 if ($path ne '') {
                   14382:                                     $item = "$path/$titles{$i}";
                   14383:                                 } else {
                   14384:                                     $item = $titles{$i};
                   14385:                                 }
                   14386:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14387:                                 if ($item eq $contents[0]) {
                   14388:                                     push(@{$env{'form.archive_directory'}},$i);
                   14389:                                     $env{'form.archive_'.$i} = 'display';
                   14390:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14391:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14392:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14393:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14394:                                     $env{'form.archive_'.$i} = 'display';
                   14395:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14396:                                     $displayed{'web'} = $i;
                   14397:                                 } else {
1.1164    raeburn  14398:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14399:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14400:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14401:                                         push(@{$env{'form.archive_directory'}},$i);
                   14402:                                     }
                   14403:                                     $env{'form.archive_'.$i} = 'dependency';
                   14404:                                 }
                   14405:                                 $total ++;
                   14406:                             }
                   14407:                             for (my $i=1; $i<$total; $i++) {
                   14408:                                 next if ($i == $displayed{'web'});
                   14409:                                 next if ($i == $displayed{'folder'});
                   14410:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14411:                             }
                   14412:                             $env{'form.phase'} = 'decompress_cleanup';
                   14413:                             $env{'form.archivedelete'} = 1;
                   14414:                             $env{'form.archive_count'} = $total-1;
                   14415:                             $output .=
                   14416:                                 &process_extracted_files('coursedocs',$docudom,
                   14417:                                                          $docuname,$destination,
                   14418:                                                          $dir_root,$hiddenelem);
                   14419:                         }
1.1055    raeburn  14420:                     } else {
                   14421:                         $warning = &mt('No new items extracted from archive file.');
                   14422:                     }
                   14423:                 } else {
                   14424:                     $output = $display;
                   14425:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14426:                 }
                   14427:             }
                   14428:         }
                   14429:     }
                   14430:     if ($error) {
                   14431:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14432:                    $error.'</p>'."\n";
                   14433:     }
                   14434:     if ($warning) {
                   14435:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14436:     }
                   14437:     return $output;
                   14438: }
                   14439: 
                   14440: sub get_extracted {
1.1056    raeburn  14441:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14442:         $titles,$wantform) = @_;
1.1055    raeburn  14443:     my $count = 0;
                   14444:     my $depth = 0;
                   14445:     my $datatable;
1.1056    raeburn  14446:     my @hierarchy;
1.1055    raeburn  14447:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14448:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14449:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14450:     foreach my $item (@{$contents}) {
                   14451:         $count ++;
1.1056    raeburn  14452:         @{$dirorder->{$count}} = @hierarchy;
                   14453:         $titles->{$count} = $item;
1.1055    raeburn  14454:         &archive_hierarchy($depth,$count,$parent,$children);
                   14455:         if ($wantform) {
                   14456:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14457:                                        $currdir,$depth,$count);
                   14458:         }
                   14459:         if ($is_dir->{$item}) {
                   14460:             $depth ++;
1.1056    raeburn  14461:             push(@hierarchy,$count);
                   14462:             $parent->{$depth} = $count;
1.1055    raeburn  14463:             $datatable .=
                   14464:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14465:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14466:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14467:             $depth --;
1.1056    raeburn  14468:             pop(@hierarchy);
1.1055    raeburn  14469:         }
                   14470:     }
                   14471:     return ($count,$datatable);
                   14472: }
                   14473: 
                   14474: sub recurse_extracted_archive {
1.1056    raeburn  14475:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14476:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14477:     my $result='';
1.1056    raeburn  14478:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14479:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14480:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14481:         return $result;
                   14482:     }
                   14483:     my $dirptr = 16384;
                   14484:     my ($newdirlistref,$newlisterror) =
                   14485:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14486:     if (ref($newdirlistref) eq 'ARRAY') {
                   14487:         foreach my $dir_line (@{$newdirlistref}) {
                   14488:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14489:             unless ($item =~ /^\.+$/) {
                   14490:                 $$count ++;
1.1056    raeburn  14491:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14492:                 $titles->{$$count} = $item;
1.1055    raeburn  14493:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14494: 
1.1055    raeburn  14495:                 my $is_dir;
                   14496:                 if ($dirptr&$testdir) {
                   14497:                     $is_dir = 1;
                   14498:                 }
                   14499:                 if ($wantform) {
                   14500:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14501:                 }
                   14502:                 if ($is_dir) {
                   14503:                     $$depth ++;
1.1056    raeburn  14504:                     push(@{$hierarchy},$$count);
                   14505:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14506:                     $result .=
                   14507:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14508:                                                    $docuname,$depth,$count,
1.1056    raeburn  14509:                                                    $hierarchy,$dirorder,$children,
                   14510:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14511:                     $$depth --;
1.1056    raeburn  14512:                     pop(@{$hierarchy});
1.1055    raeburn  14513:                 }
                   14514:             }
                   14515:         }
                   14516:     }
                   14517:     return $result;
                   14518: }
                   14519: 
                   14520: sub archive_hierarchy {
                   14521:     my ($depth,$count,$parent,$children) =@_;
                   14522:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14523:         if (exists($parent->{$depth})) {
                   14524:              $children->{$parent->{$depth}} .= $count.':';
                   14525:         }
                   14526:     }
                   14527:     return;
                   14528: }
                   14529: 
                   14530: sub archive_row {
                   14531:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14532:     my ($name) = ($item =~ m{([^/]+)$});
                   14533:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14534:                                        'display'    => 'Add as file',
1.1055    raeburn  14535:                                        'dependency' => 'Include as dependency',
                   14536:                                        'discard'    => 'Discard',
                   14537:                                       );
                   14538:     if ($is_dir) {
1.1059    raeburn  14539:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14540:     }
1.1056    raeburn  14541:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14542:     my $offset = 0;
1.1055    raeburn  14543:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14544:         $offset ++;
1.1065    raeburn  14545:         if ($action ne 'display') {
                   14546:             $offset ++;
                   14547:         }  
1.1055    raeburn  14548:         $output .= '<td><span class="LC_nobreak">'.
                   14549:                    '<label><input type="radio" name="archive_'.$count.
                   14550:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14551:         my $text = $choices{$action};
                   14552:         if ($is_dir) {
                   14553:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14554:             if ($action eq 'display') {
1.1059    raeburn  14555:                 $text = &mt('Add as folder');
1.1055    raeburn  14556:             }
1.1056    raeburn  14557:         } else {
                   14558:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14559: 
                   14560:         }
                   14561:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14562:         if ($action eq 'dependency') {
                   14563:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14564:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14565:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14566:                        '<option value=""></option>'."\n".
                   14567:                        '</select>'."\n".
                   14568:                        '</div>';
1.1059    raeburn  14569:         } elsif ($action eq 'display') {
                   14570:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14571:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14572:                        '</div>';
1.1055    raeburn  14573:         }
1.1056    raeburn  14574:         $output .= '</td>';
1.1055    raeburn  14575:     }
                   14576:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14577:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14578:     for (my $i=0; $i<$depth; $i++) {
                   14579:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14580:     }
                   14581:     if ($is_dir) {
                   14582:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14583:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14584:     } else {
                   14585:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14586:     }
                   14587:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14588:                &end_data_table_row();
                   14589:     return $output;
                   14590: }
                   14591: 
                   14592: sub archive_options_form {
1.1065    raeburn  14593:     my ($form,$display,$count,$hiddenelem) = @_;
                   14594:     my %lt = &Apache::lonlocal::texthash(
                   14595:                perm => 'Permanently remove archive file?',
                   14596:                hows => 'How should each extracted item be incorporated in the course?',
                   14597:                cont => 'Content actions for all',
                   14598:                addf => 'Add as folder/file',
                   14599:                incd => 'Include as dependency for a displayed file',
                   14600:                disc => 'Discard',
                   14601:                no   => 'No',
                   14602:                yes  => 'Yes',
                   14603:                save => 'Save',
                   14604:     );
                   14605:     my $output = <<"END";
                   14606: <form name="$form" method="post" action="">
                   14607: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14608: <label>
                   14609:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14610: </label>
                   14611: &nbsp;
                   14612: <label>
                   14613:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14614: </span>
                   14615: </p>
                   14616: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14617: <br />$lt{'hows'}
                   14618: <div class="LC_columnSection">
                   14619:   <fieldset>
                   14620:     <legend>$lt{'cont'}</legend>
                   14621:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14622:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14623:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14624:   </fieldset>
                   14625: </div>
                   14626: END
                   14627:     return $output.
1.1055    raeburn  14628:            &start_data_table()."\n".
1.1065    raeburn  14629:            $display."\n".
1.1055    raeburn  14630:            &end_data_table()."\n".
                   14631:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14632:            $hiddenelem.
1.1065    raeburn  14633:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14634:            '</form>';
                   14635: }
                   14636: 
                   14637: sub archive_javascript {
1.1056    raeburn  14638:     my ($startcount,$numitems,$titles,$children) = @_;
                   14639:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14640:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14641:     my $scripttag = <<START;
                   14642: <script type="text/javascript">
                   14643: // <![CDATA[
                   14644: 
                   14645: function checkAll(form,prefix) {
                   14646:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14647:     for (var i=0; i < form.elements.length; i++) {
                   14648:         var id = form.elements[i].id;
                   14649:         if ((id != '') && (id != undefined)) {
                   14650:             if (idstr.test(id)) {
                   14651:                 if (form.elements[i].type == 'radio') {
                   14652:                     form.elements[i].checked = true;
1.1056    raeburn  14653:                     var nostart = i-$startcount;
1.1059    raeburn  14654:                     var offset = nostart%7;
                   14655:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14656:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14657:                 }
                   14658:             }
                   14659:         }
                   14660:     }
                   14661: }
                   14662: 
                   14663: function propagateCheck(form,count) {
                   14664:     if (count > 0) {
1.1059    raeburn  14665:         var startelement = $startcount + ((count-1) * 7);
                   14666:         for (var j=1; j<6; j++) {
                   14667:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14668:                 var item = startelement + j; 
                   14669:                 if (form.elements[item].type == 'radio') {
                   14670:                     if (form.elements[item].checked) {
                   14671:                         containerCheck(form,count,j);
                   14672:                         break;
                   14673:                     }
1.1055    raeburn  14674:                 }
                   14675:             }
                   14676:         }
                   14677:     }
                   14678: }
                   14679: 
                   14680: numitems = $numitems
1.1056    raeburn  14681: var titles = new Array(numitems);
                   14682: var parents = new Array(numitems);
1.1055    raeburn  14683: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14684:     parents[i] = new Array;
1.1055    raeburn  14685: }
1.1059    raeburn  14686: var maintitle = '$maintitle';
1.1055    raeburn  14687: 
                   14688: START
                   14689: 
1.1056    raeburn  14690:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14691:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14692:         for (my $i=0; $i<@contents; $i ++) {
                   14693:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14694:         }
                   14695:     }
                   14696: 
1.1056    raeburn  14697:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14698:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14699:     }
                   14700: 
1.1055    raeburn  14701:     $scripttag .= <<END;
                   14702: 
                   14703: function containerCheck(form,count,offset) {
                   14704:     if (count > 0) {
1.1056    raeburn  14705:         dependencyCheck(form,count,offset);
1.1059    raeburn  14706:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14707:         form.elements[item].checked = true;
                   14708:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14709:             if (parents[count].length > 0) {
                   14710:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14711:                     containerCheck(form,parents[count][j],offset);
                   14712:                 }
                   14713:             }
                   14714:         }
                   14715:     }
                   14716: }
                   14717: 
                   14718: function dependencyCheck(form,count,offset) {
                   14719:     if (count > 0) {
1.1059    raeburn  14720:         var chosen = (offset+$startcount)+7*(count-1);
                   14721:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14722:         var currtype = form.elements[depitem].type;
                   14723:         if (form.elements[chosen].value == 'dependency') {
                   14724:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14725:             form.elements[depitem].options.length = 0;
                   14726:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14727:             for (var i=1; i<=numitems; i++) {
                   14728:                 if (i == count) {
                   14729:                     continue;
                   14730:                 }
1.1059    raeburn  14731:                 var startelement = $startcount + (i-1) * 7;
                   14732:                 for (var j=1; j<6; j++) {
                   14733:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14734:                         var item = startelement + j;
                   14735:                         if (form.elements[item].type == 'radio') {
                   14736:                             if (form.elements[item].checked) {
                   14737:                                 if (form.elements[item].value == 'display') {
                   14738:                                     var n = form.elements[depitem].options.length;
                   14739:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14740:                                 }
                   14741:                             }
                   14742:                         }
                   14743:                     }
                   14744:                 }
                   14745:             }
                   14746:         } else {
                   14747:             document.getElementById('arc_depon_'+count).style.display='none';
                   14748:             form.elements[depitem].options.length = 0;
                   14749:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14750:         }
1.1059    raeburn  14751:         titleCheck(form,count,offset);
1.1056    raeburn  14752:     }
                   14753: }
                   14754: 
                   14755: function propagateSelect(form,count,offset) {
                   14756:     if (count > 0) {
1.1065    raeburn  14757:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14758:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14759:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14760:             if (parents[count].length > 0) {
                   14761:                 for (var j=0; j<parents[count].length; j++) {
                   14762:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14763:                 }
                   14764:             }
                   14765:         }
                   14766:     }
                   14767: }
1.1056    raeburn  14768: 
                   14769: function containerSelect(form,count,offset,picked) {
                   14770:     if (count > 0) {
1.1065    raeburn  14771:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14772:         if (form.elements[item].type == 'radio') {
                   14773:             if (form.elements[item].value == 'dependency') {
                   14774:                 if (form.elements[item+1].type == 'select-one') {
                   14775:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14776:                         if (form.elements[item+1].options[i].value == picked) {
                   14777:                             form.elements[item+1].selectedIndex = i;
                   14778:                             break;
                   14779:                         }
                   14780:                     }
                   14781:                 }
                   14782:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14783:                     if (parents[count].length > 0) {
                   14784:                         for (var j=0; j<parents[count].length; j++) {
                   14785:                             containerSelect(form,parents[count][j],offset,picked);
                   14786:                         }
                   14787:                     }
                   14788:                 }
                   14789:             }
                   14790:         }
                   14791:     }
                   14792: }
                   14793: 
1.1059    raeburn  14794: function titleCheck(form,count,offset) {
                   14795:     if (count > 0) {
                   14796:         var chosen = (offset+$startcount)+7*(count-1);
                   14797:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14798:         var currtype = form.elements[depitem].type;
                   14799:         if (form.elements[chosen].value == 'display') {
                   14800:             document.getElementById('arc_title_'+count).style.display='block';
                   14801:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14802:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14803:             }
                   14804:         } else {
                   14805:             document.getElementById('arc_title_'+count).style.display='none';
                   14806:             if (currtype == 'text') { 
                   14807:                 document.getElementById('archive_title_'+count).value='';
                   14808:             }
                   14809:         }
                   14810:     }
                   14811:     return;
                   14812: }
                   14813: 
1.1055    raeburn  14814: // ]]>
                   14815: </script>
                   14816: END
                   14817:     return $scripttag;
                   14818: }
                   14819: 
                   14820: sub process_extracted_files {
1.1067    raeburn  14821:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14822:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14823:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14824:     my @ids=&Apache::lonnet::current_machine_ids();
                   14825:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14826:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14827:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14828:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14829:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14830:         $pathtocheck = "$dir_root/$destination";
                   14831:         $dir = $dir_root;
                   14832:         $ishome = 1;
                   14833:     } else {
                   14834:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14835:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14836:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14837:     }
                   14838:     my $currdir = "$dir_root/$destination";
                   14839:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14840:     if ($env{'form.folderpath'}) {
                   14841:         my @items = split('&',$env{'form.folderpath'});
                   14842:         $folders{'0'} = $items[-2];
1.1099    raeburn  14843:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14844:             $containers{'0'}='page';
                   14845:         } else {  
                   14846:             $containers{'0'}='sequence';
                   14847:         }
1.1055    raeburn  14848:     }
                   14849:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14850:     if ($numitems) {
                   14851:         for (my $i=1; $i<=$numitems; $i++) {
                   14852:             my $path = $env{'form.archive_content_'.$i};
                   14853:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14854:                 my $item = $1;
                   14855:                 $toplevelitems{$item} = $i;
                   14856:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14857:                     $is_dir{$item} = 1;
                   14858:                 }
                   14859:             }
                   14860:         }
                   14861:     }
1.1067    raeburn  14862:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14863:     if (keys(%toplevelitems) > 0) {
                   14864:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14865:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14866:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14867:     }
1.1066    raeburn  14868:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14869:     if ($numitems) {
                   14870:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14871:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14872:             my $path = $env{'form.archive_content_'.$i};
                   14873:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14874:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14875:                     if ($prefix ne '' && $path ne '') {
                   14876:                         if (-e $prefix.$path) {
1.1066    raeburn  14877:                             if ((@archdirs > 0) && 
                   14878:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14879:                                 $todeletedir{$prefix.$path} = 1;
                   14880:                             } else {
                   14881:                                 $todelete{$prefix.$path} = 1;
                   14882:                             }
1.1055    raeburn  14883:                         }
                   14884:                     }
                   14885:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14886:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14887:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14888:                     $docstitle = $env{'form.archive_title_'.$i};
                   14889:                     if ($docstitle eq '') {
                   14890:                         $docstitle = $title;
                   14891:                     }
1.1055    raeburn  14892:                     $outer = 0;
1.1056    raeburn  14893:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14894:                         if (@{$dirorder{$i}} > 0) {
                   14895:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14896:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14897:                                     $outer = $item;
                   14898:                                     last;
                   14899:                                 }
                   14900:                             }
                   14901:                         }
                   14902:                     }
                   14903:                     my ($errtext,$fatal) = 
                   14904:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14905:                                                '/'.$folders{$outer}.'.'.
                   14906:                                                $containers{$outer});
                   14907:                     next if ($fatal);
                   14908:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14909:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14910:                             $mapinner{$i} = time;
1.1055    raeburn  14911:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14912:                             $containers{$i} = 'sequence';
                   14913:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14914:                                       $folders{$i}.'.'.$containers{$i};
                   14915:                             my $newidx = &LONCAPA::map::getresidx();
                   14916:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14917:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14918:                             push(@LONCAPA::map::order,$newidx);
                   14919:                             my ($outtext,$errtext) =
                   14920:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14921:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14922:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14923:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14924:                             unless ($errtext) {
1.1294    raeburn  14925:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14926:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14927:                                             '</li>'."\n";
1.1067    raeburn  14928:                             }
1.1055    raeburn  14929:                         }
                   14930:                     } else {
                   14931:                         if ($context eq 'coursedocs') {
                   14932:                             my $newidx=&LONCAPA::map::getresidx();
                   14933:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14934:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14935:                                       $title;
1.1392    raeburn  14936:                             if (($outer !~ /\D/) &&
                   14937:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14938:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14939:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14940:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14941:                                 }
                   14942:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14943:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14944:                                 }
                   14945:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14946:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14947:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14948:                                         unless ($ishome) {
                   14949:                                             my $fetch = "$newdest{$i}/$title";
                   14950:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14951:                                             $prompttofetch{$fetch} = 1;
                   14952:                                         }
1.1292    raeburn  14953:                                     }
1.1067    raeburn  14954:                                 }
1.1294    raeburn  14955:                                 $LONCAPA::map::resources[$newidx]=
                   14956:                                     $docstitle.':'.$url.':false:normal:res';
                   14957:                                 push(@LONCAPA::map::order, $newidx);
                   14958:                                 my ($outtext,$errtext)=
                   14959:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14960:                                                             $docuname.'/'.$folders{$outer}.
                   14961:                                                             '.'.$containers{$outer},1,1);
                   14962:                                 unless ($errtext) {
                   14963:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14964:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14965:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14966:                                                    '</li>'."\n";
                   14967:                                     }
1.1067    raeburn  14968:                                 }
1.1294    raeburn  14969:                             } else {
                   14970:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14971:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14972:                             }
1.1055    raeburn  14973:                         }
                   14974:                     }
1.1086    raeburn  14975:                 }
                   14976:             } else {
1.1294    raeburn  14977:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14978:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14979:             }
                   14980:         }
                   14981:         for (my $i=1; $i<=$numitems; $i++) {
                   14982:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14983:             my $path = $env{'form.archive_content_'.$i};
                   14984:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14985:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14986:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14987:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14988:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14989:                         my ($itemidx,$fullpath,$relpath);
                   14990:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14991:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14992:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14993:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14994:                                     $itemidx = $j;
1.1056    raeburn  14995:                                 }
                   14996:                             }
1.1086    raeburn  14997:                         }
                   14998:                         if ($itemidx eq '') {
                   14999:                             $itemidx =  0;
                   15000:                         } 
                   15001:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15002:                             if ($mapinner{$referrer{$i}}) {
                   15003:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15004:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15005:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15006:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15007:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15008:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15009:                                             if (!-e $fullpath) {
                   15010:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15011:                                             }
                   15012:                                         }
1.1086    raeburn  15013:                                     } else {
                   15014:                                         last;
1.1056    raeburn  15015:                                     }
1.1086    raeburn  15016:                                 }
                   15017:                             }
                   15018:                         } elsif ($newdest{$referrer{$i}}) {
                   15019:                             $fullpath = $newdest{$referrer{$i}};
                   15020:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15021:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15022:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15023:                                     last;
                   15024:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15025:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15026:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15027:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15028:                                         if (!-e $fullpath) {
                   15029:                                             mkdir($fullpath,0755);
1.1056    raeburn  15030:                                         }
                   15031:                                     }
1.1086    raeburn  15032:                                 } else {
                   15033:                                     last;
1.1056    raeburn  15034:                                 }
1.1055    raeburn  15035:                             }
                   15036:                         }
1.1086    raeburn  15037:                         if ($fullpath ne '') {
                   15038:                             if (-e "$prefix$path") {
1.1292    raeburn  15039:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15040:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15041:                                 }
1.1086    raeburn  15042:                             }
                   15043:                             if (-e "$fullpath/$title") {
                   15044:                                 my $showpath;
                   15045:                                 if ($relpath ne '') {
                   15046:                                     $showpath = "$relpath/$title";
                   15047:                                 } else {
                   15048:                                     $showpath = "/$title";
                   15049:                                 } 
1.1294    raeburn  15050:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15051:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15052:                                            '</li>'."\n";
1.1292    raeburn  15053:                                 unless ($ishome) {
                   15054:                                     my $fetch = "$fullpath/$title";
                   15055:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15056:                                     $prompttofetch{$fetch} = 1;
                   15057:                                 }
1.1086    raeburn  15058:                             }
                   15059:                         }
1.1055    raeburn  15060:                     }
1.1086    raeburn  15061:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15062:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15063:                                     &HTML::Entities::encode($path,'<>&"'),
                   15064:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15065:                                 '<br />';
1.1055    raeburn  15066:                 }
                   15067:             } else {
1.1294    raeburn  15068:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15069:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15070:             }
                   15071:         }
                   15072:         if (keys(%todelete)) {
                   15073:             foreach my $key (keys(%todelete)) {
                   15074:                 unlink($key);
1.1066    raeburn  15075:             }
                   15076:         }
                   15077:         if (keys(%todeletedir)) {
                   15078:             foreach my $key (keys(%todeletedir)) {
                   15079:                 rmdir($key);
                   15080:             }
                   15081:         }
                   15082:         foreach my $dir (sort(keys(%is_dir))) {
                   15083:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15084:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15085:             }
                   15086:         }
1.1067    raeburn  15087:         if ($result ne '') {
                   15088:             $output .= '<ul>'."\n".
                   15089:                        $result."\n".
                   15090:                        '</ul>';
                   15091:         }
                   15092:         unless ($ishome) {
                   15093:             my $replicationfail;
                   15094:             foreach my $item (keys(%prompttofetch)) {
                   15095:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15096:                 unless ($fetchresult eq 'ok') {
                   15097:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15098:                 }
                   15099:             }
                   15100:             if ($replicationfail) {
                   15101:                 $output .= '<p class="LC_error">'.
                   15102:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15103:                            $replicationfail.
                   15104:                            '</ul></p>';
                   15105:             }
                   15106:         }
1.1055    raeburn  15107:     } else {
                   15108:         $warning = &mt('No items found in archive.');
                   15109:     }
                   15110:     if ($error) {
                   15111:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15112:                    $error.'</p>'."\n";
                   15113:     }
                   15114:     if ($warning) {
                   15115:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15116:     }
                   15117:     return $output;
                   15118: }
                   15119: 
1.1066    raeburn  15120: sub cleanup_empty_dirs {
                   15121:     my ($path) = @_;
                   15122:     if (($path ne '') && (-d $path)) {
                   15123:         if (opendir(my $dirh,$path)) {
                   15124:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15125:             my $numitems = 0;
                   15126:             foreach my $item (@dircontents) {
                   15127:                 if (-d "$path/$item") {
1.1111    raeburn  15128:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15129:                     if (-e "$path/$item") {
                   15130:                         $numitems ++;
                   15131:                     }
                   15132:                 } else {
                   15133:                     $numitems ++;
                   15134:                 }
                   15135:             }
                   15136:             if ($numitems == 0) {
                   15137:                 rmdir($path);
                   15138:             }
                   15139:             closedir($dirh);
                   15140:         }
                   15141:     }
                   15142:     return;
                   15143: }
                   15144: 
1.41      ng       15145: =pod
1.45      matthew  15146: 
1.1162    raeburn  15147: =item * &get_folder_hierarchy()
1.1068    raeburn  15148: 
                   15149: Provides hierarchy of names of folders/sub-folders containing the current
                   15150: item,
                   15151: 
                   15152: Inputs: 3
                   15153:      - $navmap - navmaps object
                   15154: 
                   15155:      - $map - url for map (either the trigger itself, or map containing
                   15156:                            the resource, which is the trigger).
                   15157: 
                   15158:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15159: 
                   15160: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15161: 
                   15162: =cut
                   15163: 
                   15164: sub get_folder_hierarchy {
                   15165:     my ($navmap,$map,$showitem) = @_;
                   15166:     my @pathitems;
                   15167:     if (ref($navmap)) {
                   15168:         my $mapres = $navmap->getResourceByUrl($map);
                   15169:         if (ref($mapres)) {
                   15170:             my $pcslist = $mapres->map_hierarchy();
                   15171:             if ($pcslist ne '') {
                   15172:                 my @pcs = split(/,/,$pcslist);
                   15173:                 foreach my $pc (@pcs) {
                   15174:                     if ($pc == 1) {
1.1129    raeburn  15175:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15176:                     } else {
                   15177:                         my $res = $navmap->getByMapPc($pc);
                   15178:                         if (ref($res)) {
                   15179:                             my $title = $res->compTitle();
                   15180:                             $title =~ s/\W+/_/g;
                   15181:                             if ($title ne '') {
                   15182:                                 push(@pathitems,$title);
                   15183:                             }
                   15184:                         }
                   15185:                     }
                   15186:                 }
                   15187:             }
1.1071    raeburn  15188:             if ($showitem) {
                   15189:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15190:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15191:                 } else {
                   15192:                     my $maptitle = $mapres->compTitle();
                   15193:                     $maptitle =~ s/\W+/_/g;
                   15194:                     if ($maptitle ne '') {
                   15195:                         push(@pathitems,$maptitle);
                   15196:                     }
1.1068    raeburn  15197:                 }
                   15198:             }
                   15199:         }
                   15200:     }
                   15201:     return @pathitems;
                   15202: }
                   15203: 
                   15204: =pod
                   15205: 
1.1015    raeburn  15206: =item * &get_turnedin_filepath()
                   15207: 
                   15208: Determines path in a user's portfolio file for storage of files uploaded
                   15209: to a specific essayresponse or dropbox item.
                   15210: 
                   15211: Inputs: 3 required + 1 optional.
                   15212: $symb is symb for resource, $uname and $udom are for current user (required).
                   15213: $caller is optional (can be "submission", if routine is called when storing
                   15214: an upoaded file when "Submit Answer" button was pressed).
                   15215: 
                   15216: Returns array containing $path and $multiresp. 
                   15217: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15218: than one file upload item.  Callers of routine should append partid as a 
                   15219: subdirectory to $path in cases where $multiresp is 1.
                   15220: 
                   15221: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15222: 
                   15223: =cut
                   15224: 
                   15225: sub get_turnedin_filepath {
                   15226:     my ($symb,$uname,$udom,$caller) = @_;
                   15227:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15228:     my $turnindir;
                   15229:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15230:     $turnindir = $userhash{'turnindir'};
                   15231:     my ($path,$multiresp);
                   15232:     if ($turnindir eq '') {
                   15233:         if ($caller eq 'submission') {
                   15234:             $turnindir = &mt('turned in');
                   15235:             $turnindir =~ s/\W+/_/g;
                   15236:             my %newhash = (
                   15237:                             'turnindir' => $turnindir,
                   15238:                           );
                   15239:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15240:         }
                   15241:     }
                   15242:     if ($turnindir ne '') {
                   15243:         $path = '/'.$turnindir.'/';
                   15244:         my ($multipart,$turnin,@pathitems);
                   15245:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15246:         if (defined($navmap)) {
                   15247:             my $mapres = $navmap->getResourceByUrl($map);
                   15248:             if (ref($mapres)) {
                   15249:                 my $pcslist = $mapres->map_hierarchy();
                   15250:                 if ($pcslist ne '') {
                   15251:                     foreach my $pc (split(/,/,$pcslist)) {
                   15252:                         my $res = $navmap->getByMapPc($pc);
                   15253:                         if (ref($res)) {
                   15254:                             my $title = $res->compTitle();
                   15255:                             $title =~ s/\W+/_/g;
                   15256:                             if ($title ne '') {
1.1149    raeburn  15257:                                 if (($pc > 1) && (length($title) > 12)) {
                   15258:                                     $title = substr($title,0,12);
                   15259:                                 }
1.1015    raeburn  15260:                                 push(@pathitems,$title);
                   15261:                             }
                   15262:                         }
                   15263:                     }
                   15264:                 }
                   15265:                 my $maptitle = $mapres->compTitle();
                   15266:                 $maptitle =~ s/\W+/_/g;
                   15267:                 if ($maptitle ne '') {
1.1149    raeburn  15268:                     if (length($maptitle) > 12) {
                   15269:                         $maptitle = substr($maptitle,0,12);
                   15270:                     }
1.1015    raeburn  15271:                     push(@pathitems,$maptitle);
                   15272:                 }
                   15273:                 unless ($env{'request.state'} eq 'construct') {
                   15274:                     my $res = $navmap->getBySymb($symb);
                   15275:                     if (ref($res)) {
                   15276:                         my $partlist = $res->parts();
                   15277:                         my $totaluploads = 0;
                   15278:                         if (ref($partlist) eq 'ARRAY') {
                   15279:                             foreach my $part (@{$partlist}) {
                   15280:                                 my @types = $res->responseType($part);
                   15281:                                 my @ids = $res->responseIds($part);
                   15282:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15283:                                     if ($types[$i] eq 'essay') {
                   15284:                                         my $partid = $part.'_'.$ids[$i];
                   15285:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15286:                                             $totaluploads ++;
                   15287:                                         }
                   15288:                                     }
                   15289:                                 }
                   15290:                             }
                   15291:                             if ($totaluploads > 1) {
                   15292:                                 $multiresp = 1;
                   15293:                             }
                   15294:                         }
                   15295:                     }
                   15296:                 }
                   15297:             } else {
                   15298:                 return;
                   15299:             }
                   15300:         } else {
                   15301:             return;
                   15302:         }
                   15303:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15304:         $restitle =~ s/\W+/_/g;
                   15305:         if ($restitle eq '') {
                   15306:             $restitle = ($resurl =~ m{/[^/]+$});
                   15307:             if ($restitle eq '') {
                   15308:                 $restitle = time;
                   15309:             }
                   15310:         }
1.1149    raeburn  15311:         if (length($restitle) > 12) {
                   15312:             $restitle = substr($restitle,0,12);
                   15313:         }
1.1015    raeburn  15314:         push(@pathitems,$restitle);
                   15315:         $path .= join('/',@pathitems);
                   15316:     }
                   15317:     return ($path,$multiresp);
                   15318: }
                   15319: 
                   15320: =pod
                   15321: 
1.464     albertel 15322: =back
1.41      ng       15323: 
1.112     bowersj2 15324: =head1 CSV Upload/Handling functions
1.38      albertel 15325: 
1.41      ng       15326: =over 4
                   15327: 
1.648     raeburn  15328: =item * &upfile_store($r)
1.41      ng       15329: 
                   15330: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15331: needs $env{'form.upfile'}
1.41      ng       15332: returns $datatoken to be put into hidden field
                   15333: 
                   15334: =cut
1.31      albertel 15335: 
                   15336: sub upfile_store {
                   15337:     my $r=shift;
1.258     albertel 15338:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15339:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15340:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15341:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15342: 
1.1299    raeburn  15343:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15344:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15345:                                      time.'_'.$$);
                   15346:     return if ($datatoken eq '');
                   15347: 
1.31      albertel 15348:     {
1.158     raeburn  15349:         my $datafile = $r->dir_config('lonDaemons').
                   15350:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15351:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15352:             print $fh $env{'form.upfile'};
1.158     raeburn  15353:             close($fh);
                   15354:         }
1.31      albertel 15355:     }
                   15356:     return $datatoken;
                   15357: }
                   15358: 
1.56      matthew  15359: =pod
                   15360: 
1.1290    raeburn  15361: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15362: 
                   15363: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15364: $datatoken is the name to assign to the temporary file.
1.258     albertel 15365: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15366: 
                   15367: =cut
1.31      albertel 15368: 
                   15369: sub load_tmp_file {
1.1290    raeburn  15370:     my ($r,$datatoken) = @_;
                   15371:     return if ($datatoken eq '');
1.31      albertel 15372:     my @studentdata=();
                   15373:     {
1.158     raeburn  15374:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15375:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15376:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15377:             @studentdata=<$fh>;
                   15378:             close($fh);
                   15379:         }
1.31      albertel 15380:     }
1.258     albertel 15381:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15382: }
                   15383: 
1.1290    raeburn  15384: sub valid_datatoken {
                   15385:     my ($datatoken) = @_;
1.1325    raeburn  15386:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15387:         return $datatoken;
                   15388:     }
                   15389:     return;
                   15390: }
                   15391: 
1.56      matthew  15392: =pod
                   15393: 
1.648     raeburn  15394: =item * &upfile_record_sep()
1.41      ng       15395: 
                   15396: Separate uploaded file into records
                   15397: returns array of records,
1.258     albertel 15398: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15399: 
                   15400: =cut
1.31      albertel 15401: 
                   15402: sub upfile_record_sep {
1.258     albertel 15403:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15404:     } else {
1.248     albertel 15405: 	my @records;
1.258     albertel 15406: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15407: 	    if ($line=~/^\s*$/) { next; }
                   15408: 	    push(@records,$line);
                   15409: 	}
                   15410: 	return @records;
1.31      albertel 15411:     }
                   15412: }
                   15413: 
1.56      matthew  15414: =pod
                   15415: 
1.648     raeburn  15416: =item * &record_sep($record)
1.41      ng       15417: 
1.258     albertel 15418: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15419: 
                   15420: =cut
                   15421: 
1.263     www      15422: sub takeleft {
                   15423:     my $index=shift;
                   15424:     return substr('0000'.$index,-4,4);
                   15425: }
                   15426: 
1.31      albertel 15427: sub record_sep {
                   15428:     my $record=shift;
                   15429:     my %components=();
1.258     albertel 15430:     if ($env{'form.upfiletype'} eq 'xml') {
                   15431:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15432:         my $i=0;
1.356     albertel 15433:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15434:             $field=~s/^(\"|\')//;
                   15435:             $field=~s/(\"|\')$//;
1.263     www      15436:             $components{&takeleft($i)}=$field;
1.31      albertel 15437:             $i++;
                   15438:         }
1.258     albertel 15439:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15440:         my $i=0;
1.356     albertel 15441:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15442:             $field=~s/^(\"|\')//;
                   15443:             $field=~s/(\"|\')$//;
1.263     www      15444:             $components{&takeleft($i)}=$field;
1.31      albertel 15445:             $i++;
                   15446:         }
                   15447:     } else {
1.561     www      15448:         my $separator=',';
1.480     banghart 15449:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15450:             $separator=';';
1.480     banghart 15451:         }
1.31      albertel 15452:         my $i=0;
1.561     www      15453: # the character we are looking for to indicate the end of a quote or a record 
                   15454:         my $looking_for=$separator;
                   15455: # do not add the characters to the fields
                   15456:         my $ignore=0;
                   15457: # we just encountered a separator (or the beginning of the record)
                   15458:         my $just_found_separator=1;
                   15459: # store the field we are working on here
                   15460:         my $field='';
                   15461: # work our way through all characters in record
                   15462:         foreach my $character ($record=~/(.)/g) {
                   15463:             if ($character eq $looking_for) {
                   15464:                if ($character ne $separator) {
                   15465: # Found the end of a quote, again looking for separator
                   15466:                   $looking_for=$separator;
                   15467:                   $ignore=1;
                   15468:                } else {
                   15469: # Found a separator, store away what we got
                   15470:                   $components{&takeleft($i)}=$field;
                   15471: 	          $i++;
                   15472:                   $just_found_separator=1;
                   15473:                   $ignore=0;
                   15474:                   $field='';
                   15475:                }
                   15476:                next;
                   15477:             }
                   15478: # single or double quotation marks after a separator indicate beginning of a quote
                   15479: # we are now looking for the end of the quote and need to ignore separators
                   15480:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15481:                $looking_for=$character;
                   15482:                next;
                   15483:             }
                   15484: # ignore would be true after we reached the end of a quote
                   15485:             if ($ignore) { next; }
                   15486:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15487:             $field.=$character;
                   15488:             $just_found_separator=0; 
1.31      albertel 15489:         }
1.561     www      15490: # catch the very last entry, since we never encountered the separator
                   15491:         $components{&takeleft($i)}=$field;
1.31      albertel 15492:     }
                   15493:     return %components;
                   15494: }
                   15495: 
1.144     matthew  15496: ######################################################
                   15497: ######################################################
                   15498: 
1.56      matthew  15499: =pod
                   15500: 
1.648     raeburn  15501: =item * &upfile_select_html()
1.41      ng       15502: 
1.144     matthew  15503: Return HTML code to select a file from the users machine and specify 
                   15504: the file type.
1.41      ng       15505: 
                   15506: =cut
                   15507: 
1.144     matthew  15508: ######################################################
                   15509: ######################################################
1.31      albertel 15510: sub upfile_select_html {
1.144     matthew  15511:     my %Types = (
                   15512:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15513:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15514:                  space => &mt('Space separated'),
                   15515:                  tab   => &mt('Tabulator separated'),
                   15516: #                 xml   => &mt('HTML/XML'),
                   15517:                  );
                   15518:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15519:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15520:     foreach my $type (sort(keys(%Types))) {
                   15521:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15522:     }
                   15523:     $Str .= "</select>\n";
                   15524:     return $Str;
1.31      albertel 15525: }
                   15526: 
1.301     albertel 15527: sub get_samples {
                   15528:     my ($records,$toget) = @_;
                   15529:     my @samples=({});
                   15530:     my $got=0;
                   15531:     foreach my $rec (@$records) {
                   15532: 	my %temp = &record_sep($rec);
                   15533: 	if (! grep(/\S/, values(%temp))) { next; }
                   15534: 	if (%temp) {
                   15535: 	    $samples[$got]=\%temp;
                   15536: 	    $got++;
                   15537: 	    if ($got == $toget) { last; }
                   15538: 	}
                   15539:     }
                   15540:     return \@samples;
                   15541: }
                   15542: 
1.144     matthew  15543: ######################################################
                   15544: ######################################################
                   15545: 
1.56      matthew  15546: =pod
                   15547: 
1.648     raeburn  15548: =item * &csv_print_samples($r,$records)
1.41      ng       15549: 
                   15550: Prints a table of sample values from each column uploaded $r is an
                   15551: Apache Request ref, $records is an arrayref from
                   15552: &Apache::loncommon::upfile_record_sep
                   15553: 
                   15554: =cut
                   15555: 
1.144     matthew  15556: ######################################################
                   15557: ######################################################
1.31      albertel 15558: sub csv_print_samples {
                   15559:     my ($r,$records) = @_;
1.662     bisitz   15560:     my $samples = &get_samples($records,5);
1.301     albertel 15561: 
1.594     raeburn  15562:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15563:               &start_data_table_header_row());
1.356     albertel 15564:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15565:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15566:     $r->print(&end_data_table_header_row());
1.301     albertel 15567:     foreach my $hash (@$samples) {
1.594     raeburn  15568: 	$r->print(&start_data_table_row());
1.356     albertel 15569: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15570: 	    $r->print('<td>');
1.356     albertel 15571: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15572: 	    $r->print('</td>');
                   15573: 	}
1.594     raeburn  15574: 	$r->print(&end_data_table_row());
1.31      albertel 15575:     }
1.594     raeburn  15576:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15577: }
                   15578: 
1.144     matthew  15579: ######################################################
                   15580: ######################################################
                   15581: 
1.56      matthew  15582: =pod
                   15583: 
1.648     raeburn  15584: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15585: 
                   15586: Prints a table to create associations between values and table columns.
1.144     matthew  15587: 
1.41      ng       15588: $r is an Apache Request ref,
                   15589: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15590: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15591: 
                   15592: =cut
                   15593: 
1.144     matthew  15594: ######################################################
                   15595: ######################################################
1.31      albertel 15596: sub csv_print_select_table {
                   15597:     my ($r,$records,$d) = @_;
1.301     albertel 15598:     my $i=0;
                   15599:     my $samples = &get_samples($records,1);
1.144     matthew  15600:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15601: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15602:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15603:               '<th>'.&mt('Column').'</th>'.
                   15604:               &end_data_table_header_row()."\n");
1.356     albertel 15605:     foreach my $array_ref (@$d) {
                   15606: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15607: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15608: 
1.875     bisitz   15609: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15610: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15611: 	$r->print('<option value="none"></option>');
1.356     albertel 15612: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15613: 	    $r->print('<option value="'.$sample.'"'.
                   15614:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15615:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15616: 	}
1.594     raeburn  15617: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15618: 	$i++;
                   15619:     }
1.594     raeburn  15620:     $r->print(&end_data_table());
1.31      albertel 15621:     $i--;
                   15622:     return $i;
                   15623: }
1.56      matthew  15624: 
1.144     matthew  15625: ######################################################
                   15626: ######################################################
                   15627: 
1.56      matthew  15628: =pod
1.31      albertel 15629: 
1.648     raeburn  15630: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15631: 
                   15632: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15633: 
                   15634: $r is an Apache Request ref,
                   15635: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15636: $d is an array of 2 element arrays (internal name, displayed name)
                   15637: 
                   15638: =cut
                   15639: 
1.144     matthew  15640: ######################################################
                   15641: ######################################################
1.31      albertel 15642: sub csv_samples_select_table {
                   15643:     my ($r,$records,$d) = @_;
                   15644:     my $i=0;
1.144     matthew  15645:     #
1.662     bisitz   15646:     my $max_samples = 5;
                   15647:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15648:     $r->print(&start_data_table().
                   15649:               &start_data_table_header_row().'<th>'.
                   15650:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15651:               &end_data_table_header_row());
1.301     albertel 15652: 
                   15653:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15654: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15655: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15656: 	foreach my $option (@$d) {
                   15657: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15658: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15659:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15660:                       $display.'</option>');
1.31      albertel 15661: 	}
                   15662: 	$r->print('</select></td><td>');
1.662     bisitz   15663: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15664: 	    if (defined($samples->[$line]{$key})) { 
                   15665: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15666: 	    }
                   15667: 	}
1.594     raeburn  15668: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15669: 	$i++;
                   15670:     }
1.594     raeburn  15671:     $r->print(&end_data_table());
1.31      albertel 15672:     $i--;
                   15673:     return($i);
1.115     matthew  15674: }
                   15675: 
1.144     matthew  15676: ######################################################
                   15677: ######################################################
                   15678: 
1.115     matthew  15679: =pod
                   15680: 
1.648     raeburn  15681: =item * &clean_excel_name($name)
1.115     matthew  15682: 
                   15683: Returns a replacement for $name which does not contain any illegal characters.
                   15684: 
                   15685: =cut
                   15686: 
1.144     matthew  15687: ######################################################
                   15688: ######################################################
1.115     matthew  15689: sub clean_excel_name {
                   15690:     my ($name) = @_;
                   15691:     $name =~ s/[:\*\?\/\\]//g;
                   15692:     if (length($name) > 31) {
                   15693:         $name = substr($name,0,31);
                   15694:     }
                   15695:     return $name;
1.25      albertel 15696: }
1.84      albertel 15697: 
1.85      albertel 15698: =pod
                   15699: 
1.648     raeburn  15700: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15701: 
                   15702: Returns either 1 or undef
                   15703: 
                   15704: 1 if the part is to be hidden, undef if it is to be shown
                   15705: 
                   15706: Arguments are:
                   15707: 
                   15708: $id the id of the part to be checked
                   15709: $symb, optional the symb of the resource to check
                   15710: $udom, optional the domain of the user to check for
                   15711: $uname, optional the username of the user to check for
                   15712: 
                   15713: =cut
1.84      albertel 15714: 
                   15715: sub check_if_partid_hidden {
                   15716:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15717:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15718: 					 $symb,$udom,$uname);
1.141     albertel 15719:     my $truth=1;
                   15720:     #if the string starts with !, then the list is the list to show not hide
                   15721:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15722:     my @hiddenlist=split(/,/,$hiddenparts);
                   15723:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15724: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15725:     }
1.141     albertel 15726:     return !$truth;
1.84      albertel 15727: }
1.127     matthew  15728: 
1.138     matthew  15729: 
                   15730: ############################################################
                   15731: ############################################################
                   15732: 
                   15733: =pod
                   15734: 
1.157     matthew  15735: =back 
                   15736: 
1.138     matthew  15737: =head1 cgi-bin script and graphing routines
                   15738: 
1.157     matthew  15739: =over 4
                   15740: 
1.648     raeburn  15741: =item * &get_cgi_id()
1.138     matthew  15742: 
                   15743: Inputs: none
                   15744: 
                   15745: Returns an id which can be used to pass environment variables
                   15746: to various cgi-bin scripts.  These environment variables will
                   15747: be removed from the users environment after a given time by
                   15748: the routine &Apache::lonnet::transfer_profile_to_env.
                   15749: 
                   15750: =cut
                   15751: 
                   15752: ############################################################
                   15753: ############################################################
1.152     albertel 15754: my $uniq=0;
1.136     matthew  15755: sub get_cgi_id {
1.154     albertel 15756:     $uniq=($uniq+1)%100000;
1.280     albertel 15757:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15758: }
                   15759: 
1.127     matthew  15760: ############################################################
                   15761: ############################################################
                   15762: 
                   15763: =pod
                   15764: 
1.648     raeburn  15765: =item * &DrawBarGraph()
1.127     matthew  15766: 
1.138     matthew  15767: Facilitates the plotting of data in a (stacked) bar graph.
                   15768: Puts plot definition data into the users environment in order for 
                   15769: graph.png to plot it.  Returns an <img> tag for the plot.
                   15770: The bars on the plot are labeled '1','2',...,'n'.
                   15771: 
                   15772: Inputs:
                   15773: 
                   15774: =over 4
                   15775: 
                   15776: =item $Title: string, the title of the plot
                   15777: 
                   15778: =item $xlabel: string, text describing the X-axis of the plot
                   15779: 
                   15780: =item $ylabel: string, text describing the Y-axis of the plot
                   15781: 
                   15782: =item $Max: scalar, the maximum Y value to use in the plot
                   15783: If $Max is < any data point, the graph will not be rendered.
                   15784: 
1.140     matthew  15785: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15786: they are plotted.  If undefined, default values will be used.
                   15787: 
1.178     matthew  15788: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15789: 
1.138     matthew  15790: =item @Values: An array of array references.  Each array reference holds data
                   15791: to be plotted in a stacked bar chart.
                   15792: 
1.239     matthew  15793: =item If the final element of @Values is a hash reference the key/value
                   15794: pairs will be added to the graph definition.
                   15795: 
1.138     matthew  15796: =back
                   15797: 
                   15798: Returns:
                   15799: 
                   15800: An <img> tag which references graph.png and the appropriate identifying
                   15801: information for the plot.
                   15802: 
1.127     matthew  15803: =cut
                   15804: 
                   15805: ############################################################
                   15806: ############################################################
1.134     matthew  15807: sub DrawBarGraph {
1.178     matthew  15808:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15809:     #
                   15810:     if (! defined($colors)) {
                   15811:         $colors = ['#33ff00', 
                   15812:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15813:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15814:                   ]; 
                   15815:     }
1.228     matthew  15816:     my $extra_settings = {};
                   15817:     if (ref($Values[-1]) eq 'HASH') {
                   15818:         $extra_settings = pop(@Values);
                   15819:     }
1.127     matthew  15820:     #
1.136     matthew  15821:     my $identifier = &get_cgi_id();
                   15822:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15823:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15824:         return '';
                   15825:     }
1.225     matthew  15826:     #
                   15827:     my @Labels;
                   15828:     if (defined($labels)) {
                   15829:         @Labels = @$labels;
                   15830:     } else {
                   15831:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15832:             push(@Labels,$i+1);
1.225     matthew  15833:         }
                   15834:     }
                   15835:     #
1.129     matthew  15836:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15837:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15838:     my %ValuesHash;
                   15839:     my $NumSets=1;
                   15840:     foreach my $array (@Values) {
                   15841:         next if (! ref($array));
1.136     matthew  15842:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15843:             join(',',@$array);
1.129     matthew  15844:     }
1.127     matthew  15845:     #
1.136     matthew  15846:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15847:     if ($NumBars < 3) {
                   15848:         $width = 120+$NumBars*32;
1.220     matthew  15849:         $xskip = 1;
1.225     matthew  15850:         $bar_width = 30;
                   15851:     } elsif ($NumBars < 5) {
                   15852:         $width = 120+$NumBars*20;
                   15853:         $xskip = 1;
                   15854:         $bar_width = 20;
1.220     matthew  15855:     } elsif ($NumBars < 10) {
1.136     matthew  15856:         $width = 120+$NumBars*15;
                   15857:         $xskip = 1;
                   15858:         $bar_width = 15;
                   15859:     } elsif ($NumBars <= 25) {
                   15860:         $width = 120+$NumBars*11;
                   15861:         $xskip = 5;
                   15862:         $bar_width = 8;
                   15863:     } elsif ($NumBars <= 50) {
                   15864:         $width = 120+$NumBars*8;
                   15865:         $xskip = 5;
                   15866:         $bar_width = 4;
                   15867:     } else {
                   15868:         $width = 120+$NumBars*8;
                   15869:         $xskip = 5;
                   15870:         $bar_width = 4;
                   15871:     }
                   15872:     #
1.137     matthew  15873:     $Max = 1 if ($Max < 1);
                   15874:     if ( int($Max) < $Max ) {
                   15875:         $Max++;
                   15876:         $Max = int($Max);
                   15877:     }
1.127     matthew  15878:     $Title  = '' if (! defined($Title));
                   15879:     $xlabel = '' if (! defined($xlabel));
                   15880:     $ylabel = '' if (! defined($ylabel));
1.369     www      15881:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15882:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15883:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15884:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15885:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15886:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15887:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15888:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15889:     $ValuesHash{$id.'.height'}   = $height;
                   15890:     $ValuesHash{$id.'.width'}    = $width;
                   15891:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15892:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15893:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15894:     #
1.228     matthew  15895:     # Deal with other parameters
                   15896:     while (my ($key,$value) = each(%$extra_settings)) {
                   15897:         $ValuesHash{$id.'.'.$key} = $value;
                   15898:     }
                   15899:     #
1.646     raeburn  15900:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15901:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15902: }
                   15903: 
                   15904: ############################################################
                   15905: ############################################################
                   15906: 
                   15907: =pod
                   15908: 
1.648     raeburn  15909: =item * &DrawXYGraph()
1.137     matthew  15910: 
1.138     matthew  15911: Facilitates the plotting of data in an XY graph.
                   15912: Puts plot definition data into the users environment in order for 
                   15913: graph.png to plot it.  Returns an <img> tag for the plot.
                   15914: 
                   15915: Inputs:
                   15916: 
                   15917: =over 4
                   15918: 
                   15919: =item $Title: string, the title of the plot
                   15920: 
                   15921: =item $xlabel: string, text describing the X-axis of the plot
                   15922: 
                   15923: =item $ylabel: string, text describing the Y-axis of the plot
                   15924: 
                   15925: =item $Max: scalar, the maximum Y value to use in the plot
                   15926: If $Max is < any data point, the graph will not be rendered.
                   15927: 
                   15928: =item $colors: Array ref containing the hex color codes for the data to be 
                   15929: plotted in.  If undefined, default values will be used.
                   15930: 
                   15931: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15932: 
                   15933: =item $Ydata: Array ref containing Array refs.  
1.185     www      15934: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15935: 
                   15936: =item %Values: hash indicating or overriding any default values which are 
                   15937: passed to graph.png.  
                   15938: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15939: 
                   15940: =back
                   15941: 
                   15942: Returns:
                   15943: 
                   15944: An <img> tag which references graph.png and the appropriate identifying
                   15945: information for the plot.
                   15946: 
1.137     matthew  15947: =cut
                   15948: 
                   15949: ############################################################
                   15950: ############################################################
                   15951: sub DrawXYGraph {
                   15952:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15953:     #
                   15954:     # Create the identifier for the graph
                   15955:     my $identifier = &get_cgi_id();
                   15956:     my $id = 'cgi.'.$identifier;
                   15957:     #
                   15958:     $Title  = '' if (! defined($Title));
                   15959:     $xlabel = '' if (! defined($xlabel));
                   15960:     $ylabel = '' if (! defined($ylabel));
                   15961:     my %ValuesHash = 
                   15962:         (
1.369     www      15963:          $id.'.title'  => &escape($Title),
                   15964:          $id.'.xlabel' => &escape($xlabel),
                   15965:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15966:          $id.'.y_max_value'=> $Max,
                   15967:          $id.'.labels'     => join(',',@$Xlabels),
                   15968:          $id.'.PlotType'   => 'XY',
                   15969:          );
                   15970:     #
                   15971:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15972:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15973:     }
                   15974:     #
                   15975:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15976:         return '';
                   15977:     }
                   15978:     my $NumSets=1;
1.138     matthew  15979:     foreach my $array (@{$Ydata}){
1.137     matthew  15980:         next if (! ref($array));
                   15981:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15982:     }
1.138     matthew  15983:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15984:     #
                   15985:     # Deal with other parameters
                   15986:     while (my ($key,$value) = each(%Values)) {
                   15987:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15988:     }
                   15989:     #
1.646     raeburn  15990:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15991:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15992: }
                   15993: 
                   15994: ############################################################
                   15995: ############################################################
                   15996: 
                   15997: =pod
                   15998: 
1.648     raeburn  15999: =item * &DrawXYYGraph()
1.138     matthew  16000: 
                   16001: Facilitates the plotting of data in an XY graph with two Y axes.
                   16002: Puts plot definition data into the users environment in order for 
                   16003: graph.png to plot it.  Returns an <img> tag for the plot.
                   16004: 
                   16005: Inputs:
                   16006: 
                   16007: =over 4
                   16008: 
                   16009: =item $Title: string, the title of the plot
                   16010: 
                   16011: =item $xlabel: string, text describing the X-axis of the plot
                   16012: 
                   16013: =item $ylabel: string, text describing the Y-axis of the plot
                   16014: 
                   16015: =item $colors: Array ref containing the hex color codes for the data to be 
                   16016: plotted in.  If undefined, default values will be used.
                   16017: 
                   16018: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16019: 
                   16020: =item $Ydata1: The first data set
                   16021: 
                   16022: =item $Min1: The minimum value of the left Y-axis
                   16023: 
                   16024: =item $Max1: The maximum value of the left Y-axis
                   16025: 
                   16026: =item $Ydata2: The second data set
                   16027: 
                   16028: =item $Min2: The minimum value of the right Y-axis
                   16029: 
                   16030: =item $Max2: The maximum value of the left Y-axis
                   16031: 
                   16032: =item %Values: hash indicating or overriding any default values which are 
                   16033: passed to graph.png.  
                   16034: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16035: 
                   16036: =back
                   16037: 
                   16038: Returns:
                   16039: 
                   16040: An <img> tag which references graph.png and the appropriate identifying
                   16041: information for the plot.
1.136     matthew  16042: 
                   16043: =cut
                   16044: 
                   16045: ############################################################
                   16046: ############################################################
1.137     matthew  16047: sub DrawXYYGraph {
                   16048:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16049:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16050:     #
                   16051:     # Create the identifier for the graph
                   16052:     my $identifier = &get_cgi_id();
                   16053:     my $id = 'cgi.'.$identifier;
                   16054:     #
                   16055:     $Title  = '' if (! defined($Title));
                   16056:     $xlabel = '' if (! defined($xlabel));
                   16057:     $ylabel = '' if (! defined($ylabel));
                   16058:     my %ValuesHash = 
                   16059:         (
1.369     www      16060:          $id.'.title'  => &escape($Title),
                   16061:          $id.'.xlabel' => &escape($xlabel),
                   16062:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16063:          $id.'.labels' => join(',',@$Xlabels),
                   16064:          $id.'.PlotType' => 'XY',
                   16065:          $id.'.NumSets' => 2,
1.137     matthew  16066:          $id.'.two_axes' => 1,
                   16067:          $id.'.y1_max_value' => $Max1,
                   16068:          $id.'.y1_min_value' => $Min1,
                   16069:          $id.'.y2_max_value' => $Max2,
                   16070:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16071:          );
                   16072:     #
1.137     matthew  16073:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16074:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16075:     }
                   16076:     #
                   16077:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16078:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16079:         return '';
                   16080:     }
                   16081:     my $NumSets=1;
1.137     matthew  16082:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16083:         next if (! ref($array));
                   16084:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16085:     }
                   16086:     #
                   16087:     # Deal with other parameters
                   16088:     while (my ($key,$value) = each(%Values)) {
                   16089:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16090:     }
                   16091:     #
1.646     raeburn  16092:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16093:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16094: }
                   16095: 
                   16096: ############################################################
                   16097: ############################################################
                   16098: 
                   16099: =pod
                   16100: 
1.157     matthew  16101: =back 
                   16102: 
1.139     matthew  16103: =head1 Statistics helper routines?  
                   16104: 
                   16105: Bad place for them but what the hell.
                   16106: 
1.157     matthew  16107: =over 4
                   16108: 
1.648     raeburn  16109: =item * &chartlink()
1.139     matthew  16110: 
                   16111: Returns a link to the chart for a specific student.  
                   16112: 
                   16113: Inputs:
                   16114: 
                   16115: =over 4
                   16116: 
                   16117: =item $linktext: The text of the link
                   16118: 
                   16119: =item $sname: The students username
                   16120: 
                   16121: =item $sdomain: The students domain
                   16122: 
                   16123: =back
                   16124: 
1.157     matthew  16125: =back
                   16126: 
1.139     matthew  16127: =cut
                   16128: 
                   16129: ############################################################
                   16130: ############################################################
                   16131: sub chartlink {
                   16132:     my ($linktext, $sname, $sdomain) = @_;
                   16133:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16134:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16135:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16136:        '">'.$linktext.'</a>';
1.153     matthew  16137: }
                   16138: 
                   16139: #######################################################
                   16140: #######################################################
                   16141: 
                   16142: =pod
                   16143: 
                   16144: =head1 Course Environment Routines
1.157     matthew  16145: 
                   16146: =over 4
1.153     matthew  16147: 
1.648     raeburn  16148: =item * &restore_course_settings()
1.153     matthew  16149: 
1.648     raeburn  16150: =item * &store_course_settings()
1.153     matthew  16151: 
                   16152: Restores/Store indicated form parameters from the course environment.
                   16153: Will not overwrite existing values of the form parameters.
                   16154: 
                   16155: Inputs: 
                   16156: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16157: 
                   16158: a hash ref describing the data to be stored.  For example:
                   16159:    
                   16160: %Save_Parameters = ('Status' => 'scalar',
                   16161:     'chartoutputmode' => 'scalar',
                   16162:     'chartoutputdata' => 'scalar',
                   16163:     'Section' => 'array',
1.373     raeburn  16164:     'Group' => 'array',
1.153     matthew  16165:     'StudentData' => 'array',
                   16166:     'Maps' => 'array');
                   16167: 
                   16168: Returns: both routines return nothing
                   16169: 
1.631     raeburn  16170: =back
                   16171: 
1.153     matthew  16172: =cut
                   16173: 
                   16174: #######################################################
                   16175: #######################################################
                   16176: sub store_course_settings {
1.496     albertel 16177:     return &store_settings($env{'request.course.id'},@_);
                   16178: }
                   16179: 
                   16180: sub store_settings {
1.153     matthew  16181:     # save to the environment
                   16182:     # appenv the same items, just to be safe
1.300     albertel 16183:     my $udom  = $env{'user.domain'};
                   16184:     my $uname = $env{'user.name'};
1.496     albertel 16185:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16186:     my %SaveHash;
                   16187:     my %AppHash;
                   16188:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16189:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16190:         my $envname = 'environment.'.$basename;
1.258     albertel 16191:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16192:             # Save this value away
                   16193:             if ($type eq 'scalar' &&
1.258     albertel 16194:                 (! exists($env{$envname}) || 
                   16195:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16196:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16197:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16198:             } elsif ($type eq 'array') {
                   16199:                 my $stored_form;
1.258     albertel 16200:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16201:                     $stored_form = join(',',
                   16202:                                         map {
1.369     www      16203:                                             &escape($_);
1.258     albertel 16204:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16205:                 } else {
                   16206:                     $stored_form = 
1.369     www      16207:                         &escape($env{'form.'.$setting});
1.153     matthew  16208:                 }
                   16209:                 # Determine if the array contents are the same.
1.258     albertel 16210:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16211:                     $SaveHash{$basename} = $stored_form;
                   16212:                     $AppHash{$envname}   = $stored_form;
                   16213:                 }
                   16214:             }
                   16215:         }
                   16216:     }
                   16217:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16218:                                           $udom,$uname);
1.153     matthew  16219:     if ($put_result !~ /^(ok|delayed)/) {
                   16220:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16221:                                  'got error:'.$put_result);
                   16222:     }
                   16223:     # Make sure these settings stick around in this session, too
1.646     raeburn  16224:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16225:     return;
                   16226: }
                   16227: 
                   16228: sub restore_course_settings {
1.499     albertel 16229:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16230: }
                   16231: 
                   16232: sub restore_settings {
                   16233:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16234:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16235:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16236:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16237:             '.'.$setting;
1.258     albertel 16238:         if (exists($env{$envname})) {
1.153     matthew  16239:             if ($type eq 'scalar') {
1.258     albertel 16240:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16241:             } elsif ($type eq 'array') {
1.258     albertel 16242:                 $env{'form.'.$setting} = [ 
1.153     matthew  16243:                                            map { 
1.369     www      16244:                                                &unescape($_); 
1.258     albertel 16245:                                            } split(',',$env{$envname})
1.153     matthew  16246:                                            ];
                   16247:             }
                   16248:         }
                   16249:     }
1.127     matthew  16250: }
                   16251: 
1.618     raeburn  16252: #######################################################
                   16253: #######################################################
                   16254: 
                   16255: =pod
                   16256: 
                   16257: =head1 Domain E-mail Routines  
                   16258: 
                   16259: =over 4
                   16260: 
1.648     raeburn  16261: =item * &build_recipient_list()
1.618     raeburn  16262: 
1.1144    raeburn  16263: Build recipient lists for following types of e-mail:
1.766     raeburn  16264: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16265: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16266: module change checking, student/employee ID conflict checks, as
                   16267: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16268: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16269: 
                   16270: Inputs:
1.619     raeburn  16271: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16272: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16273: requestsmail, updatesmail, or idconflictsmail).
                   16274: 
1.619     raeburn  16275: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16276: 
1.619     raeburn  16277: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16278: i.e., predates configuration by DC via domainprefs.pm
                   16279: 
                   16280: $requname username of requester (if mailing type is helpdeskmail)
                   16281: 
                   16282: $requdom domain of requester (if mailing type is helpdeskmail)
                   16283: 
                   16284: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16285: 
1.618     raeburn  16286: 
1.655     raeburn  16287: Returns: comma separated list of addresses to which to send e-mail.
                   16288: 
                   16289: =back
1.618     raeburn  16290: 
                   16291: =cut
                   16292: 
                   16293: ############################################################
                   16294: ############################################################
                   16295: sub build_recipient_list {
1.1297    raeburn  16296:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16297:     my @recipients;
1.1270    raeburn  16298:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16299:     my %domconfig =
1.1270    raeburn  16300:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16301:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16302:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16303:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16304:                 my @contacts = ('adminemail','supportemail');
                   16305:                 foreach my $item (@contacts) {
                   16306:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16307:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16308:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16309:                             push(@recipients,$addr);
                   16310:                         }
1.619     raeburn  16311:                     }
1.1270    raeburn  16312:                 }
                   16313:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16314:                 if ($mailing eq 'helpdeskmail') {
                   16315:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16316:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16317:                         my @ok_bccs;
                   16318:                         foreach my $bcc (@bccs) {
                   16319:                             $bcc =~ s/^\s+//g;
                   16320:                             $bcc =~ s/\s+$//g;
                   16321:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16322:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16323:                                     push(@ok_bccs,$bcc);
                   16324:                                 }
                   16325:                             }
                   16326:                         }
                   16327:                         if (@ok_bccs > 0) {
                   16328:                             $allbcc = join(', ',@ok_bccs);
                   16329:                         }
                   16330:                     }
                   16331:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16332:                 }
                   16333:             }
1.766     raeburn  16334:         } elsif ($origmail ne '') {
1.1270    raeburn  16335:             $lastresort = $origmail;
1.618     raeburn  16336:         }
1.1297    raeburn  16337:         if ($mailing eq 'helpdeskmail') {
                   16338:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16339:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16340:                 my ($inststatus,$inststatus_checked);
                   16341:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16342:                     ($env{'user.domain'} ne 'public')) {
                   16343:                     $inststatus_checked = 1;
                   16344:                     $inststatus = $env{'environment.inststatus'};
                   16345:                 }
                   16346:                 unless ($inststatus_checked) {
                   16347:                     if (($requname ne '') && ($requdom ne '')) {
                   16348:                         if (($requname =~ /^$match_username$/) &&
                   16349:                             ($requdom =~ /^$match_domain$/) &&
                   16350:                             (&Apache::lonnet::domain($requdom))) {
                   16351:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16352:                                                                       $requdom);
                   16353:                             unless ($requhome eq 'no_host') {
                   16354:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16355:                                 $inststatus = $userenv{'inststatus'};
                   16356:                                 $inststatus_checked = 1;
                   16357:                             }
                   16358:                         }
                   16359:                     }
                   16360:                 }
                   16361:                 unless ($inststatus_checked) {
                   16362:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16363:                         my %srch = (srchby     => 'email',
                   16364:                                     srchdomain => $defdom,
                   16365:                                     srchterm   => $reqemail,
                   16366:                                     srchtype   => 'exact');
                   16367:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16368:                         foreach my $uname (keys(%srch_results)) {
                   16369:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16370:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16371:                                 $inststatus_checked = 1;
                   16372:                                 last;
                   16373:                             }
                   16374:                         }
                   16375:                         unless ($inststatus_checked) {
                   16376:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16377:                             if ($dirsrchres eq 'ok') {
                   16378:                                 foreach my $uname (keys(%srch_results)) {
                   16379:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16380:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16381:                                         $inststatus_checked = 1;
                   16382:                                         last;
                   16383:                                     }
                   16384:                                 }
                   16385:                             }
                   16386:                         }
                   16387:                     }
                   16388:                 }
                   16389:                 if ($inststatus ne '') {
                   16390:                     foreach my $status (split(/\:/,$inststatus)) {
                   16391:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16392:                             my @contacts = ('adminemail','supportemail');
                   16393:                             foreach my $item (@contacts) {
                   16394:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16395:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16396:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16397:                                         push(@recipients,$addr);
                   16398:                                     }
                   16399:                                 }
                   16400:                             }
                   16401:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16402:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16403:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16404:                                 my @ok_bccs;
                   16405:                                 foreach my $bcc (@bccs) {
                   16406:                                     $bcc =~ s/^\s+//g;
                   16407:                                     $bcc =~ s/\s+$//g;
                   16408:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16409:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16410:                                             push(@ok_bccs,$bcc);
                   16411:                                         }
                   16412:                                     }
                   16413:                                 }
                   16414:                                 if (@ok_bccs > 0) {
                   16415:                                     $allbcc = join(', ',@ok_bccs);
                   16416:                                 }
                   16417:                             }
                   16418:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16419:                             last;
                   16420:                         }
                   16421:                     }
                   16422:                 }
                   16423:             }
                   16424:         }
1.619     raeburn  16425:     } elsif ($origmail ne '') {
1.1270    raeburn  16426:         $lastresort = $origmail;
                   16427:     }
1.1297    raeburn  16428:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16429:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16430:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16431:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16432:             my %what = (
                   16433:                           perlvar => 1,
                   16434:                        );
                   16435:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16436:             if ($primary) {
                   16437:                 my $gotaddr;
                   16438:                 my ($result,$returnhash) =
                   16439:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16440:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16441:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16442:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16443:                         $gotaddr = 1;
                   16444:                     }
                   16445:                 }
                   16446:                 unless ($gotaddr) {
                   16447:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16448:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16449:                     unless ($uintdom eq $intdom) {
                   16450:                         my %domconfig =
                   16451:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16452:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16453:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16454:                                 my @contacts = ('adminemail','supportemail');
                   16455:                                 foreach my $item (@contacts) {
                   16456:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16457:                                         my $addr = $domconfig{'contacts'}{$item};
                   16458:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16459:                                             push(@recipients,$addr);
                   16460:                                         }
                   16461:                                     }
                   16462:                                 }
                   16463:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16464:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16465:                                 }
                   16466:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16467:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16468:                                     my @ok_bccs;
                   16469:                                     foreach my $bcc (@bccs) {
                   16470:                                         $bcc =~ s/^\s+//g;
                   16471:                                         $bcc =~ s/\s+$//g;
                   16472:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16473:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16474:                                                 push(@ok_bccs,$bcc);
                   16475:                                             }
                   16476:                                         }
                   16477:                                     }
                   16478:                                     if (@ok_bccs > 0) {
                   16479:                                         $allbcc = join(', ',@ok_bccs);
                   16480:                                     }
                   16481:                                 }
                   16482:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16483:                             }
                   16484:                         }
                   16485:                     }
                   16486:                 }
                   16487:             }
                   16488:         }
1.618     raeburn  16489:     }
1.688     raeburn  16490:     if (defined($defmail)) {
                   16491:         if ($defmail ne '') {
                   16492:             push(@recipients,$defmail);
                   16493:         }
1.618     raeburn  16494:     }
                   16495:     if ($otheremails) {
1.619     raeburn  16496:         my @others;
                   16497:         if ($otheremails =~ /,/) {
                   16498:             @others = split(/,/,$otheremails);
1.618     raeburn  16499:         } else {
1.619     raeburn  16500:             push(@others,$otheremails);
                   16501:         }
                   16502:         foreach my $addr (@others) {
                   16503:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16504:                 push(@recipients,$addr);
                   16505:             }
1.618     raeburn  16506:         }
                   16507:     }
1.1298    raeburn  16508:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16509:         if ((!@recipients) && ($lastresort ne '')) {
                   16510:             push(@recipients,$lastresort);
                   16511:         }
                   16512:     } elsif ($lastresort ne '') {
                   16513:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16514:             push(@recipients,$lastresort);
                   16515:         }
                   16516:     }
1.1271    raeburn  16517:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16518:     if (wantarray) {
                   16519:         return ($recipientlist,$allbcc,$addtext);
                   16520:     } else {
                   16521:         return $recipientlist;
                   16522:     }
1.618     raeburn  16523: }
                   16524: 
1.127     matthew  16525: ############################################################
                   16526: ############################################################
1.154     albertel 16527: 
1.655     raeburn  16528: =pod
                   16529: 
1.1224    musolffc 16530: =over 4
                   16531: 
1.1223    musolffc 16532: =item * &mime_email()
                   16533: 
                   16534: Sends an email with a possible attachment
                   16535: 
                   16536: Inputs:
                   16537: 
                   16538: =over 4
                   16539: 
                   16540: from -              Sender's email address
                   16541: 
1.1343    raeburn  16542: replyto -           Reply-To email address
                   16543: 
1.1223    musolffc 16544: to -                Email address of recipient
                   16545: 
                   16546: subject -           Subject of email
                   16547: 
                   16548: body -              Body of email
                   16549: 
                   16550: cc_string -         Carbon copy email address
                   16551: 
                   16552: bcc -               Blind carbon copy email address
                   16553: 
                   16554: attachment_path -   Path of file to be attached
                   16555: 
                   16556: file_name -         Name of file to be attached
                   16557: 
                   16558: attachment_text -   The body of an attachment of type "TEXT"
                   16559: 
                   16560: =back
                   16561: 
                   16562: =back
                   16563: 
                   16564: =cut
                   16565: 
                   16566: ############################################################
                   16567: ############################################################
                   16568: 
                   16569: sub mime_email {
1.1343    raeburn  16570:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16571:         $file_name,$attachment_text) = @_;
                   16572:  
1.1223    musolffc 16573:     my $msg = MIME::Lite->new(
                   16574:              From    => $from,
                   16575:              To      => $to,
                   16576:              Subject => $subject,
                   16577:              Type    =>'TEXT',
                   16578:              Data    => $body,
                   16579:              );
1.1343    raeburn  16580:     if ($replyto ne '') {
                   16581:         $msg->add("Reply-To" => $replyto);
                   16582:     }
1.1223    musolffc 16583:     if ($cc_string ne '') {
                   16584:         $msg->add("Cc" => $cc_string);
                   16585:     }
                   16586:     if ($bcc ne '') {
                   16587:         $msg->add("Bcc" => $bcc);
                   16588:     }
                   16589:     $msg->attr("content-type"         => "text/plain");
                   16590:     $msg->attr("content-type.charset" => "UTF-8");
                   16591:     # Attach file if given
                   16592:     if ($attachment_path) {
                   16593:         unless ($file_name) {
                   16594:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16595:         }
                   16596:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16597:         $msg->attach(Type     => $type,
                   16598:                      Path     => $attachment_path,
                   16599:                      Filename => $file_name
                   16600:                      );
                   16601:     # Otherwise attach text if given
                   16602:     } elsif ($attachment_text) {
                   16603:         $msg->attach(Type => 'TEXT',
                   16604:                      Data => $attachment_text);
                   16605:     }
                   16606:     # Send it
                   16607:     $msg->send('sendmail');
                   16608: }
                   16609: 
                   16610: ############################################################
                   16611: ############################################################
                   16612: 
                   16613: =pod
                   16614: 
1.655     raeburn  16615: =head1 Course Catalog Routines
                   16616: 
                   16617: =over 4
                   16618: 
                   16619: =item * &gather_categories()
                   16620: 
                   16621: Converts category definitions - keys of categories hash stored in  
                   16622: coursecategories in configuration.db on the primary library server in a 
                   16623: domain - to an array.  Also generates javascript and idx hash used to 
                   16624: generate Domain Coordinator interface for editing Course Categories.
                   16625: 
                   16626: Inputs:
1.663     raeburn  16627: 
1.655     raeburn  16628: categories (reference to hash of category definitions).
1.663     raeburn  16629: 
1.655     raeburn  16630: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16631:       categories and subcategories).
1.663     raeburn  16632: 
1.655     raeburn  16633: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16634:       editing Course Categories).
1.663     raeburn  16635: 
1.655     raeburn  16636: jsarray (reference to array of categories used to create Javascript arrays for
                   16637:          Domain Coordinator interface for editing Course Categories).
                   16638: 
                   16639: Returns: nothing
                   16640: 
                   16641: Side effects: populates cats, idx and jsarray. 
                   16642: 
                   16643: =cut
                   16644: 
                   16645: sub gather_categories {
                   16646:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16647:     my %counters;
                   16648:     my $num = 0;
                   16649:     foreach my $item (keys(%{$categories})) {
                   16650:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16651:         if ($container eq '' && $depth == 0) {
                   16652:             $cats->[$depth][$categories->{$item}] = $cat;
                   16653:         } else {
                   16654:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16655:         }
                   16656:         my ($escitem,$tail) = split(/:/,$item,2);
                   16657:         if ($counters{$tail} eq '') {
                   16658:             $counters{$tail} = $num;
                   16659:             $num ++;
                   16660:         }
                   16661:         if (ref($idx) eq 'HASH') {
                   16662:             $idx->{$item} = $counters{$tail};
                   16663:         }
                   16664:         if (ref($jsarray) eq 'ARRAY') {
                   16665:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16666:         }
                   16667:     }
                   16668:     return;
                   16669: }
                   16670: 
                   16671: =pod
                   16672: 
                   16673: =item * &extract_categories()
                   16674: 
                   16675: Used to generate breadcrumb trails for course categories.
                   16676: 
                   16677: Inputs:
1.663     raeburn  16678: 
1.655     raeburn  16679: categories (reference to hash of category definitions).
1.663     raeburn  16680: 
1.655     raeburn  16681: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16682:       categories and subcategories).
1.663     raeburn  16683: 
1.655     raeburn  16684: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16685: 
1.655     raeburn  16686: allitems (reference to hash - key is category key 
                   16687:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16688: 
1.655     raeburn  16689: idx (reference to hash of counters used in Domain Coordinator interface for
                   16690:       editing Course Categories).
1.663     raeburn  16691: 
1.655     raeburn  16692: jsarray (reference to array of categories used to create Javascript arrays for
                   16693:          Domain Coordinator interface for editing Course Categories).
                   16694: 
1.665     raeburn  16695: subcats (reference to hash of arrays containing all subcategories within each 
                   16696:          category, -recursive)
                   16697: 
1.1321    raeburn  16698: maxd (reference to hash used to hold max depth for all top-level categories).
                   16699: 
1.655     raeburn  16700: Returns: nothing
                   16701: 
                   16702: Side effects: populates trails and allitems hash references.
                   16703: 
                   16704: =cut
                   16705: 
                   16706: sub extract_categories {
1.1321    raeburn  16707:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16708:     if (ref($categories) eq 'HASH') {
                   16709:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16710:         if (ref($cats->[0]) eq 'ARRAY') {
                   16711:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16712:                 my $name = $cats->[0][$i];
                   16713:                 my $item = &escape($name).'::0';
                   16714:                 my $trailstr;
                   16715:                 if ($name eq 'instcode') {
                   16716:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16717:                 } elsif ($name eq 'communities') {
                   16718:                     $trailstr = &mt('Communities');
1.1239    raeburn  16719:                 } elsif ($name eq 'placement') {
                   16720:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16721:                 } else {
                   16722:                     $trailstr = $name;
                   16723:                 }
                   16724:                 if ($allitems->{$item} eq '') {
                   16725:                     push(@{$trails},$trailstr);
                   16726:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16727:                 }
                   16728:                 my @parents = ($name);
                   16729:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16730:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16731:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16732:                         if (ref($subcats) eq 'HASH') {
                   16733:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16734:                         }
1.1321    raeburn  16735:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16736:                     }
                   16737:                 } else {
                   16738:                     if (ref($subcats) eq 'HASH') {
                   16739:                         $subcats->{$item} = [];
1.655     raeburn  16740:                     }
1.1321    raeburn  16741:                     if (ref($maxd) eq 'HASH') {
                   16742:                         $maxd->{$name} = 1;
                   16743:                     }
1.655     raeburn  16744:                 }
                   16745:             }
                   16746:         }
                   16747:     }
                   16748:     return;
                   16749: }
                   16750: 
                   16751: =pod
                   16752: 
1.1162    raeburn  16753: =item * &recurse_categories()
1.655     raeburn  16754: 
                   16755: Recursively used to generate breadcrumb trails for course categories.
                   16756: 
                   16757: Inputs:
1.663     raeburn  16758: 
1.655     raeburn  16759: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16760:       categories and subcategories).
1.663     raeburn  16761: 
1.655     raeburn  16762: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16763: 
                   16764: category (current course category, for which breadcrumb trail is being generated).
                   16765: 
                   16766: trails (reference to array of breadcrumb trails for each category).
                   16767: 
1.655     raeburn  16768: allitems (reference to hash - key is category key
                   16769:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16770: 
1.655     raeburn  16771: parents (array containing containers directories for current category, 
                   16772:          back to top level). 
                   16773: 
                   16774: Returns: nothing
                   16775: 
                   16776: Side effects: populates trails and allitems hash references
                   16777: 
                   16778: =cut
                   16779: 
                   16780: sub recurse_categories {
1.1321    raeburn  16781:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16782:     my $shallower = $depth - 1;
                   16783:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16784:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16785:             my $name = $cats->[$depth]{$category}[$k];
                   16786:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16787:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16788:             if ($allitems->{$item} eq '') {
                   16789:                 push(@{$trails},$trailstr);
                   16790:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16791:             }
                   16792:             my $deeper = $depth+1;
                   16793:             push(@{$parents},$category);
1.665     raeburn  16794:             if (ref($subcats) eq 'HASH') {
                   16795:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16796:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16797:                     my $higher;
                   16798:                     if ($j > 0) {
                   16799:                         $higher = &escape($parents->[$j]).':'.
                   16800:                                   &escape($parents->[$j-1]).':'.$j;
                   16801:                     } else {
                   16802:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16803:                     }
                   16804:                     push(@{$subcats->{$higher}},$subcat);
                   16805:                 }
                   16806:             }
                   16807:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16808:                                 $subcats,$maxd);
1.655     raeburn  16809:             pop(@{$parents});
                   16810:         }
                   16811:     } else {
                   16812:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16813:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16814:         if ($allitems->{$item} eq '') {
                   16815:             push(@{$trails},$trailstr);
                   16816:             $allitems->{$item} = scalar(@{$trails})-1;
                   16817:         }
1.1321    raeburn  16818:         if (ref($maxd) eq 'HASH') {
                   16819:             if ($depth > $maxd->{$parents->[0]}) {
                   16820:                 $maxd->{$parents->[0]} = $depth;
                   16821:             }
                   16822:         }
1.655     raeburn  16823:     }
                   16824:     return;
                   16825: }
                   16826: 
1.663     raeburn  16827: =pod
                   16828: 
1.1162    raeburn  16829: =item * &assign_categories_table()
1.663     raeburn  16830: 
                   16831: Create a datatable for display of hierarchical categories in a domain,
                   16832: with checkboxes to allow a course to be categorized. 
                   16833: 
                   16834: Inputs:
                   16835: 
                   16836: cathash - reference to hash of categories defined for the domain (from
                   16837:           configuration.db)
                   16838: 
                   16839: currcat - scalar with an & separated list of categories assigned to a course. 
                   16840: 
1.919     raeburn  16841: type    - scalar contains course type (Course or Community).
                   16842: 
1.1260    raeburn  16843: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16844:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16845: 
1.663     raeburn  16846: Returns: $output (markup to be displayed) 
                   16847: 
                   16848: =cut
                   16849: 
                   16850: sub assign_categories_table {
1.1259    raeburn  16851:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16852:     my $output;
                   16853:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16854:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16855:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16856:         $maxdepth = scalar(@cats);
                   16857:         if (@cats > 0) {
                   16858:             my $itemcount = 0;
                   16859:             if (ref($cats[0]) eq 'ARRAY') {
                   16860:                 my @currcategories;
                   16861:                 if ($currcat ne '') {
                   16862:                     @currcategories = split('&',$currcat);
                   16863:                 }
1.919     raeburn  16864:                 my $table;
1.663     raeburn  16865:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16866:                     my $parent = $cats[0][$i];
1.919     raeburn  16867:                     next if ($parent eq 'instcode');
                   16868:                     if ($type eq 'Community') {
                   16869:                         next unless ($parent eq 'communities');
1.1239    raeburn  16870:                     } elsif ($type eq 'Placement') {
                   16871:                         next unless ($parent eq 'placement');
1.919     raeburn  16872:                     } else {
1.1239    raeburn  16873:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16874:                     }
1.663     raeburn  16875:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16876:                     my $item = &escape($parent).'::0';
                   16877:                     my $checked = '';
                   16878:                     if (@currcategories > 0) {
                   16879:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16880:                             $checked = ' checked="checked"';
1.663     raeburn  16881:                         }
                   16882:                     }
1.919     raeburn  16883:                     my $parent_title = $parent;
                   16884:                     if ($parent eq 'communities') {
                   16885:                         $parent_title = &mt('Communities');
1.1239    raeburn  16886:                     } elsif ($parent eq 'placement') {
                   16887:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16888:                     }
                   16889:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16890:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16891:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16892:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16893:                     my $depth = 1;
                   16894:                     push(@path,$parent);
1.1259    raeburn  16895:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16896:                     pop(@path);
1.919     raeburn  16897:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16898:                     $itemcount ++;
                   16899:                 }
1.919     raeburn  16900:                 if ($itemcount) {
                   16901:                     $output = &Apache::loncommon::start_data_table().
                   16902:                               $table.
                   16903:                               &Apache::loncommon::end_data_table();
                   16904:                 }
1.663     raeburn  16905:             }
                   16906:         }
                   16907:     }
                   16908:     return $output;
                   16909: }
                   16910: 
                   16911: =pod
                   16912: 
1.1162    raeburn  16913: =item * &assign_category_rows()
1.663     raeburn  16914: 
                   16915: Create a datatable row for display of nested categories in a domain,
                   16916: with checkboxes to allow a course to be categorized,called recursively.
                   16917: 
                   16918: Inputs:
                   16919: 
                   16920: itemcount - track row number for alternating colors
                   16921: 
                   16922: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16923:       categories and subcategories.
                   16924: 
                   16925: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16926: 
                   16927: parent - parent of current category item
                   16928: 
                   16929: path - Array containing all categories back up through the hierarchy from the
                   16930:        current category to the top level.
                   16931: 
                   16932: currcategories - reference to array of current categories assigned to the course
                   16933: 
1.1260    raeburn  16934: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16935:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16936: 
1.663     raeburn  16937: Returns: $output (markup to be displayed).
                   16938: 
                   16939: =cut
                   16940: 
                   16941: sub assign_category_rows {
1.1259    raeburn  16942:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16943:     my ($text,$name,$item,$chgstr);
                   16944:     if (ref($cats) eq 'ARRAY') {
                   16945:         my $maxdepth = scalar(@{$cats});
                   16946:         if (ref($cats->[$depth]) eq 'HASH') {
                   16947:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16948:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16949:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16950:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16951:                 for (my $j=0; $j<$numchildren; $j++) {
                   16952:                     $name = $cats->[$depth]{$parent}[$j];
                   16953:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16954:                     my $deeper = $depth+1;
                   16955:                     my $checked = '';
                   16956:                     if (ref($currcategories) eq 'ARRAY') {
                   16957:                         if (@{$currcategories} > 0) {
                   16958:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16959:                                 $checked = ' checked="checked"';
1.663     raeburn  16960:                             }
                   16961:                         }
                   16962:                     }
1.664     raeburn  16963:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16964:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16965:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16966:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16967:                              '</td><td>';
1.663     raeburn  16968:                     if (ref($path) eq 'ARRAY') {
                   16969:                         push(@{$path},$name);
1.1259    raeburn  16970:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16971:                         pop(@{$path});
                   16972:                     }
                   16973:                     $text .= '</td></tr>';
                   16974:                 }
                   16975:                 $text .= '</table></td>';
                   16976:             }
                   16977:         }
                   16978:     }
                   16979:     return $text;
                   16980: }
                   16981: 
1.1181    raeburn  16982: =pod
                   16983: 
                   16984: =back
                   16985: 
                   16986: =cut
                   16987: 
1.655     raeburn  16988: ############################################################
                   16989: ############################################################
                   16990: 
                   16991: 
1.443     albertel 16992: sub commit_customrole {
1.1408    raeburn  16993:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16994:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16995:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16996:                      $context,$othdomby,$requester);
1.630     raeburn  16997:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16998:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16999:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17000:     if (wantarray) {
                   17001:         return ($output,$result);
                   17002:     } else {
                   17003:         return $output;
                   17004:     }
1.443     albertel 17005: }
                   17006: 
                   17007: sub commit_standardrole {
1.1408    raeburn  17008:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17009:         $othdomby,$requester) = @_;
1.1399    raeburn  17010:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17011:     if ($context eq 'auto') {
                   17012:         $linefeed = "\n";
                   17013:     } else {
                   17014:         $linefeed = "<br />\n";
                   17015:     }  
1.443     albertel 17016:     if ($three eq 'st') {
1.1399    raeburn  17017:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17018:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17019:                                       $requester);
1.541     raeburn  17020:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17021:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17022:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17023:         } else {
1.541     raeburn  17024:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17025:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17026:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17027:             if ($context eq 'auto') {
                   17028:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17029:             } else {
                   17030:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17031:                &mt('Add to classlist').': <b>ok</b>';
                   17032:             }
                   17033:             $output .= $linefeed;
1.443     albertel 17034:         }
                   17035:     } else {
                   17036:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17037:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17038:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17039:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17040:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17041:         if ($context eq 'auto') {
                   17042:             $output .= $result.$linefeed;
                   17043:         } else {
                   17044:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17045:         }
1.443     albertel 17046:     }
1.1399    raeburn  17047:     if (wantarray) {
                   17048:         return ($output,$result);
                   17049:     } else {
                   17050:         return $output;
                   17051:     }
1.443     albertel 17052: }
                   17053: 
                   17054: sub commit_studentrole {
1.1116    raeburn  17055:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17056:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17057:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17058:     if ($context eq 'auto') {
                   17059:         $linefeed = "\n";
                   17060:     } else {
                   17061:         $linefeed = '<br />'."\n";
                   17062:     }
1.443     albertel 17063:     if (defined($one) && defined($two)) {
                   17064:         my $cid=$one.'_'.$two;
                   17065:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17066:         my $secchange = 0;
                   17067:         my $expire_role_result;
                   17068:         my $modify_section_result;
1.628     raeburn  17069:         if ($oldsec ne '-1') { 
                   17070:             if ($oldsec ne $sec) {
1.443     albertel 17071:                 $secchange = 1;
1.628     raeburn  17072:                 my $now = time;
1.443     albertel 17073:                 my $uurl='/'.$cid;
                   17074:                 $uurl=~s/\_/\//g;
                   17075:                 if ($oldsec) {
                   17076:                     $uurl.='/'.$oldsec;
                   17077:                 }
1.626     raeburn  17078:                 $oldsecurl = $uurl;
1.628     raeburn  17079:                 $expire_role_result = 
1.1408    raeburn  17080:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17081:                                                 '','','',$context,$othdomby,$requester);
                   17082:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17083:                     if ($expire_role_result eq 'refused') {
                   17084:                         my @roles = ('st');
                   17085:                         my @statuses = ('previous');
                   17086:                         my @roledoms = ($one);
                   17087:                         my $withsec = 1;
                   17088:                         my %roleshash = 
                   17089:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17090:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17091:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17092:                             my ($oldstart,$oldend) = 
                   17093:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17094:                             if ($oldend > 0 && $oldend <= $now) {
                   17095:                                 $expire_role_result = 'ok';
                   17096:                             }
                   17097:                         }
                   17098:                     }
                   17099:                 }
1.443     albertel 17100:                 $result = $expire_role_result;
                   17101:             }
                   17102:         }
                   17103:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17104:             $modify_section_result = 
                   17105:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17106:                                                            undef,undef,undef,$sec,
                   17107:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17108:                                                            '',$context,$credits,'',
                   17109:                                                            $othdomby,$requester);
1.443     albertel 17110:             if ($modify_section_result =~ /^ok/) {
                   17111:                 if ($secchange == 1) {
1.628     raeburn  17112:                     if ($sec eq '') {
                   17113:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17114:                     } else {
                   17115:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17116:                     }
1.443     albertel 17117:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17118:                     if ($sec eq '') {
                   17119:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17120:                     } else {
                   17121:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17122:                     }
1.443     albertel 17123:                 } else {
1.628     raeburn  17124:                     if ($sec eq '') {
                   17125:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17126:                     } else {
                   17127:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17128:                     }
1.443     albertel 17129:                 }
                   17130:             } else {
1.1115    raeburn  17131:                 if ($secchange) { 
1.628     raeburn  17132:                     $$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;
                   17133:                 } else {
                   17134:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17135:                 }
1.443     albertel 17136:             }
                   17137:             $result = $modify_section_result;
                   17138:         } elsif ($secchange == 1) {
1.628     raeburn  17139:             if ($oldsec eq '') {
1.1103    raeburn  17140:                 $$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  17141:             } else {
                   17142:                 $$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;
                   17143:             }
1.626     raeburn  17144:             if ($expire_role_result eq 'refused') {
                   17145:                 my $newsecurl = '/'.$cid;
                   17146:                 $newsecurl =~ s/\_/\//g;
                   17147:                 if ($sec ne '') {
                   17148:                     $newsecurl.='/'.$sec;
                   17149:                 }
                   17150:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17151:                     if ($sec eq '') {
                   17152:                         $$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;
                   17153:                     } else {
                   17154:                         $$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;
                   17155:                     }
                   17156:                 }
                   17157:             }
1.443     albertel 17158:         }
                   17159:     } else {
1.626     raeburn  17160:         $$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 17161:         $result = "error: incomplete course id\n";
                   17162:     }
                   17163:     return $result;
                   17164: }
                   17165: 
1.1108    raeburn  17166: sub show_role_extent {
                   17167:     my ($scope,$context,$role) = @_;
                   17168:     $scope =~ s{^/}{};
                   17169:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17170:     push(@courseroles,'co');
                   17171:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17172:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17173:         $scope =~ s{/}{_};
                   17174:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17175:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17176:         my ($audom,$auname) = split(/\//,$scope);
                   17177:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17178:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17179:     } else {
                   17180:         $scope =~ s{/$}{};
                   17181:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17182:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17183:     }
                   17184: }
                   17185: 
1.443     albertel 17186: ############################################################
                   17187: ############################################################
                   17188: 
1.566     albertel 17189: sub check_clone {
1.578     raeburn  17190:     my ($args,$linefeed) = @_;
1.566     albertel 17191:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17192:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17193:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17194:     my $clonetitle;
                   17195:     my @clonemsg;
1.566     albertel 17196:     my $can_clone = 0;
1.944     raeburn  17197:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17198:     if ($lctype ne 'community') {
                   17199:         $lctype = 'course';
                   17200:     }
1.566     albertel 17201:     if ($clonehome eq 'no_host') {
1.944     raeburn  17202:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17203:             push(@clonemsg,({
                   17204:                               mt => 'No new community created.',
                   17205:                               args => [],
                   17206:                             },
                   17207:                             {
                   17208:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17209:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17210:                             }));
1.908     raeburn  17211:         } else {
1.1344    raeburn  17212:             push(@clonemsg,({
                   17213:                               mt => 'No new course created.',
                   17214:                               args => [],
                   17215:                             },
                   17216:                             {
                   17217:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17218:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17219:                             }));
                   17220:         }
1.566     albertel 17221:     } else {
                   17222: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17223:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17224:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17225:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17226:                 push(@clonemsg,({
                   17227:                                   mt => 'No new community created.',
                   17228:                                   args => [],
                   17229:                                 },
                   17230:                                 {
                   17231:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17232:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17233:                                 }));
                   17234:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17235:             }
                   17236:         }
1.1262    raeburn  17237: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17238:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17239: 	    $can_clone = 1;
                   17240: 	} else {
1.1221    raeburn  17241: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17242: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17243:             if ($clonehash{'cloners'} eq '') {
                   17244:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17245:                 if ($domdefs{'canclone'}) {
                   17246:                     unless ($domdefs{'canclone'} eq 'none') {
                   17247:                         if ($domdefs{'canclone'} eq 'domain') {
                   17248:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17249:                                 $can_clone = 1;
                   17250:                             }
                   17251:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17252:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17253:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17254:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17255:                                 $can_clone = 1;
                   17256:                             }
                   17257:                         }
                   17258:                     }
                   17259:                 }
1.578     raeburn  17260:             } else {
1.1221    raeburn  17261: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17262:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17263:                     $can_clone = 1;
1.1221    raeburn  17264:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17265:                     $can_clone = 1;
1.1225    raeburn  17266:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17267:                     $can_clone = 1;
1.1221    raeburn  17268:                 }
                   17269:                 unless ($can_clone) {
1.1225    raeburn  17270:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17271:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17272:                         my (%gotdomdefaults,%gotcodedefaults);
                   17273:                         foreach my $cloner (@cloners) {
                   17274:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17275:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17276:                                 my (%codedefaults,@code_order);
                   17277:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17278:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17279:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17280:                                     }
                   17281:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17282:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17283:                                     }
                   17284:                                 } else {
                   17285:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17286:                                                                             \%codedefaults,
                   17287:                                                                             \@code_order);
                   17288:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17289:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17290:                                 }
                   17291:                                 if (@code_order > 0) {
                   17292:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17293:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17294:                                                                                 $args->{'crscode'})) {
                   17295:                                         $can_clone = 1;
                   17296:                                         last;
                   17297:                                     }
                   17298:                                 }
                   17299:                             }
                   17300:                         }
                   17301:                     }
1.1225    raeburn  17302:                 }
                   17303:             }
                   17304:             unless ($can_clone) {
                   17305:                 my $ccrole = 'cc';
                   17306:                 if ($args->{'crstype'} eq 'Community') {
                   17307:                     $ccrole = 'co';
                   17308:                 }
                   17309: 	        my %roleshash =
                   17310: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17311: 					          $args->{'ccdomain'},
                   17312:                                                   'userroles',['active'],[$ccrole],
                   17313: 					          [$args->{'clonedomain'}]);
                   17314: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17315:                     $can_clone = 1;
                   17316:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17317:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17318:                     $can_clone = 1;
1.1221    raeburn  17319:                 }
                   17320:             }
                   17321:             unless ($can_clone) {
                   17322:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17323:                     push(@clonemsg,({
                   17324:                                       mt => 'No new community created.',
                   17325:                                       args => [],
                   17326:                                     },
                   17327:                                     {
                   17328:                                       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]).',
                   17329:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17330:                                     }));
1.942     raeburn  17331:                 } else {
1.1344    raeburn  17332:                     push(@clonemsg,({
                   17333:                                       mt => 'No new course created.',
                   17334:                                       args => [],
                   17335:                                     },
                   17336:                                     {
                   17337:                                       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]).',
                   17338:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17339:                                     }));
1.1221    raeburn  17340:                 }
1.566     albertel 17341: 	    }
1.578     raeburn  17342:         }
1.566     albertel 17343:     }
1.1344    raeburn  17344:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17345: }
                   17346: 
1.444     albertel 17347: sub construct_course {
1.1262    raeburn  17348:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17349:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17350:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17351:     my $linefeed =  '<br />'."\n";
                   17352:     if ($context eq 'auto') {
                   17353:         $linefeed = "\n";
                   17354:     }
1.566     albertel 17355: 
                   17356: #
                   17357: # Are we cloning?
                   17358: #
1.1344    raeburn  17359:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17360:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17361: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17362:         if (!$can_clone) {
1.1344    raeburn  17363: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17364: 	}
                   17365:     }
                   17366: 
1.444     albertel 17367: #
                   17368: # Open course
                   17369: #
1.1239    raeburn  17370:     my $showncrstype;
                   17371:     if ($args->{'crstype'} eq 'Placement') {
                   17372:         $showncrstype = 'placement test'; 
                   17373:     } else {  
                   17374:         $showncrstype = lc($args->{'crstype'});
                   17375:     }
1.444     albertel 17376:     my %cenv=();
                   17377:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17378:                                              $args->{'cdescr'},
                   17379:                                              $args->{'curl'},
                   17380:                                              $args->{'course_home'},
                   17381:                                              $args->{'nonstandard'},
                   17382:                                              $args->{'crscode'},
                   17383:                                              $args->{'ccuname'}.':'.
                   17384:                                              $args->{'ccdomain'},
1.882     raeburn  17385:                                              $args->{'crstype'},
1.1344    raeburn  17386:                                              $cnum,$context,$category,
                   17387:                                              $callercontext);
1.444     albertel 17388: 
                   17389:     # Note: The testing routines depend on this being output; see 
                   17390:     # Utils::Course. This needs to at least be output as a comment
                   17391:     # if anyone ever decides to not show this, and Utils::Course::new
                   17392:     # will need to be suitably modified.
1.1344    raeburn  17393:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17394:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17395:     } else {
                   17396:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17397:     }
1.943     raeburn  17398:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17399:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17400:     }
                   17401: 
1.444     albertel 17402: #
                   17403: # Check if created correctly
                   17404: #
1.479     albertel 17405:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17406:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17407:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17408:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17409:             $outcome .= &mt_user($user_lh,
                   17410:                             'Course creation failed, unrecognized course home server.');
                   17411:         } else {
                   17412:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17413:         }
                   17414:         $outcome .= $linefeed;
                   17415:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17416:     }
1.541     raeburn  17417:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17418: 
1.444     albertel 17419: #
1.566     albertel 17420: # Do the cloning
                   17421: #   
1.1344    raeburn  17422:     my @clonemsg;
1.566     albertel 17423:     if ($can_clone && $cloneid) {
1.1344    raeburn  17424:         push(@clonemsg,
                   17425:                       {
                   17426:                           mt => 'Created [_1] by cloning from [_2]',
                   17427:                           args => [$showncrstype,$clonetitle],
                   17428:                       });
1.566     albertel 17429: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17430: # Copy all files
1.1344    raeburn  17431:         my @info =
                   17432: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17433: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17434:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17435:                                                      $args->{'tinyurls'});
                   17436:         if (@info) {
                   17437:             push(@clonemsg,@info);
                   17438:         }
1.444     albertel 17439: # Restore URL
1.566     albertel 17440: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17441: # Restore title
1.566     albertel 17442: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17443: # Restore creation date, creator and creation context.
                   17444:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17445:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17446:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17447: # Mark as cloned
1.566     albertel 17448: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17449: # Need to clone grading mode
                   17450:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17451:         $cenv{'grading'}=$newenv{'grading'};
                   17452: # Do not clone these environment entries
                   17453:         &Apache::lonnet::del('environment',
                   17454:                   ['default_enrollment_start_date',
                   17455:                    'default_enrollment_end_date',
                   17456:                    'question.email',
                   17457:                    'policy.email',
                   17458:                    'comment.email',
                   17459:                    'pch.users.denied',
1.725     raeburn  17460:                    'plc.users.denied',
                   17461:                    'hidefromcat',
1.1121    raeburn  17462:                    'checkforpriv',
1.1355    raeburn  17463:                    'categories'],
1.638     www      17464:                    $$crsudom,$$crsunum);
1.1170    raeburn  17465:         if ($args->{'textbook'}) {
                   17466:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17467:         }
1.444     albertel 17468:     }
1.566     albertel 17469: 
1.444     albertel 17470: #
                   17471: # Set environment (will override cloned, if existing)
                   17472: #
                   17473:     my @sections = ();
                   17474:     my @xlists = ();
                   17475:     if ($args->{'crstype'}) {
                   17476:         $cenv{'type'}=$args->{'crstype'};
                   17477:     }
1.1371    raeburn  17478:     if ($args->{'lti'}) {
                   17479:         $cenv{'internal.lti'}=$args->{'lti'};
                   17480:     }
1.444     albertel 17481:     if ($args->{'crsid'}) {
                   17482:         $cenv{'courseid'}=$args->{'crsid'};
                   17483:     }
                   17484:     if ($args->{'crscode'}) {
                   17485:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17486:     }
                   17487:     if ($args->{'crsquota'} ne '') {
                   17488:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17489:     } else {
                   17490:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17491:     }
                   17492:     if ($args->{'ccuname'}) {
                   17493:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17494:                                         ':'.$args->{'ccdomain'};
                   17495:     } else {
                   17496:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17497:     }
1.1116    raeburn  17498:     if ($args->{'defaultcredits'}) {
                   17499:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17500:     }
1.444     albertel 17501:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17502:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17503:     if ($args->{'crssections'}) {
                   17504:         $cenv{'internal.sectionnums'} = '';
                   17505:         if ($args->{'crssections'} =~ m/,/) {
                   17506:             @sections = split/,/,$args->{'crssections'};
                   17507:         } else {
                   17508:             $sections[0] = $args->{'crssections'};
                   17509:         }
                   17510:         if (@sections > 0) {
                   17511:             foreach my $item (@sections) {
                   17512:                 my ($sec,$gp) = split/:/,$item;
                   17513:                 my $class = $args->{'crscode'}.$sec;
                   17514:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17515:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17516:                 if ($addcheck eq 'ok') {
                   17517:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17518:                         push(@oklcsecs,$gp);
                   17519:                     }
                   17520:                 } else {
1.1263    raeburn  17521:                     push(@badclasses,$class);
1.444     albertel 17522:                 }
                   17523:             }
                   17524:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17525:         }
                   17526:     }
                   17527: # do not hide course coordinator from staff listing, 
                   17528: # even if privileged
                   17529:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17530: # add course coordinator's domain to domains to check for privileged users
                   17531: # if different to course domain
                   17532:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17533:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17534:     }
1.444     albertel 17535: # add crosslistings
                   17536:     if ($args->{'crsxlist'}) {
                   17537:         $cenv{'internal.crosslistings'}='';
                   17538:         if ($args->{'crsxlist'} =~ m/,/) {
                   17539:             @xlists = split/,/,$args->{'crsxlist'};
                   17540:         } else {
                   17541:             $xlists[0] = $args->{'crsxlist'};
                   17542:         }
                   17543:         if (@xlists > 0) {
                   17544:             foreach my $item (@xlists) {
                   17545:                 my ($xl,$gp) = split/:/,$item;
                   17546:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17547:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17548:                 if ($addcheck eq 'ok') {
                   17549:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17550:                         push(@oklcsecs,$gp);
                   17551:                     }
                   17552:                 } else {
1.1263    raeburn  17553:                     push(@badclasses,$xl);
1.444     albertel 17554:                 }
                   17555:             }
                   17556:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17557:         }
                   17558:     }
                   17559:     if ($args->{'autoadds'}) {
                   17560:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17561:     }
                   17562:     if ($args->{'autodrops'}) {
                   17563:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17564:     }
                   17565: # check for notification of enrollment changes
                   17566:     my @notified = ();
                   17567:     if ($args->{'notify_owner'}) {
                   17568:         if ($args->{'ccuname'} ne '') {
                   17569:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17570:         }
                   17571:     }
                   17572:     if ($args->{'notify_dc'}) {
                   17573:         if ($uname ne '') { 
1.630     raeburn  17574:             push(@notified,$uname.':'.$udom);
1.444     albertel 17575:         }
                   17576:     }
                   17577:     if (@notified > 0) {
                   17578:         my $notifylist;
                   17579:         if (@notified > 1) {
                   17580:             $notifylist = join(',',@notified);
                   17581:         } else {
                   17582:             $notifylist = $notified[0];
                   17583:         }
                   17584:         $cenv{'internal.notifylist'} = $notifylist;
                   17585:     }
                   17586:     if (@badclasses > 0) {
                   17587:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17588:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17589:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17590:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17591:         );
1.1264    raeburn  17592:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17593:                            &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  17594:         if ($context eq 'auto') {
                   17595:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17596:         } else {
1.566     albertel 17597:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17598:         }
                   17599:         foreach my $item (@badclasses) {
1.541     raeburn  17600:             if ($context eq 'auto') {
1.1261    raeburn  17601:                 $outcome .= " - $item\n";
1.541     raeburn  17602:             } else {
1.1261    raeburn  17603:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17604:             }
1.1261    raeburn  17605:         }
                   17606:         if ($context eq 'auto') {
                   17607:             $outcome .= $linefeed;
                   17608:         } else {
                   17609:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17610:         } 
1.444     albertel 17611:     }
                   17612:     if ($args->{'no_end_date'}) {
                   17613:         $args->{'endaccess'} = 0;
                   17614:     }
1.1412    raeburn  17615: #  If an official course with institutional sections is created by cloning 
                   17616: #  an existing course, section-specific hiding of course totals in student's
                   17617: #  view of grades as copied from cloned course, will be checked for valid 
                   17618: #  sections.
                   17619:     if (($can_clone && $cloneid) &&
                   17620:         ($cenv{'internal.coursecode'} ne '') &&
                   17621:         ($cenv{'grading'} eq 'standard') &&
                   17622:         ($cenv{'hidetotals'} ne '') &&
                   17623:         ($cenv{'hidetotals'} ne 'all')) {
                   17624:         my @hidesecs;
                   17625:         my $deletehidetotals;
                   17626:         if (@oklcsecs) {
                   17627:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17628:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17629:                     push(@hidesecs,$sec);
                   17630:                 }
                   17631:             }
                   17632:             if (@hidesecs) {
                   17633:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17634:             } else {
                   17635:                 $deletehidetotals = 1;
                   17636:             }
                   17637:         } else {
                   17638:             $deletehidetotals = 1;
                   17639:         }
                   17640:         if ($deletehidetotals) {
                   17641:             delete($cenv{'hidetotals'});
                   17642:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17643:         }
                   17644:     }
1.444     albertel 17645:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17646:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17647:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17648:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17649:     if ($args->{'showphotos'}) {
                   17650:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17651:     }
                   17652:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17653:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17654:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17655:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17656:             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'); 
                   17657:             if ($context eq 'auto') {
                   17658:                 $outcome .= $krb_msg;
                   17659:             } else {
1.566     albertel 17660:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17661:             }
                   17662:             $outcome .= $linefeed;
1.444     albertel 17663:         }
                   17664:     }
                   17665:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17666:        if ($args->{'setpolicy'}) {
                   17667:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17668:        }
                   17669:        if ($args->{'setcontent'}) {
                   17670:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17671:        }
1.1251    raeburn  17672:        if ($args->{'setcomment'}) {
                   17673:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17674:        }
1.444     albertel 17675:     }
                   17676:     if ($args->{'reshome'}) {
                   17677: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17678: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17679:     }
                   17680: #
                   17681: # course has keyed access
                   17682: #
                   17683:     if ($args->{'setkeys'}) {
                   17684:        $cenv{'keyaccess'}='yes';
                   17685:     }
                   17686: # if specified, key authority is not course, but user
                   17687: # only active if keyaccess is yes
                   17688:     if ($args->{'keyauth'}) {
1.487     albertel 17689: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17690: 	$user = &LONCAPA::clean_username($user);
                   17691: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17692: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17693: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17694: 	}
                   17695:     }
                   17696: 
1.1166    raeburn  17697: #
1.1167    raeburn  17698: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17699: #
                   17700:     if ($args->{'uniquecode'}) {
                   17701:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17702:         if ($code) {
                   17703:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17704:             my %crsinfo =
                   17705:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17706:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17707:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17708:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17709:             } 
1.1166    raeburn  17710:             if (ref($coderef)) {
                   17711:                 $$coderef = $code;
                   17712:             }
                   17713:         }
                   17714:     }
                   17715: 
1.444     albertel 17716:     if ($args->{'disresdis'}) {
                   17717:         $cenv{'pch.roles.denied'}='st';
                   17718:     }
                   17719:     if ($args->{'disablechat'}) {
                   17720:         $cenv{'plc.roles.denied'}='st';
                   17721:     }
                   17722: 
                   17723:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17724:     # course
                   17725:     $cenv{'course.helper.not.run'} = 1;
                   17726:     #
                   17727:     # Use new Randomseed
                   17728:     #
                   17729:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17730:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17731:     #
                   17732:     # The encryption code and receipt prefix for this course
                   17733:     #
                   17734:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17735:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17736:     #
                   17737:     # By default, use standard grading
                   17738:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17739: 
1.541     raeburn  17740:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17741:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17742: #
                   17743: # Open all assignments
                   17744: #
                   17745:     if ($args->{'openall'}) {
1.1341    raeburn  17746:        my $opendate = time;
                   17747:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17748:            $opendate = $args->{'openallfrom'};
                   17749:        }
1.444     albertel 17750:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17751:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17752:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17753:        $outcome .= &mt('All assignments open starting [_1]',
                   17754:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17755:                    &Apache::lonnet::cput
                   17756:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17757:    }
                   17758: #
                   17759: # Set first page
                   17760: #
                   17761:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17762: 	    || ($cloneid)) {
                   17763: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17764: 
                   17765: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17766:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17767: 
1.444     albertel 17768:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17769:         my $title; my $url;
                   17770:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17771: 	    $title=&mt('Syllabus');
1.444     albertel 17772:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17773:         } else {
1.963     raeburn  17774:             $title=&mt('Table of Contents');
1.444     albertel 17775:             $url='/adm/navmaps';
                   17776:         }
1.445     albertel 17777: 
                   17778:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17779: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17780: 
                   17781: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17782:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17783:     }
1.566     albertel 17784: 
1.1237    raeburn  17785: # 
                   17786: # Set params for Placement Tests
                   17787: #
1.1239    raeburn  17788:     if ($args->{'crstype'} eq 'Placement') {
                   17789:        my %storecontent; 
                   17790:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17791:        my %defaults = (
                   17792:                         buttonshide   => { value => 'yes',
                   17793:                                            type => 'string_yesno',},
                   17794:                         type          => { value => 'randomizetry',
                   17795:                                            type  => 'string_questiontype',},
                   17796:                         maxtries      => { value => 1,
                   17797:                                            type => 'int_pos',},
                   17798:                         problemstatus => { value => 'no',
                   17799:                                            type  => 'string_problemstatus',},
                   17800:                       );
                   17801:        foreach my $key (keys(%defaults)) {
                   17802:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17803:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17804:        }
1.1237    raeburn  17805:        &Apache::lonnet::cput
                   17806:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17807:     }
                   17808: 
1.1344    raeburn  17809:     return (1,$outcome,\@clonemsg);
1.444     albertel 17810: }
                   17811: 
1.1166    raeburn  17812: sub make_unique_code {
                   17813:     my ($cdom,$cnum) = @_;
                   17814:     # get lock on uniquecodes db
                   17815:     my $lockhash = {
                   17816:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17817:                                                   ':'.$env{'user.domain'},
                   17818:                    };
                   17819:     my $tries = 0;
                   17820:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17821:     my ($code,$error);
                   17822:   
                   17823:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17824:         $tries ++;
                   17825:         sleep 1;
                   17826:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17827:     }
                   17828:     if ($gotlock eq 'ok') {
                   17829:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17830:         my $gotcode;
                   17831:         my $attempts = 0;
                   17832:         while ((!$gotcode) && ($attempts < 100)) {
                   17833:             $code = &generate_code();
                   17834:             if (!exists($currcodes{$code})) {
                   17835:                 $gotcode = 1;
                   17836:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17837:                     $error = 'nostore';
                   17838:                 }
                   17839:             }
                   17840:             $attempts ++;
                   17841:         }
                   17842:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17843:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17844:     } else {
                   17845:         $error = 'nolock';
                   17846:     }
                   17847:     return ($code,$error);
                   17848: }
                   17849: 
                   17850: sub generate_code {
                   17851:     my $code;
                   17852:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17853:     for (my $i=0; $i<6; $i++) {
                   17854:         my $lettnum = int (rand 2);
                   17855:         my $item = '';
                   17856:         if ($lettnum) {
                   17857:             $item = $letts[int( rand(18) )];
                   17858:         } else {
                   17859:             $item = 1+int( rand(8) );
                   17860:         }
                   17861:         $code .= $item;
                   17862:     }
                   17863:     return $code;
                   17864: }
                   17865: 
1.444     albertel 17866: ############################################################
                   17867: ############################################################
                   17868: 
1.1237    raeburn  17869: # Community, Course and Placement Test
1.378     raeburn  17870: sub course_type {
                   17871:     my ($cid) = @_;
                   17872:     if (!defined($cid)) {
                   17873:         $cid = $env{'request.course.id'};
                   17874:     }
1.404     albertel 17875:     if (defined($env{'course.'.$cid.'.type'})) {
                   17876:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17877:     } else {
                   17878:         return 'Course';
1.377     raeburn  17879:     }
                   17880: }
1.156     albertel 17881: 
1.406     raeburn  17882: sub group_term {
                   17883:     my $crstype = &course_type();
                   17884:     my %names = (
                   17885:                   'Course' => 'group',
1.865     raeburn  17886:                   'Community' => 'group',
1.1237    raeburn  17887:                   'Placement' => 'group',
1.406     raeburn  17888:                 );
                   17889:     return $names{$crstype};
                   17890: }
                   17891: 
1.902     raeburn  17892: sub course_types {
1.1310    raeburn  17893:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17894:     my %typename = (
                   17895:                          official   => 'Official course',
                   17896:                          unofficial => 'Unofficial course',
                   17897:                          community  => 'Community',
1.1165    raeburn  17898:                          textbook   => 'Textbook course',
1.1237    raeburn  17899:                          placement  => 'Placement test',
1.1310    raeburn  17900:                          lti        => 'LTI provider',
1.902     raeburn  17901:                    );
                   17902:     return (\@types,\%typename);
                   17903: }
                   17904: 
1.156     albertel 17905: sub icon {
                   17906:     my ($file)=@_;
1.505     albertel 17907:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17908:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17909:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17910:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17911: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17912: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17913: 	            $curfext.".gif") {
                   17914: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17915: 		$curfext.".gif";
                   17916: 	}
                   17917:     }
1.249     albertel 17918:     return &lonhttpdurl($iconname);
1.154     albertel 17919: } 
1.84      albertel 17920: 
1.575     albertel 17921: sub lonhttpdurl {
1.692     www      17922: #
                   17923: # Had been used for "small fry" static images on separate port 8080.
                   17924: # Modify here if lightweight http functionality desired again.
                   17925: # Currently eliminated due to increasing firewall issues.
                   17926: #
1.575     albertel 17927:     my ($url)=@_;
1.692     www      17928:     return $url;
1.215     albertel 17929: }
                   17930: 
1.213     albertel 17931: sub connection_aborted {
                   17932:     my ($r)=@_;
                   17933:     $r->print(" ");$r->rflush();
                   17934:     my $c = $r->connection;
                   17935:     return $c->aborted();
                   17936: }
                   17937: 
1.221     foxr     17938: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17939: #    strings as 'strings'.
                   17940: sub escape_single {
1.221     foxr     17941:     my ($input) = @_;
1.223     albertel 17942:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17943:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17944:     return $input;
                   17945: }
1.223     albertel 17946: 
1.222     foxr     17947: #  Same as escape_single, but escape's "'s  This 
                   17948: #  can be used for  "strings"
                   17949: sub escape_double {
                   17950:     my ($input) = @_;
                   17951:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17952:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17953:     return $input;
                   17954: }
1.223     albertel 17955:  
1.222     foxr     17956: #   Escapes the last element of a full URL.
                   17957: sub escape_url {
                   17958:     my ($url)   = @_;
1.238     raeburn  17959:     my @urlslices = split(/\//, $url,-1);
1.369     www      17960:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17961:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17962: }
1.462     albertel 17963: 
1.820     raeburn  17964: sub compare_arrays {
                   17965:     my ($arrayref1,$arrayref2) = @_;
                   17966:     my (@difference,%count);
                   17967:     @difference = ();
                   17968:     %count = ();
                   17969:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17970:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17971:         foreach my $element (keys(%count)) {
                   17972:             if ($count{$element} == 1) {
                   17973:                 push(@difference,$element);
                   17974:             }
                   17975:         }
                   17976:     }
                   17977:     return @difference;
                   17978: }
                   17979: 
1.1322    raeburn  17980: sub lon_status_items {
                   17981:     my %defaults = (
                   17982:                      E         => 100,
                   17983:                      W         => 4,
                   17984:                      N         => 1,
1.1324    raeburn  17985:                      U         => 5,
1.1322    raeburn  17986:                      threshold => 200,
                   17987:                      sysmail   => 2500,
                   17988:                    );
                   17989:     my %names = (
                   17990:                    E => 'Errors',
                   17991:                    W => 'Warnings',
                   17992:                    N => 'Notices',
1.1324    raeburn  17993:                    U => 'Unsent',
1.1322    raeburn  17994:                 );
                   17995:     return (\%defaults,\%names);
                   17996: }
                   17997: 
1.817     bisitz   17998: # -------------------------------------------------------- Initialize user login
1.462     albertel 17999: sub init_user_environment {
1.463     albertel 18000:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18001:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18002: 
                   18003:     my $public=($username eq 'public' && $domain eq 'public');
                   18004: 
1.1415    raeburn  18005:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18006:         $coauthorenv);
1.462     albertel 18007:     my $now=time;
                   18008: 
                   18009:     if ($public) {
                   18010: 	my $max_public=100;
                   18011: 	my $oldest;
                   18012: 	my $oldest_time=0;
                   18013: 	for(my $next=1;$next<=$max_public;$next++) {
                   18014: 	    if (-e $lonids."/publicuser_$next.id") {
                   18015: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18016: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18017: 		    $oldest_time=$mtime;
                   18018: 		    $oldest=$next;
                   18019: 		}
                   18020: 	    } else {
                   18021: 		$cookie="publicuser_$next";
                   18022: 		last;
                   18023: 	    }
                   18024: 	}
                   18025: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18026:     } else {
1.1275    raeburn  18027: 	# See if old ID present, if so, remove if this isn't a robot,
                   18028: 	# killing any existing non-robot sessions
1.463     albertel 18029: 	if (!$args->{'robot'}) {
                   18030: 	    opendir(DIR,$lonids);
                   18031: 	    while ($filename=readdir(DIR)) {
                   18032: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18033:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18034:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18035:                         my $linkedfile;
1.1320    raeburn  18036:                         if (exists($oldenv{'user.linkedenv'})) {
                   18037:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18038:                         }
1.1320    raeburn  18039:                         untie(%oldenv);
                   18040:                         if (unlink("$lonids/$filename")) {
                   18041:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18042:                                 if (-l "$lonids/$linkedfile.id") {
                   18043:                                     unlink("$lonids/$linkedfile.id");
                   18044:                                 }
1.1295    raeburn  18045:                             }
                   18046:                         }
                   18047:                     } else {
                   18048:                         unlink($lonids.'/'.$filename);
                   18049:                     }
1.463     albertel 18050: 		}
1.462     albertel 18051: 	    }
1.463     albertel 18052: 	    closedir(DIR);
1.1204    raeburn  18053: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18054:             my $namespace = 'nohist_courseeditor';
                   18055:             my $lockingkey = 'paste'."\0".'locked_num';
                   18056:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18057:                                                 $domain,$username);
                   18058:             if (exists($lockhash{$lockingkey})) {
                   18059:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18060:                 unless ($delresult eq 'ok') {
                   18061:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18062:                 }
                   18063:             }
1.462     albertel 18064: 	}
                   18065: # Give them a new cookie
1.463     albertel 18066: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18067: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18068: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18069:     
                   18070: # Initialize roles
                   18071: 
1.1414    raeburn  18072: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18073:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18074:     }
                   18075: # ------------------------------------ Check browser type and MathML capability
                   18076: 
1.1194    raeburn  18077:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18078:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18079: 
                   18080: # ------------------------------------------------------------- Get environment
                   18081: 
                   18082:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18083:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18084:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18085: 	undef(%userenv);
                   18086:     }
                   18087:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18088: 	$form->{'interface'}=$userenv{'interface'};
                   18089:     }
                   18090:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18091: 
                   18092: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18093:     foreach my $option ('interface','localpath','localres') {
                   18094:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18095:     }
                   18096: # --------------------------------------------------------- Write first profile
                   18097: 
                   18098:     {
1.1350    raeburn  18099:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18100: 	my %initial_env = 
                   18101: 	    ("user.name"          => $username,
                   18102: 	     "user.domain"        => $domain,
                   18103: 	     "user.home"          => $authhost,
                   18104: 	     "browser.type"       => $clientbrowser,
                   18105: 	     "browser.version"    => $clientversion,
                   18106: 	     "browser.mathml"     => $clientmathml,
                   18107: 	     "browser.unicode"    => $clientunicode,
                   18108: 	     "browser.os"         => $clientos,
1.1137    raeburn  18109:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18110:              "browser.info"       => $clientinfo,
1.1194    raeburn  18111:              "browser.osversion"  => $clientosversion,
1.462     albertel 18112: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18113: 	     "request.course.fn"  => '',
                   18114: 	     "request.course.uri" => '',
                   18115: 	     "request.course.sec" => '',
                   18116: 	     "request.role"       => 'cm',
                   18117: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18118: 	     "request.host"       => $ip,);
1.462     albertel 18119: 
                   18120:         if ($form->{'localpath'}) {
                   18121: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18122: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18123:         }
                   18124: 	
                   18125: 	if ($form->{'interface'}) {
                   18126: 	    $form->{'interface'}=~s/\W//gs;
                   18127: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18128: 	    $env{'browser.interface'}=$form->{'interface'};
                   18129: 	}
                   18130: 
1.1157    raeburn  18131:         if ($form->{'iptoken'}) {
                   18132:             my $lonhost = $r->dir_config('lonHostID');
                   18133:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18134:             $env{'user.noloadbalance'} = $lonhost;
                   18135:         }
                   18136: 
1.1268    raeburn  18137:         if ($form->{'noloadbalance'}) {
                   18138:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18139:             my $hosthere = $form->{'noloadbalance'};
                   18140:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18141:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18142:                 $env{'user.noloadbalance'} = $hosthere;
                   18143:             }
                   18144:         }
                   18145: 
1.1016    raeburn  18146:         unless ($domain eq 'public') {
1.1273    raeburn  18147:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18148:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18149: 
1.1414    raeburn  18150:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18151:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18152:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18153:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18154:             }
1.980     raeburn  18155: 
1.1311    raeburn  18156:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18157:                 $userenv{'canrequest.'.$crstype} =
                   18158:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18159:                                                       'reload','requestcourses',
                   18160:                                                       \%userenv,\%domdef,\%is_adv);
                   18161:             }
1.724     raeburn  18162: 
1.1418    raeburn  18163:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18164:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18165:                 if ($userenv{'authoreditors'}) {
                   18166:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18167:                 } elsif ($domdef{'editors'} ne '') {
                   18168:                     $userenv{'editors'} = $domdef{'editors'};
                   18169:                 } else {
                   18170:                     $userenv{'editors'} = 'edit,xml';
                   18171:                 }
1.1431    raeburn  18172:                 if ($userenv{'authorarchive'}) {
                   18173:                     $userenv{'canarchive'} = 1;
                   18174:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18175:                          ($domdef{'archive'})) {
                   18176:                     $userenv{'canarchive'} = 1;
                   18177:                 }
1.1418    raeburn  18178:             }
                   18179: 
1.1273    raeburn  18180:             $userenv{'canrequest.author'} =
                   18181:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18182:                                                   'reload','requestauthor',
1.980     raeburn  18183:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18184:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18185:                                                  $domain,$username);
                   18186:             my $reqstatus = $reqauthor{'author_status'};
                   18187:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18188:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18189:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18190:                                                       $reqauthor{'author'}{'timestamp'};
                   18191:                 }
1.1092    raeburn  18192:             }
1.1287    raeburn  18193:             my ($types,$typename) = &course_types();
                   18194:             if (ref($types) eq 'ARRAY') {
                   18195:                 my @options = ('approval','validate','autolimit');
                   18196:                 my $optregex = join('|',@options);
                   18197:                 my (%willtrust,%trustchecked);
                   18198:                 foreach my $type (@{$types}) {
                   18199:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18200:                     if ($dom_str ne '') {
                   18201:                         my $updatedstr = '';
                   18202:                         my @possdomains = split(',',$dom_str);
                   18203:                         foreach my $entry (@possdomains) {
                   18204:                             my ($extdom,$extopt) = split(':',$entry);
                   18205:                             unless ($trustchecked{$extdom}) {
                   18206:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18207:                                 $trustchecked{$extdom} = 1;
                   18208:                             }
                   18209:                             if ($willtrust{$extdom}) {
                   18210:                                 $updatedstr .= $entry.',';
                   18211:                             }
                   18212:                         }
                   18213:                         $updatedstr =~ s/,$//;
                   18214:                         if ($updatedstr) {
                   18215:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18216:                         } else {
                   18217:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18218:                         }
                   18219:                     }
                   18220:                 }
                   18221:             }
1.1092    raeburn  18222:         }
1.462     albertel 18223: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18224: 
1.462     albertel 18225: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18226: 		 &GDBM_WRCREAT(),0640)) {
                   18227: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18228: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18229: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18230:             if (ref($firstaccenv) eq 'HASH') {
                   18231:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18232:             }
                   18233:             if (ref($timerintenv) eq 'HASH') {
                   18234:                 &_add_to_env(\%disk_env,$timerintenv);
                   18235:             }
1.1414    raeburn  18236:             if (ref($coauthorenv) eq 'HASH') {
                   18237:                 if (keys(%{$coauthorenv})) {
                   18238:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18239:                 }
                   18240:             }
1.463     albertel 18241: 	    if (ref($args->{'extra_env'})) {
                   18242: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18243: 	    }
1.462     albertel 18244: 	    untie(%disk_env);
                   18245: 	} else {
1.705     tempelho 18246: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18247: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18248: 	    return 'error: '.$!;
                   18249: 	}
                   18250:     }
                   18251:     $env{'request.role'}='cm';
                   18252:     $env{'request.role.adv'}=$env{'user.adv'};
                   18253:     $env{'browser.type'}=$clientbrowser;
                   18254: 
                   18255:     return $cookie;
                   18256: 
                   18257: }
                   18258: 
                   18259: sub _add_to_env {
                   18260:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18261:     if (ref($env_data) eq 'HASH') {
                   18262:         while (my ($key,$value) = each(%$env_data)) {
                   18263: 	    $idf->{$prefix.$key} = $value;
                   18264: 	    $env{$prefix.$key}   = $value;
                   18265:         }
1.462     albertel 18266:     }
                   18267: }
                   18268: 
1.685     tempelho 18269: # --- Get the symbolic name of a problem and the url
                   18270: sub get_symb {
                   18271:     my ($request,$silent) = @_;
1.726     raeburn  18272:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18273:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18274:     if ($symb eq '') {
                   18275:         if (!$silent) {
1.1071    raeburn  18276:             if (ref($request)) { 
                   18277:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18278:             }
1.685     tempelho 18279:             return ();
                   18280:         }
                   18281:     }
                   18282:     &Apache::lonenc::check_decrypt(\$symb);
                   18283:     return ($symb);
                   18284: }
                   18285: 
                   18286: # --------------------------------------------------------------Get annotation
                   18287: 
                   18288: sub get_annotation {
                   18289:     my ($symb,$enc) = @_;
                   18290: 
                   18291:     my $key = $symb;
                   18292:     if (!$enc) {
                   18293:         $key =
                   18294:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18295:     }
                   18296:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18297:     return $annotation{$key};
                   18298: }
                   18299: 
                   18300: sub clean_symb {
1.731     raeburn  18301:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18302: 
                   18303:     &Apache::lonenc::check_decrypt(\$symb);
                   18304:     my $enc = $env{'request.enc'};
1.731     raeburn  18305:     if ($delete_enc) {
1.730     raeburn  18306:         delete($env{'request.enc'});
                   18307:     }
1.685     tempelho 18308: 
                   18309:     return ($symb,$enc);
                   18310: }
1.462     albertel 18311: 
1.1181    raeburn  18312: ############################################################
                   18313: ############################################################
                   18314: 
                   18315: =pod
                   18316: 
                   18317: =head1 Routines for building display used to search for courses
                   18318: 
                   18319: 
                   18320: =over 4
                   18321: 
                   18322: =item * &build_filters()
                   18323: 
                   18324: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18325: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18326: and quotacheck.pl
                   18327: 
1.1181    raeburn  18328: 
                   18329: Inputs:
                   18330: 
                   18331: filterlist - anonymous array of fields to include as potential filters 
                   18332: 
                   18333: crstype - course type
                   18334: 
                   18335: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18336:               to pop-open a course selector (will contain "extra element"). 
                   18337: 
                   18338: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18339: 
                   18340: filter - anonymous hash of criteria and their values
                   18341: 
                   18342: action - form action
                   18343: 
                   18344: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18345: 
1.1182    raeburn  18346: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18347: 
                   18348: cloneruname - username of owner of new course who wants to clone
                   18349: 
                   18350: clonerudom - domain of owner of new course who wants to clone
                   18351: 
                   18352: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18353: 
                   18354: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18355: 
                   18356: codedom - domain
                   18357: 
                   18358: formname - value of form element named "form". 
                   18359: 
                   18360: fixeddom - domain, if fixed.
                   18361: 
                   18362: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18363: 
                   18364: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18365: 
                   18366: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18367: 
                   18368: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18369: 
                   18370: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18371: 
                   18372: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18373: 
                   18374: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18375: 
1.1182    raeburn  18376: 
1.1181    raeburn  18377: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18378: 
1.1182    raeburn  18379: 
1.1181    raeburn  18380: Side Effects: None
                   18381: 
                   18382: =cut
                   18383: 
                   18384: # ---------------------------------------------- search for courses based on last activity etc.
                   18385: 
                   18386: sub build_filters {
                   18387:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18388:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18389:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18390:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18391:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18392:     my ($list,$jscript);
1.1181    raeburn  18393:     my $onchange = 'javascript:updateFilters(this)';
                   18394:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18395:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18396:         $typeselectform,$instcodetitle);
                   18397:     if ($formname eq '') {
                   18398:         $formname = $caller;
                   18399:     }
                   18400:     foreach my $item (@{$filterlist}) {
                   18401:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18402:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18403:             if ($item eq 'domainfilter') {
                   18404:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18405:             } elsif ($item eq 'coursefilter') {
                   18406:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18407:             } elsif ($item eq 'ownerfilter') {
                   18408:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18409:             } elsif ($item eq 'ownerdomfilter') {
                   18410:                 $filter->{'ownerdomfilter'} =
                   18411:                     &LONCAPA::clean_domain($filter->{$item});
                   18412:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18413:                                                        'ownerdomfilter',1);
                   18414:             } elsif ($item eq 'personfilter') {
                   18415:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18416:             } elsif ($item eq 'persondomfilter') {
                   18417:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18418:                                                         'persondomfilter',1);
                   18419:             } else {
                   18420:                 $filter->{$item} =~ s/\W//g;
                   18421:             }
                   18422:             if (!$filter->{$item}) {
                   18423:                 $filter->{$item} = '';
                   18424:             }
                   18425:         }
                   18426:         if ($item eq 'domainfilter') {
                   18427:             my $allow_blank = 1;
                   18428:             if ($formname eq 'portform') {
                   18429:                 $allow_blank=0;
                   18430:             } elsif ($formname eq 'studentform') {
                   18431:                 $allow_blank=0;
                   18432:             }
                   18433:             if ($fixeddom) {
                   18434:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18435:                                     ' value="'.$codedom.'" />'.
                   18436:                                     &Apache::lonnet::domain($codedom,'description');
                   18437:             } else {
                   18438:                 $domainselectform = &select_dom_form($filter->{$item},
                   18439:                                                      'domainfilter',
                   18440:                                                       $allow_blank,'',$onchange);
                   18441:             }
                   18442:         } else {
                   18443:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18444:         }
                   18445:     }
                   18446: 
                   18447:     # last course activity filter and selection
                   18448:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18449: 
                   18450:     # course created filter and selection
                   18451:     if (exists($filter->{'createdfilter'})) {
                   18452:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18453:     }
                   18454: 
1.1239    raeburn  18455:     my $prefix = $crstype;
                   18456:     if ($crstype eq 'Placement') {
                   18457:         $prefix = 'Placement Test'
                   18458:     }
1.1181    raeburn  18459:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18460:                 'cac' => "$prefix Activity",
                   18461:                 'ccr' => "$prefix Created",
                   18462:                 'cde' => "$prefix Title",
                   18463:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18464:                 'ins' => 'Institutional Code',
                   18465:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18466:                 'cow' => "$prefix Owner/Co-owner",
                   18467:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18468:                 'cog' => 'Type',
                   18469:              );
                   18470: 
                   18471:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18472:         my $typeval = 'Course';
                   18473:         if ($crstype eq 'Community') {
                   18474:             $typeval = 'Community';
1.1239    raeburn  18475:         } elsif ($crstype eq 'Placement') {
                   18476:             $typeval = 'Placement';
1.1181    raeburn  18477:         }
                   18478:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18479:     } else {
                   18480:         $typeselectform =  '<select name="type" size="1"';
                   18481:         if ($onchange) {
                   18482:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18483:         }
                   18484:         $typeselectform .= '>'."\n";
1.1237    raeburn  18485:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18486:             my $shown;
                   18487:             if ($posstype eq 'Placement') {
                   18488:                 $shown = &mt('Placement Test');
                   18489:             } else {
                   18490:                 $shown = &mt($posstype);
                   18491:             }
1.1181    raeburn  18492:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18493:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18494:         }
                   18495:         $typeselectform.="</select>";
                   18496:     }
                   18497: 
                   18498:     my ($cloneableonlyform,$cloneabletitle);
                   18499:     if (exists($filter->{'cloneableonly'})) {
                   18500:         my $cloneableon = '';
                   18501:         my $cloneableoff = ' checked="checked"';
                   18502:         if ($filter->{'cloneableonly'}) {
                   18503:             $cloneableon = $cloneableoff;
                   18504:             $cloneableoff = '';
                   18505:         }
                   18506:         $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>';
                   18507:         if ($formname eq 'ccrs') {
1.1187    bisitz   18508:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18509:         } else {
                   18510:             $cloneabletitle = &mt('Cloneable by you');
                   18511:         }
                   18512:     }
                   18513:     my $officialjs;
                   18514:     if ($crstype eq 'Course') {
                   18515:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18516: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18517: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18518:             if ($codedom) { 
1.1181    raeburn  18519:                 $officialjs = 1;
                   18520:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18521:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18522:                                                                   $officialjs,$codetitlesref);
                   18523:                 if ($jscript) {
1.1182    raeburn  18524:                     $jscript = '<script type="text/javascript">'."\n".
                   18525:                                '// <![CDATA['."\n".
                   18526:                                $jscript."\n".
                   18527:                                '// ]]>'."\n".
                   18528:                                '</script>'."\n";
1.1181    raeburn  18529:                 }
                   18530:             }
                   18531:             if ($instcodeform eq '') {
                   18532:                 $instcodeform =
                   18533:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18534:                     $list->{'instcodefilter'}.'" />';
                   18535:                 $instcodetitle = $lt{'ins'};
                   18536:             } else {
                   18537:                 $instcodetitle = $lt{'inc'};
                   18538:             }
                   18539:             if ($fixeddom) {
                   18540:                 $instcodetitle .= '<br />('.$codedom.')';
                   18541:             }
                   18542:         }
                   18543:     }
                   18544:     my $output = qq|
                   18545: <form method="post" name="filterpicker" action="$action">
                   18546: <input type="hidden" name="form" value="$formname" />
                   18547: |;
                   18548:     if ($formname eq 'modifycourse') {
                   18549:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18550:                    '<input type="hidden" name="prevphase" value="'.
                   18551:                    $prevphase.'" />'."\n";
1.1198    musolffc 18552:     } elsif ($formname eq 'quotacheck') {
                   18553:         $output .= qq|
                   18554: <input type="hidden" name="sortby" value="" />
                   18555: <input type="hidden" name="sortorder" value="" />
                   18556: |;
                   18557:     } else {
1.1181    raeburn  18558:         my $name_input;
                   18559:         if ($cnameelement ne '') {
                   18560:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18561:                           $cnameelement.'" />';
                   18562:         }
                   18563:         $output .= qq|
1.1182    raeburn  18564: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18565: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18566: $name_input
                   18567: $roleelement
                   18568: $multelement
                   18569: $typeelement
                   18570: |;
                   18571:         if ($formname eq 'portform') {
                   18572:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18573:         }
                   18574:     }
                   18575:     if ($fixeddom) {
                   18576:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18577:     }
                   18578:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18579:     if ($sincefilterform) {
                   18580:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18581:                   .$sincefilterform
                   18582:                   .&Apache::lonhtmlcommon::row_closure();
                   18583:     }
                   18584:     if ($createdfilterform) {
                   18585:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18586:                   .$createdfilterform
                   18587:                   .&Apache::lonhtmlcommon::row_closure();
                   18588:     }
                   18589:     if ($domainselectform) {
                   18590:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18591:                   .$domainselectform
                   18592:                   .&Apache::lonhtmlcommon::row_closure();
                   18593:     }
                   18594:     if ($typeselectform) {
                   18595:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18596:             $output .= $typeselectform;
                   18597:         } else {
                   18598:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18599:                       .$typeselectform
                   18600:                       .&Apache::lonhtmlcommon::row_closure();
                   18601:         }
                   18602:     }
                   18603:     if ($instcodeform) {
                   18604:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18605:                   .$instcodeform
                   18606:                   .&Apache::lonhtmlcommon::row_closure();
                   18607:     }
                   18608:     if (exists($filter->{'ownerfilter'})) {
                   18609:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18610:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18611:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18612:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18613:                    $ownerdomselectform.'</td></tr></table>'.
                   18614:                    &Apache::lonhtmlcommon::row_closure();
                   18615:     }
                   18616:     if (exists($filter->{'personfilter'})) {
                   18617:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18618:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18619:                    '<input type="text" name="personfilter" size="20" value="'.
                   18620:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18621:                    $persondomselectform.'</td></tr></table>'.
                   18622:                    &Apache::lonhtmlcommon::row_closure();
                   18623:     }
                   18624:     if (exists($filter->{'coursefilter'})) {
                   18625:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18626:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18627:                   .$list->{'coursefilter'}.'" />'
                   18628:                   .&Apache::lonhtmlcommon::row_closure();
                   18629:     }
                   18630:     if ($cloneableonlyform) {
                   18631:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18632:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18633:     }
                   18634:     if (exists($filter->{'descriptfilter'})) {
                   18635:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18636:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18637:                   .$list->{'descriptfilter'}.'" />'
                   18638:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18639:     }
                   18640:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18641:                '<input type="hidden" name="updater" value="" />'."\n".
                   18642:                '<input type="submit" name="gosearch" value="'.
                   18643:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18644:     return $jscript.$clonewarning.$output;
                   18645: }
                   18646: 
                   18647: =pod 
                   18648: 
                   18649: =item * &timebased_select_form()
                   18650: 
1.1182    raeburn  18651: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18652: filter e.g., Course Activity, Course Created, when searching for courses
                   18653: or communities
                   18654: 
                   18655: Inputs:
                   18656: 
                   18657: item - name of form element (sincefilter or createdfilter)
                   18658: 
                   18659: filter - anonymous hash of criteria and their values
                   18660: 
                   18661: Returns: HTML for a select box contained a blank, then six time selections,
                   18662:          with value set in incoming form variables currently selected. 
                   18663: 
                   18664: Side Effects: None
                   18665: 
                   18666: =cut
                   18667: 
                   18668: sub timebased_select_form {
                   18669:     my ($item,$filter) = @_;
                   18670:     if (ref($filter) eq 'HASH') {
                   18671:         $filter->{$item} =~ s/[^\d-]//g;
                   18672:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18673:         return &select_form(
                   18674:                             $filter->{$item},
                   18675:                             $item,
                   18676:                             {      '-1' => '',
                   18677:                                 '86400' => &mt('today'),
                   18678:                                '604800' => &mt('last week'),
                   18679:                               '2592000' => &mt('last month'),
                   18680:                               '7776000' => &mt('last three months'),
                   18681:                              '15552000' => &mt('last six months'),
                   18682:                              '31104000' => &mt('last year'),
                   18683:                     'select_form_order' =>
                   18684:                            ['-1','86400','604800','2592000','7776000',
                   18685:                             '15552000','31104000']});
                   18686:     }
                   18687: }
                   18688: 
                   18689: =pod
                   18690: 
                   18691: =item * &js_changer()
                   18692: 
                   18693: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18694: when course type or domain is changed, and also to hide 'Searching ...' on
                   18695: page load completion for page showing search result.
1.1181    raeburn  18696: 
                   18697: Inputs: None
                   18698: 
1.1183    raeburn  18699: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18700: 
                   18701: Side Effects: None
                   18702: 
                   18703: =cut
                   18704: 
                   18705: sub js_changer {
                   18706:     return <<ENDJS;
                   18707: <script type="text/javascript">
                   18708: // <![CDATA[
                   18709: function updateFilters(caller) {
                   18710:     if (typeof(caller) != "undefined") {
                   18711:         document.filterpicker.updater.value = caller.name;
                   18712:     }
                   18713:     document.filterpicker.submit();
                   18714: }
1.1183    raeburn  18715: 
                   18716: function hideSearching() {
                   18717:     if (document.getElementById('searching')) {
                   18718:         document.getElementById('searching').style.display = 'none';
                   18719:     }
                   18720:     return;
                   18721: }
                   18722: 
1.1181    raeburn  18723: // ]]>
                   18724: </script>
                   18725: 
                   18726: ENDJS
                   18727: }
                   18728: 
                   18729: =pod
                   18730: 
1.1182    raeburn  18731: =item * &search_courses()
                   18732: 
                   18733: Process selected filters form course search form and pass to lonnet::courseiddump
                   18734: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18735: 
                   18736: Inputs:
                   18737: 
                   18738: dom - domain being searched 
                   18739: 
                   18740: type - course type ('Course' or 'Community' or '.' if any).
                   18741: 
                   18742: filter - anonymous hash of criteria and their values
                   18743: 
                   18744: numtitles - for institutional codes - number of categories
                   18745: 
                   18746: cloneruname - optional username of new course owner
                   18747: 
                   18748: clonerudom - optional domain of new course owner
                   18749: 
1.1221    raeburn  18750: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18751:             (used when DC is using course creation form)
                   18752: 
                   18753: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18754: 
1.1221    raeburn  18755: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18756:            (and so can clone automatically)
                   18757: 
                   18758: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18759: 
                   18760: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18761:               courses to clone 
1.1182    raeburn  18762: 
                   18763: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18764: 
                   18765: 
                   18766: Side Effects: None
                   18767: 
                   18768: =cut
                   18769: 
                   18770: 
                   18771: sub search_courses {
1.1221    raeburn  18772:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18773:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18774:     my (%courses,%showcourses,$cloner);
                   18775:     if (($filter->{'ownerfilter'} ne '') ||
                   18776:         ($filter->{'ownerdomfilter'} ne '')) {
                   18777:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18778:                                        $filter->{'ownerdomfilter'};
                   18779:     }
                   18780:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18781:         if (!$filter->{$item}) {
                   18782:             $filter->{$item}='.';
                   18783:         }
                   18784:     }
                   18785:     my $now = time;
                   18786:     my $timefilter =
                   18787:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18788:     my ($createdbefore,$createdafter);
                   18789:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18790:         $createdbefore = $now;
                   18791:         $createdafter = $now-$filter->{'createdfilter'};
                   18792:     }
                   18793:     my ($instcodefilter,$regexpok);
                   18794:     if ($numtitles) {
                   18795:         if ($env{'form.official'} eq 'on') {
                   18796:             $instcodefilter =
                   18797:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18798:             $regexpok = 1;
                   18799:         } elsif ($env{'form.official'} eq 'off') {
                   18800:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18801:             unless ($instcodefilter eq '') {
                   18802:                 $regexpok = -1;
                   18803:             }
                   18804:         }
                   18805:     } else {
                   18806:         $instcodefilter = $filter->{'instcodefilter'};
                   18807:     }
                   18808:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18809:     if ($type eq '') { $type = '.'; }
                   18810: 
                   18811:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18812:         $cloner = $cloneruname.':'.$clonerudom;
                   18813:     }
                   18814:     %courses = &Apache::lonnet::courseiddump($dom,
                   18815:                                              $filter->{'descriptfilter'},
                   18816:                                              $timefilter,
                   18817:                                              $instcodefilter,
                   18818:                                              $filter->{'combownerfilter'},
                   18819:                                              $filter->{'coursefilter'},
                   18820:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18821:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18822:                                              $filter->{'cloneableonly'},
                   18823:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18824:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18825:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18826:         my $ccrole;
                   18827:         if ($type eq 'Community') {
                   18828:             $ccrole = 'co';
                   18829:         } else {
                   18830:             $ccrole = 'cc';
                   18831:         }
                   18832:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18833:                                                      $filter->{'persondomfilter'},
                   18834:                                                      'userroles',undef,
                   18835:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18836:                                                      $dom);
                   18837:         foreach my $role (keys(%rolehash)) {
                   18838:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18839:             my $cid = $cdom.'_'.$cnum;
                   18840:             if (exists($courses{$cid})) {
                   18841:                 if (ref($courses{$cid}) eq 'HASH') {
                   18842:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18843:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18844:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18845:                         }
                   18846:                     } else {
                   18847:                         $courses{$cid}{roles} = [$courserole];
                   18848:                     }
                   18849:                     $showcourses{$cid} = $courses{$cid};
                   18850:                 }
                   18851:             }
                   18852:         }
                   18853:         %courses = %showcourses;
                   18854:     }
                   18855:     return %courses;
                   18856: }
                   18857: 
                   18858: =pod
                   18859: 
1.1181    raeburn  18860: =back
                   18861: 
1.1207    raeburn  18862: =head1 Routines for version requirements for current course.
                   18863: 
                   18864: =over 4
                   18865: 
                   18866: =item * &check_release_required()
                   18867: 
                   18868: Compares required LON-CAPA version with version on server, and
                   18869: if required version is newer looks for a server with the required version.
                   18870: 
                   18871: Looks first at servers in user's owen domain; if none suitable, looks at
                   18872: servers in course's domain are permitted to host sessions for user's domain.
                   18873: 
                   18874: Inputs:
                   18875: 
                   18876: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18877: 
                   18878: $courseid - Course ID of current course
                   18879: 
                   18880: $rolecode - User's current role in course (for switchserver query string).
                   18881: 
                   18882: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18883: 
                   18884: 
                   18885: Returns:
                   18886: 
                   18887: $switchserver - query string tp append to /adm/switchserver call (if 
                   18888:                 current server's LON-CAPA version is too old. 
                   18889: 
                   18890: $warning - Message is displayed if no suitable server could be found.
                   18891: 
                   18892: =cut
                   18893: 
                   18894: sub check_release_required {
                   18895:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18896:     my ($switchserver,$warning);
                   18897:     if ($required ne '') {
                   18898:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18899:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18900:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18901:             my $otherserver;
                   18902:             if (($major eq '' && $minor eq '') ||
                   18903:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18904:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18905:                 my $switchlcrev =
                   18906:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18907:                                                            $userdomserver);
                   18908:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18909:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18910:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18911:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18912:                     if ($cdom ne $env{'user.domain'}) {
                   18913:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18914:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18915:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18916:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18917:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18918:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18919:                         my $canhost =
                   18920:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18921:                                                               $coursedomserver,
                   18922:                                                               $remoterev,
                   18923:                                                               $udomdefaults{'remotesessions'},
                   18924:                                                               $defdomdefaults{'hostedsessions'});
                   18925: 
                   18926:                         if ($canhost) {
                   18927:                             $otherserver = $coursedomserver;
                   18928:                         } else {
                   18929:                             $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.");
                   18930:                         }
                   18931:                     } else {
                   18932:                         $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).");
                   18933:                     }
                   18934:                 } else {
                   18935:                     $otherserver = $userdomserver;
                   18936:                 }
                   18937:             }
                   18938:             if ($otherserver ne '') {
                   18939:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18940:             }
                   18941:         }
                   18942:     }
                   18943:     return ($switchserver,$warning);
                   18944: }
                   18945: 
                   18946: =pod
                   18947: 
                   18948: =item * &check_release_result()
                   18949: 
                   18950: Inputs:
                   18951: 
                   18952: $switchwarning - Warning message if no suitable server found to host session.
                   18953: 
                   18954: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18955:                 and current role.
                   18956: 
                   18957: Returns: HTML to display with information about requirement to switch server.
                   18958:          Either displaying warning with link to Roles/Courses screen or
                   18959:          display link to switchserver.
                   18960: 
1.1181    raeburn  18961: =cut
                   18962: 
1.1207    raeburn  18963: sub check_release_result {
                   18964:     my ($switchwarning,$switchserver) = @_;
                   18965:     my $output = &start_page('Selected course unavailable on this server').
                   18966:                  '<p class="LC_warning">';
                   18967:     if ($switchwarning) {
                   18968:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18969:         if (&show_course()) {
                   18970:             $output .= &mt('Display courses');
                   18971:         } else {
                   18972:             $output .= &mt('Display roles');
                   18973:         }
                   18974:         $output .= '</a>';
                   18975:     } elsif ($switchserver) {
                   18976:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18977:                    '<br />'.
                   18978:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18979:                    &mt('Switch Server').
                   18980:                    '</a>';
                   18981:     }
                   18982:     $output .= '</p>'.&end_page();
                   18983:     return $output;
                   18984: }
                   18985: 
                   18986: =pod
                   18987: 
                   18988: =item * &needs_coursereinit()
                   18989: 
                   18990: Determine if course contents stored for user's session needs to be
                   18991: refreshed, because content has changed since "Big Hash" last tied.
                   18992: 
                   18993: Check for change is made if time last checked is more than 10 minutes ago
                   18994: (by default).
                   18995: 
                   18996: Inputs:
                   18997: 
                   18998: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18999: 
                   19000: $interval (optional) - Time which may elapse (in s) between last check for content
                   19001:                        change in current course. (default: 600 s).  
                   19002: 
                   19003: Returns: an array; first element is:
                   19004: 
                   19005: =over 4
                   19006: 
                   19007: 'switch' - if content updates mean user's session
                   19008:            needs to be switched to a server running a newer LON-CAPA version
                   19009:  
                   19010: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19011:            on current server hosting user's session                
                   19012: 
                   19013: ''       - if no action required.
                   19014: 
                   19015: =back
                   19016: 
                   19017: If first item element is 'switch':
                   19018: 
                   19019: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19020: 
                   19021: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19022:                               and current role. 
                   19023: 
                   19024: otherwise: no other elements returned.
                   19025: 
                   19026: =back
                   19027: 
                   19028: =cut
                   19029: 
                   19030: sub needs_coursereinit {
                   19031:     my ($loncaparev,$interval) = @_;
                   19032:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19033:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19034:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19035:     my $now = time;
                   19036:     if ($interval eq '') {
                   19037:         $interval = 600;
                   19038:     }
                   19039:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19040:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19041:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19042:         if ($blocked) {
                   19043:             return ();
                   19044:         }
1.1391    raeburn  19045:         my $update;
                   19046:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19047:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19048:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19049:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19050:             if ($needswitch) {
                   19051:                 return ('switch',$switchwarning,$switchserver);
                   19052:             }
                   19053:             $update = 'main';
                   19054:         }
                   19055:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19056:             if ($update) {
                   19057:                 $update = 'both';
                   19058:             } else {
                   19059:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19060:                 if ($needswitch) {
                   19061:                     return ('switch',$switchwarning,$switchserver);
                   19062:                 } else {
                   19063:                     $update = 'supp';
1.1207    raeburn  19064:                 }
                   19065:             }
1.1391    raeburn  19066:         }
1.1451    raeburn  19067:         return ($update); 
1.1391    raeburn  19068:     }
                   19069:     return ();
                   19070: }
                   19071: 
                   19072: sub switch_for_update {
                   19073:     my ($loncaparev,$cdom,$cnum) = @_;
                   19074:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19075:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19076:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19077:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19078:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19079:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19080:             my ($switchserver,$switchwarning) =
                   19081:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19082:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19083:             if ($switchwarning ne '' || $switchserver ne '') {
                   19084:                 return ('switch',$switchwarning,$switchserver);
                   19085:             }
1.1207    raeburn  19086:         }
                   19087:     }
                   19088:     return ();
                   19089: }
1.1181    raeburn  19090: 
1.1083    raeburn  19091: sub update_content_constraints {
1.1395    raeburn  19092:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19093:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19094:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19095:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19096:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19097:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19098:         if ($item eq 'resourcetag') {
                   19099:             if ($name eq 'responsetype') {
                   19100:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19101:             }
1.1307    raeburn  19102:         } elsif ($item eq 'course') {
                   19103:             if ($name eq 'courserestype') {
                   19104:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19105:             }
1.1083    raeburn  19106:         }
                   19107:     }
                   19108:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19109:     if (defined($navmap)) {
1.1307    raeburn  19110:         my (%allresponses,%allcrsrestypes);
                   19111:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19112:             if ($res->is_tool()) {
                   19113:                 if ($allcrsrestypes{'exttool'}) {
                   19114:                     $allcrsrestypes{'exttool'} ++;
                   19115:                 } else {
                   19116:                     $allcrsrestypes{'exttool'} = 1;
                   19117:                 }
                   19118:                 next;
                   19119:             }
1.1083    raeburn  19120:             my %responses = $res->responseTypes();
                   19121:             foreach my $key (keys(%responses)) {
                   19122:                 next unless(exists($checkresponsetypes{$key}));
                   19123:                 $allresponses{$key} += $responses{$key};
                   19124:             }
                   19125:         }
                   19126:         foreach my $key (keys(%allresponses)) {
                   19127:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19128:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19129:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19130:             }
                   19131:         }
1.1307    raeburn  19132:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19133:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19134:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19135:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19136:             }
                   19137:         }
1.1083    raeburn  19138:         undef($navmap);
                   19139:     }
1.1391    raeburn  19140:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19141:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19142:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19143:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19144:         }
                   19145:     }
1.1083    raeburn  19146:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19147:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19148:     }
                   19149:     return;
                   19150: }
                   19151: 
1.1110    raeburn  19152: sub allmaps_incourse {
                   19153:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19154:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19155:         $cid = $env{'request.course.id'};
                   19156:         $cdom = $env{'course.'.$cid.'.domain'};
                   19157:         $cnum = $env{'course.'.$cid.'.num'};
                   19158:         $chome = $env{'course.'.$cid.'.home'};
                   19159:     }
                   19160:     my %allmaps = ();
                   19161:     my $lastchange =
                   19162:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19163:     if ($lastchange > $env{'request.course.tied'}) {
                   19164:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19165:         unless ($ferr) {
1.1395    raeburn  19166:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19167:         }
                   19168:     }
                   19169:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19170:     if (defined($navmap)) {
                   19171:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19172:             $allmaps{$res->src()} = 1;
                   19173:         }
                   19174:     }
                   19175:     return \%allmaps;
                   19176: }
                   19177: 
1.1083    raeburn  19178: sub parse_supplemental_title {
                   19179:     my ($title) = @_;
                   19180: 
                   19181:     my ($foldertitle,$renametitle);
                   19182:     if ($title =~ /&amp;&amp;&amp;/) {
                   19183:         $title = &HTML::Entites::decode($title);
                   19184:     }
                   19185:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19186:         $renametitle=$4;
                   19187:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19188:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19189:         my $name =  &plainname($uname,$udom);
                   19190:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19191:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19192:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19193:         if ($foldertitle ne '') {
1.1401    raeburn  19194:             $title .= ': <br />'.$foldertitle;
                   19195:         }
1.1083    raeburn  19196:     }
                   19197:     if (wantarray) {
                   19198:         return ($title,$foldertitle,$renametitle);
                   19199:     }
                   19200:     return $title;
                   19201: }
                   19202: 
1.1395    raeburn  19203: sub get_supplemental {
                   19204:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19205:     my $hashid=$cnum.':'.$cdom;
                   19206:     my ($supplemental,$cached,$set_httprefs);
                   19207:     unless ($ignorecache) {
                   19208:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19209:     }
                   19210:     unless (defined($cached)) {
                   19211:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19212:         unless ($chome eq 'no_host') {
                   19213:             my @order = @LONCAPA::map::order;
                   19214:             my @resources = @LONCAPA::map::resources;
                   19215:             my @resparms = @LONCAPA::map::resparms;
                   19216:             my @zombies = @LONCAPA::map::zombies;
                   19217:             my ($errors,%ids,%hidden);
                   19218:             $errors =
                   19219:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19220:                                       $errors,$possdel,\%ids,\%hidden);
                   19221:             @LONCAPA::map::order = @order;
                   19222:             @LONCAPA::map::resources = @resources;
                   19223:             @LONCAPA::map::resparms = @resparms;
                   19224:             @LONCAPA::map::zombies = @zombies;
                   19225:             $set_httprefs = 1;
                   19226:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19227:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19228:             }
                   19229:             $supplemental = {
                   19230:                                ids => \%ids,
                   19231:                                hidden => \%hidden,
                   19232:                             };
                   19233:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19234:         }
                   19235:     }
                   19236:     return ($supplemental,$set_httprefs);
                   19237: }
                   19238: 
1.1143    raeburn  19239: sub recurse_supplemental {
1.1391    raeburn  19240:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19241:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19242:         my $mapnum;
                   19243:         if ($suppmap eq 'supplemental.sequence') {
                   19244:             $mapnum = 0;
                   19245:         } else {
                   19246:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19247:         }
1.1143    raeburn  19248:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19249:         if ($fatal) {
                   19250:             $errors ++;
                   19251:         } else {
1.1389    raeburn  19252:             my @order = @LONCAPA::map::order;
                   19253:             if (@order > 0) {
                   19254:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19255:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19256:                 foreach my $idx (@order) {
                   19257:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19258:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19259:                         my $id = $mapnum.':'.$idx;
                   19260:                         push(@{$suppids->{$src}},$id);
                   19261:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19262:                             $hiddensupp->{$id} = 1;
                   19263:                         }
1.1146    raeburn  19264:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19265:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19266:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19267:                         } else {
1.1391    raeburn  19268:                             my $allowed;
                   19269:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19270:                                 $allowed = 1;
                   19271:                             } elsif ($possdel) {
                   19272:                                 foreach my $item (@{$suppids->{$src}}) {
                   19273:                                     next if ($item eq $id);
                   19274:                                     unless ($hiddensupp->{$item}) {
                   19275:                                        $allowed = 1;
                   19276:                                        last;
                   19277:                                     }
                   19278:                                 }
                   19279:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19280:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19281:                                 }
                   19282:                             }
                   19283:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19284:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19285:                             }
1.1143    raeburn  19286:                         }
                   19287:                     }
                   19288:                 }
                   19289:             }
                   19290:         }
                   19291:     }
1.1391    raeburn  19292:     return $errors;
                   19293: }
                   19294: 
                   19295: sub set_supp_httprefs {
                   19296:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19297:     if (ref($supplemental) eq 'HASH') {
                   19298:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19299:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19300:                 next if ($src =~ /\.sequence$/);
                   19301:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19302:                     my $allowed;
                   19303:                     if ($env{'request.role.adv'}) {
                   19304:                         $allowed = 1;
                   19305:                     } else {
                   19306:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19307:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19308:                                 $allowed = 1;
                   19309:                                 last;
                   19310:                             }
                   19311:                         }
                   19312:                     }
                   19313:                     if (exists($env{'httpref.'.$src})) {
                   19314:                         if ($possdel) {
                   19315:                             unless ($allowed) {
                   19316:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19317:                             }
                   19318:                         }
                   19319:                     } elsif ($allowed) {
                   19320:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19321:                     }
                   19322:                 }
                   19323:             }
                   19324:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19325:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19326:             }
                   19327:         }
                   19328:     }
                   19329: }
                   19330: 
                   19331: sub get_supp_parameter {
                   19332:     my ($resparm,$name)=@_;
                   19333:     return if ($resparm eq '');
                   19334:     my $value=undef;
                   19335:     my $ptype=undef;
                   19336:     foreach (split('&&&',$resparm)) {
                   19337:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19338:         if ($thisname eq $name) {
                   19339:             $value=$thisvalue;
                   19340:             $ptype=$thistype;
                   19341:         }
                   19342:     }
                   19343:     return $value;
1.1143    raeburn  19344: }
                   19345: 
1.1101    raeburn  19346: sub symb_to_docspath {
1.1267    raeburn  19347:     my ($symb,$navmapref) = @_;
                   19348:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19349:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19350:     if ($resurl=~/\.(sequence|page)$/) {
                   19351:         $mapurl=$resurl;
                   19352:     } elsif ($resurl eq 'adm/navmaps') {
                   19353:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19354:     }
                   19355:     my $mapresobj;
1.1267    raeburn  19356:     unless (ref($$navmapref)) {
                   19357:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19358:     }
                   19359:     if (ref($$navmapref)) {
                   19360:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19361:     }
                   19362:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19363:     my $type=$2;
                   19364:     my $path;
                   19365:     if (ref($mapresobj)) {
                   19366:         my $pcslist = $mapresobj->map_hierarchy();
                   19367:         if ($pcslist ne '') {
                   19368:             foreach my $pc (split(/,/,$pcslist)) {
                   19369:                 next if ($pc <= 1);
1.1267    raeburn  19370:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19371:                 if (ref($res)) {
                   19372:                     my $thisurl = $res->src();
                   19373:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19374:                     my $thistitle = $res->title();
                   19375:                     $path .= '&'.
                   19376:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19377:                              &escape($thistitle).
1.1101    raeburn  19378:                              ':'.$res->randompick().
                   19379:                              ':'.$res->randomout().
                   19380:                              ':'.$res->encrypted().
                   19381:                              ':'.$res->randomorder().
                   19382:                              ':'.$res->is_page();
                   19383:                 }
                   19384:             }
                   19385:         }
                   19386:         $path =~ s/^\&//;
                   19387:         my $maptitle = $mapresobj->title();
                   19388:         if ($mapurl eq 'default') {
1.1129    raeburn  19389:             $maptitle = 'Main Content';
1.1101    raeburn  19390:         }
                   19391:         $path .= (($path ne '')? '&' : '').
                   19392:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19393:                  &escape($maptitle).
1.1101    raeburn  19394:                  ':'.$mapresobj->randompick().
                   19395:                  ':'.$mapresobj->randomout().
                   19396:                  ':'.$mapresobj->encrypted().
                   19397:                  ':'.$mapresobj->randomorder().
                   19398:                  ':'.$mapresobj->is_page();
                   19399:     } else {
                   19400:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19401:         my $ispage = (($type eq 'page')? 1 : '');
                   19402:         if ($mapurl eq 'default') {
1.1129    raeburn  19403:             $maptitle = 'Main Content';
1.1101    raeburn  19404:         }
                   19405:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19406:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19407:     }
                   19408:     unless ($mapurl eq 'default') {
                   19409:         $path = 'default&'.
1.1146    raeburn  19410:                 &escape('Main Content').
1.1101    raeburn  19411:                 ':::::&'.$path;
                   19412:     }
                   19413:     return $path;
                   19414: }
                   19415: 
1.1393    raeburn  19416: sub validate_folderpath {
                   19417:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19418:     if ($env{'form.folderpath'} ne '') {
                   19419:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19420:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19421:         for (my $i=0; $i<@items; $i++) {
                   19422:             my $odd = $i%2;
                   19423:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19424:                 $badpath = 1;
1.1394    raeburn  19425:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19426:                 my $idx = $i-1;
1.1394    raeburn  19427:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19428:                     my $esc_name = $1;
                   19429:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19430:                         $supppath .= '&'.$esc_name;
                   19431:                         $changed = 1;
                   19432:                     } else {
                   19433:                         $supppath .= '&'.$items[$i];
                   19434:                     }
                   19435:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19436:                     $changed = 1;
1.1393    raeburn  19437:                     my $is_hidden;
                   19438:                     unless ($got_supp) {
1.1395    raeburn  19439:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19440:                         if (ref($supplemental) eq 'HASH') {
                   19441:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19442:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19443:                             }
                   19444:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19445:                                 %suppids = %{$supplemental->{'ids'}};
                   19446:                             }
                   19447:                         }
                   19448:                         $got_supp = 1;
                   19449:                     }
                   19450:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19451:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19452:                         if ($supphidden{$mapid}) {
                   19453:                             $is_hidden = 1;
                   19454:                         }
                   19455:                     }
1.1394    raeburn  19456:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19457:                 } else {
                   19458:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19459:                 }
                   19460:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19461:                 $badpath = 1;
1.1394    raeburn  19462:             } elsif ($supplementalflag) {
1.1393    raeburn  19463:                 $supppath .= '&'.$items[$i];
                   19464:             }
                   19465:             last if ($badpath);
                   19466:         }
                   19467:         if ($badpath) {
                   19468:             delete($env{'form.folderpath'});
1.1394    raeburn  19469:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19470:             $supppath =~ s/^\&//;
                   19471:             $env{'form.folderpath'} = $supppath;
                   19472:         }
                   19473:     }
                   19474:     return;
                   19475: }
                   19476: 
1.1094    raeburn  19477: sub captcha_display {
1.1327    raeburn  19478:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19479:     my ($output,$error);
1.1234    raeburn  19480:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19481:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19482:     if ($captcha eq 'original') {
1.1094    raeburn  19483:         $output = &create_captcha();
                   19484:         unless ($output) {
1.1172    raeburn  19485:             $error = 'captcha';
1.1094    raeburn  19486:         }
                   19487:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19488:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19489:         unless ($output) {
1.1172    raeburn  19490:             $error = 'recaptcha';
1.1094    raeburn  19491:         }
                   19492:     }
1.1234    raeburn  19493:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19494: }
                   19495: 
                   19496: sub captcha_response {
1.1327    raeburn  19497:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19498:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19499:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19500:     if ($captcha eq 'original') {
1.1094    raeburn  19501:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19502:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19503:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19504:     } else {
                   19505:         $captcha_chk = 1;
                   19506:     }
                   19507:     return ($captcha_chk,$captcha_error);
                   19508: }
                   19509: 
                   19510: sub get_captcha_config {
1.1327    raeburn  19511:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19512:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19513:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19514:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19515:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19516:     if ($context eq 'usercreation') {
                   19517:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19518:         if (ref($domconfig{$context}) eq 'HASH') {
                   19519:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19520:             if (ref($hashtocheck) eq 'HASH') {
                   19521:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19522:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19523:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19524:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19525:                     }
                   19526:                     if ($privkey && $pubkey) {
                   19527:                         $captcha = 'recaptcha';
1.1234    raeburn  19528:                         $version = $hashtocheck->{'recaptchaversion'};
                   19529:                         if ($version ne '2') {
                   19530:                             $version = 1;
                   19531:                         }
1.1095    raeburn  19532:                     } else {
                   19533:                         $captcha = 'original';
                   19534:                     }
                   19535:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19536:                     $captcha = 'original';
                   19537:                 }
1.1094    raeburn  19538:             }
1.1095    raeburn  19539:         } else {
                   19540:             $captcha = 'captcha';
                   19541:         }
                   19542:     } elsif ($context eq 'login') {
                   19543:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19544:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19545:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19546:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19547:             if ($privkey && $pubkey) {
                   19548:                 $captcha = 'recaptcha';
1.1234    raeburn  19549:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19550:                 if ($version ne '2') {
                   19551:                     $version = 1; 
                   19552:                 }
1.1095    raeburn  19553:             } else {
                   19554:                 $captcha = 'original';
1.1094    raeburn  19555:             }
1.1095    raeburn  19556:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19557:             $captcha = 'original';
1.1094    raeburn  19558:         }
1.1327    raeburn  19559:     } elsif ($context eq 'passwords') {
                   19560:         if ($dom_in_effect) {
                   19561:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19562:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19563:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19564:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19565:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19566:                 }
                   19567:                 if ($privkey && $pubkey) {
                   19568:                     $captcha = 'recaptcha';
                   19569:                     $version = $passwdconf{'recaptchaversion'};
                   19570:                     if ($version ne '2') {
                   19571:                         $version = 1;
                   19572:                     }
                   19573:                 } else {
                   19574:                     $captcha = 'original';
                   19575:                 }
                   19576:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19577:                 $captcha = 'original';
                   19578:             }
                   19579:         }
                   19580:     } 
1.1234    raeburn  19581:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19582: }
                   19583: 
                   19584: sub create_captcha {
                   19585:     my %captcha_params = &captcha_settings();
                   19586:     my ($output,$maxtries,$tries) = ('',10,0);
                   19587:     while ($tries < $maxtries) {
                   19588:         $tries ++;
                   19589:         my $captcha = Authen::Captcha->new (
                   19590:                                            output_folder => $captcha_params{'output_dir'},
                   19591:                                            data_folder   => $captcha_params{'db_dir'},
                   19592:                                           );
                   19593:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19594: 
                   19595:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19596:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19597:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19598:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19599:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19600:                       '</span><br />'.
1.1176    raeburn  19601:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19602:             last;
                   19603:         }
                   19604:     }
1.1323    raeburn  19605:     if ($output eq '') {
                   19606:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19607:     }
1.1094    raeburn  19608:     return $output;
                   19609: }
                   19610: 
                   19611: sub captcha_settings {
                   19612:     my %captcha_params = (
                   19613:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19614:                            www_output_dir => "/captchaspool",
                   19615:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19616:                            numchars       => '5',
                   19617:                          );
                   19618:     return %captcha_params;
                   19619: }
                   19620: 
                   19621: sub check_captcha {
                   19622:     my ($captcha_chk,$captcha_error);
                   19623:     my $code = $env{'form.code'};
                   19624:     my $md5sum = $env{'form.crypt'};
                   19625:     my %captcha_params = &captcha_settings();
                   19626:     my $captcha = Authen::Captcha->new(
                   19627:                       output_folder => $captcha_params{'output_dir'},
                   19628:                       data_folder   => $captcha_params{'db_dir'},
                   19629:                   );
1.1109    raeburn  19630:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19631:     my %captcha_hash = (
                   19632:                         0       => 'Code not checked (file error)',
                   19633:                        -1      => 'Failed: code expired',
                   19634:                        -2      => 'Failed: invalid code (not in database)',
                   19635:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19636:     );
                   19637:     if ($captcha_chk != 1) {
                   19638:         $captcha_error = $captcha_hash{$captcha_chk}
                   19639:     }
                   19640:     return ($captcha_chk,$captcha_error);
                   19641: }
                   19642: 
                   19643: sub create_recaptcha {
1.1234    raeburn  19644:     my ($pubkey,$version) = @_;
                   19645:     if ($version >= 2) {
1.1367    raeburn  19646:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19647:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19648:     } else {
                   19649:         my $use_ssl;
                   19650:         if ($ENV{'SERVER_PORT'} == 443) {
                   19651:             $use_ssl = 1;
                   19652:         }
                   19653:         my $captcha = Captcha::reCAPTCHA->new;
                   19654:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19655:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19656:                &mt('If the text is hard to read, [_1] will replace them.',
                   19657:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19658:                '<br /><br />';
                   19659:     }
1.1094    raeburn  19660: }
                   19661: 
                   19662: sub check_recaptcha {
1.1234    raeburn  19663:     my ($privkey,$version) = @_;
1.1094    raeburn  19664:     my $captcha_chk;
1.1350    raeburn  19665:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19666:     if ($version >= 2) {
                   19667:         my %info = (
                   19668:                      secret   => $privkey, 
                   19669:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19670:                      remoteip => $ip,
1.1234    raeburn  19671:                    );
1.1280    raeburn  19672:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19673:         $request->content(join('&',map {
                   19674:                          my $name = escape($_);
                   19675:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19676:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19677:                          : &escape($info{$_}) );
                   19678:         } keys(%info)));
                   19679:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19680:         if ($response->is_success)  {
                   19681:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19682:             if (ref($data) eq 'HASH') {
                   19683:                 if ($data->{'success'}) {
                   19684:                     $captcha_chk = 1;
                   19685:                 }
                   19686:             }
                   19687:         }
                   19688:     } else {
                   19689:         my $captcha = Captcha::reCAPTCHA->new;
                   19690:         my $captcha_result =
                   19691:             $captcha->check_answer(
                   19692:                                     $privkey,
1.1350    raeburn  19693:                                     $ip,
1.1234    raeburn  19694:                                     $env{'form.recaptcha_challenge_field'},
                   19695:                                     $env{'form.recaptcha_response_field'},
                   19696:                                   );
                   19697:         if ($captcha_result->{is_valid}) {
                   19698:             $captcha_chk = 1;
                   19699:         }
1.1094    raeburn  19700:     }
                   19701:     return $captcha_chk;
                   19702: }
                   19703: 
1.1174    raeburn  19704: sub emailusername_info {
1.1244    raeburn  19705:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19706:     my %titles = &Apache::lonlocal::texthash (
                   19707:                      lastname      => 'Last Name',
                   19708:                      firstname     => 'First Name',
                   19709:                      institution   => 'School/college/university',
                   19710:                      location      => "School's city, state/province, country",
                   19711:                      web           => "School's web address",
                   19712:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19713:                      id            => 'Student/Employee ID',
1.1174    raeburn  19714:                  );
                   19715:     return (\@fields,\%titles);
                   19716: }
                   19717: 
1.1161    raeburn  19718: sub cleanup_html {
                   19719:     my ($incoming) = @_;
                   19720:     my $outgoing;
                   19721:     if ($incoming ne '') {
                   19722:         $outgoing = $incoming;
                   19723:         $outgoing =~ s/;/&#059;/g;
                   19724:         $outgoing =~ s/\#/&#035;/g;
                   19725:         $outgoing =~ s/\&/&#038;/g;
                   19726:         $outgoing =~ s/</&#060;/g;
                   19727:         $outgoing =~ s/>/&#062;/g;
                   19728:         $outgoing =~ s/\(/&#040/g;
                   19729:         $outgoing =~ s/\)/&#041;/g;
                   19730:         $outgoing =~ s/"/&#034;/g;
                   19731:         $outgoing =~ s/'/&#039;/g;
                   19732:         $outgoing =~ s/\$/&#036;/g;
                   19733:         $outgoing =~ s{/}{&#047;}g;
                   19734:         $outgoing =~ s/=/&#061;/g;
                   19735:         $outgoing =~ s/\\/&#092;/g
                   19736:     }
                   19737:     return $outgoing;
                   19738: }
                   19739: 
1.1190    musolffc 19740: # Checks for critical messages and returns a redirect url if one exists.
                   19741: # $interval indicates how often to check for messages.
1.1282    raeburn  19742: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19743: sub critical_redirect {
1.1282    raeburn  19744:     my ($interval,$context) = @_;
1.1356    raeburn  19745:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19746:         return ();
                   19747:     }
1.1190    musolffc 19748:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19749:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19750:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19751:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19752:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19753:             if ($blocked) {
                   19754:                 my $checkrole = "cm./$cdom/$cnum";
                   19755:                 if ($env{'request.course.sec'} ne '') {
                   19756:                     $checkrole .= "/$env{'request.course.sec'}";
                   19757:                 }
                   19758:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19759:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19760:                     return;
                   19761:                 }
                   19762:             }
                   19763:         }
1.1190    musolffc 19764:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19765:                                         $env{'user.name'});
                   19766:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19767:         my $redirecturl;
1.1190    musolffc 19768:         if ($what[0]) {
1.1356    raeburn  19769: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19770: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19771: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19772:                 return (1, $url);
1.1190    musolffc 19773:             }
1.1191    raeburn  19774:         }
                   19775:     } 
                   19776:     return ();
1.1190    musolffc 19777: }
                   19778: 
1.1174    raeburn  19779: # Use:
                   19780: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19781: #
                   19782: ##################################################
                   19783: #          password associated functions         #
                   19784: ##################################################
                   19785: sub des_keys {
                   19786:     # Make a new key for DES encryption.
                   19787:     # Each key has two parts which are returned separately.
                   19788:     # Please note:  Each key must be passed through the &hex function
                   19789:     # before it is output to the web browser.  The hex versions cannot
                   19790:     # be used to decrypt.
                   19791:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19792:                 '8','9','a','b','c','d','e','f');
                   19793:     my $lkey='';
                   19794:     for (0..7) {
                   19795:         $lkey.=$hexstr[rand(15)];
                   19796:     }
                   19797:     my $ukey='';
                   19798:     for (0..7) {
                   19799:         $ukey.=$hexstr[rand(15)];
                   19800:     }
                   19801:     return ($lkey,$ukey);
                   19802: }
                   19803: 
                   19804: sub des_decrypt {
                   19805:     my ($key,$cyphertext) = @_;
                   19806:     my $keybin=pack("H16",$key);
                   19807:     my $cypher;
                   19808:     if ($Crypt::DES::VERSION>=2.03) {
                   19809:         $cypher=new Crypt::DES $keybin;
                   19810:     } else {
                   19811:         $cypher=new DES $keybin;
                   19812:     }
1.1233    raeburn  19813:     my $plaintext='';
                   19814:     my $cypherlength = length($cyphertext);
                   19815:     my $numchunks = int($cypherlength/32);
                   19816:     for (my $j=0; $j<$numchunks; $j++) {
                   19817:         my $start = $j*32;
                   19818:         my $cypherblock = substr($cyphertext,$start,32);
                   19819:         my $chunk =
                   19820:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19821:         $chunk .=
                   19822:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19823:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19824:         $plaintext .= $chunk;
                   19825:     }
1.1174    raeburn  19826:     return $plaintext;
                   19827: }
                   19828: 
1.1344    raeburn  19829: sub get_requested_shorturls {
1.1309    raeburn  19830:     my ($cdom,$cnum,$navmap) = @_;
                   19831:     return unless (ref($navmap));
1.1344    raeburn  19832:     my ($numnew,$errors);
1.1309    raeburn  19833:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19834:     if (@toshorten) {
                   19835:         my (%maps,%resources,%titles);
                   19836:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19837:                                                                'shorturls',$cdom,$cnum);
                   19838:         if (keys(%resources)) {
1.1344    raeburn  19839:             my %tocreate;
1.1309    raeburn  19840:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19841:                 my $symb = $resources{$item};
                   19842:                 if ($symb) {
                   19843:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19844:                 }
                   19845:             }
1.1344    raeburn  19846:             if (keys(%tocreate)) {
                   19847:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19848:                                                       \%tocreate);
                   19849:             }
1.1309    raeburn  19850:         }
1.1344    raeburn  19851:     }
                   19852:     return ($numnew,$errors);
                   19853: }
                   19854: 
                   19855: sub make_short_symbs {
                   19856:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19857:     my ($numnew,@errors);
                   19858:     if (ref($tocreateref) eq 'HASH') {
                   19859:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19860:         if (keys(%tocreate)) {
                   19861:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19862:             my $su = Short::URL->new(no_vowels => 1);
                   19863:             my $init = '';
                   19864:             my (%newunique,%addcourse,%courseonly,%failed);
                   19865:             # get lock on tiny db
                   19866:             my $now = time;
1.1344    raeburn  19867:             if ($lockuser eq '') {
                   19868:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19869:             }
1.1309    raeburn  19870:             my $lockhash = {
1.1344    raeburn  19871:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19872:                             };
                   19873:             my $tries = 0;
                   19874:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19875:             my ($code,$error);
                   19876:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19877:                 $tries ++;
                   19878:                 sleep 1;
1.1319    raeburn  19879:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19880:             }
                   19881:             if ($gotlock eq 'ok') {
                   19882:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19883:                                        \%addcourse,\%courseonly,\%failed);
                   19884:                 if (keys(%failed)) {
                   19885:                     my $numfailed = scalar(keys(%failed));
                   19886:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19887:                 }
                   19888:                 if (keys(%newunique)) {
                   19889:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19890:                     if ($putres eq 'ok') {
                   19891:                         $numnew = scalar(keys(%newunique));
                   19892:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19893:                         unless ($newputres eq 'ok') {
                   19894:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19895:                         }
                   19896:                     } else {
                   19897:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19898:                     }
                   19899:                 }
                   19900:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19901:                 unless ($dellockres eq 'ok') {
                   19902:                     push(@errors,&mt('error: could not release lockfile'));
                   19903:                 }
                   19904:             } else {
                   19905:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19906:             }
                   19907:             if (keys(%courseonly)) {
                   19908:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19909:                 if ($result ne 'ok') {
                   19910:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19911:                 }
                   19912:             }
                   19913:         }
                   19914:     }
                   19915:     return ($numnew,\@errors);
                   19916: }
                   19917: 
                   19918: sub shorten_symbs {
                   19919:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19920:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19921:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19922:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19923:     my (%possibles,%collisions);
                   19924:     foreach my $key (keys(%{$tocreate})) {
                   19925:         my $num = String::CRC32::crc32($key);
                   19926:         my $tiny = $su->encode($num,$init);
                   19927:         if ($tiny) {
                   19928:             $possibles{$tiny} = $key;
                   19929:         }
                   19930:     }
                   19931:     if (!$init) {
                   19932:         $init = 1;
                   19933:     } else {
                   19934:         $init ++;
                   19935:     }
                   19936:     if (keys(%possibles)) {
                   19937:         my @posstiny = keys(%possibles);
                   19938:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19939:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19940:         if (keys(%currtiny)) {
                   19941:             foreach my $key (keys(%currtiny)) {
                   19942:                 next if ($currtiny{$key} eq '');
                   19943:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19944:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19945:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19946:                         $courseonly->{$tsymb} = $key;
                   19947:                     }
                   19948:                 } else {
                   19949:                     $collisions{$possibles{$key}} = 1;
                   19950:                 }
                   19951:                 delete($possibles{$key});
                   19952:             }
                   19953:         }
                   19954:         foreach my $key (keys(%possibles)) {
                   19955:             $newunique->{$key} = $possibles{$key};
                   19956:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19957:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19958:                 $addcourse->{$tsymb} = $key;
                   19959:             }
                   19960:         }
                   19961:     }
                   19962:     if (keys(%collisions)) {
                   19963:         if ($init <5) {
                   19964:             if (!$init) {
                   19965:                 $init = 1;
                   19966:             } else {
                   19967:                 $init ++;
                   19968:             }
                   19969:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19970:                                    $newunique,$addcourse,$courseonly,$failed);
                   19971:         } else {
                   19972:             foreach my $key (keys(%collisions)) {
                   19973:                 $failed->{$key} = 1;
                   19974:             }
                   19975:         }
                   19976:     }
                   19977:     return $init;
                   19978: }
                   19979: 
1.1328    raeburn  19980: sub is_nonframeable {
1.1329    raeburn  19981:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19982:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19983:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19984: 
                   19985:     $remprotocol = lc($remprotocol);
                   19986:     $remhost = lc($remhost);
                   19987:     my $remport = 80;
                   19988:     if ($remprotocol eq 'https') {
                   19989:         $remport = 443;
                   19990:     }
1.1330    raeburn  19991:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19992:     if ($cached) {
                   19993:         unless ($nocache) {
                   19994:             if ($result) {
                   19995:                 return 1;
                   19996:             } else {
                   19997:                 return 0;
                   19998:             }
                   19999:         }
                   20000:     }
1.1328    raeburn  20001:     my $uselink;
                   20002:     my $request = new HTTP::Request('HEAD',$url);
                   20003:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20004:     if ($response->is_success()) {
                   20005:         my $secpolicy = lc($response->header('content-security-policy'));
                   20006:         my $xframeop = lc($response->header('x-frame-options'));
                   20007:         $secpolicy =~ s/^\s+|\s+$//g;
                   20008:         $xframeop =~ s/^\s+|\s+$//g;
                   20009:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20010:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20011:             my ($origin,$protocol,$port);
                   20012:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20013:                 $port = $ENV{'SERVER_PORT'};
                   20014:             } else {
                   20015:                 $port = 80;
                   20016:             }
                   20017:             if ($absolute eq '') {
                   20018:                 $protocol = 'http:';
                   20019:                 if ($port == 443) {
                   20020:                     $protocol = 'https:';
                   20021:                 }
                   20022:                 $origin = $protocol.'//'.lc($hostname);
                   20023:             } else {
                   20024:                 $origin = lc($absolute);
                   20025:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20026:             }
                   20027:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20028:                 my $framepolicy = $1;
                   20029:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20030:                 my @policies = split(/\s+/,$framepolicy);
                   20031:                 if (@policies) {
                   20032:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20033:                         $uselink = 1;
                   20034:                     } else {
                   20035:                         $uselink = 1;
                   20036:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20037:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20038:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20039:                             undef($uselink);
                   20040:                         }
                   20041:                         if ($uselink) {
                   20042:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20043:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20044:                                     undef($uselink);
                   20045:                                 }
                   20046:                             }
                   20047:                         }
                   20048:                         if ($uselink) {
                   20049:                             my @possok;
                   20050:                             if ($ip ne '') {
                   20051:                                 push(@possok,$ip);
                   20052:                             }
                   20053:                             my $hoststr = '';
                   20054:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20055:                                 if ($hoststr eq '') {
                   20056:                                     $hoststr = $part;
                   20057:                                 } else {
                   20058:                                     $hoststr = "$part.$hoststr";
                   20059:                                 }
                   20060:                                 if ($hoststr eq $hostname) {
                   20061:                                     push(@possok,$hostname);
                   20062:                                 } else {
                   20063:                                     push(@possok,"*.$hoststr");
                   20064:                                 }
                   20065:                             }
                   20066:                             if (@possok) {
                   20067:                                 foreach my $poss (@possok) {
                   20068:                                     last if (!$uselink);
                   20069:                                     foreach my $policy (@policies) {
                   20070:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20071:                                             undef($uselink);
                   20072:                                             last;
                   20073:                                         }
                   20074:                                     }
                   20075:                                 }
                   20076:                             }
                   20077:                         }
                   20078:                     }
                   20079:                 }
                   20080:             } elsif ($xframeop ne '') {
                   20081:                 $uselink = 1;
                   20082:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20083:                 if (@policies) {
                   20084:                     unless (grep(/^deny$/,@policies)) {
                   20085:                         if ($origin ne '') {
                   20086:                             if (grep(/^sameorigin$/,@policies)) {
                   20087:                                 if ($remotehost eq $origin) {
                   20088:                                     undef($uselink);
                   20089:                                 }
                   20090:                             }
                   20091:                             if ($uselink) {
                   20092:                                 foreach my $policy (@policies) {
                   20093:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20094:                                         my $allowfrom = $1;
                   20095:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20096:                                             undef($uselink);
                   20097:                                             last;
                   20098:                                         }
                   20099:                                     }
                   20100:                                 }
                   20101:                             }
                   20102:                         }
                   20103:                     }
                   20104:                 }
                   20105:             }
                   20106:         }
                   20107:     }
1.1329    raeburn  20108:     if ($nocache) {
                   20109:         if ($cached) {
                   20110:             my $devalidate;
                   20111:             if ($uselink && !$result) {
                   20112:                 $devalidate = 1;
                   20113:             } elsif (!$uselink && $result) {
                   20114:                 $devalidate = 1;
                   20115:             }
                   20116:             if ($devalidate) {
                   20117:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20118:             }
                   20119:         }
                   20120:     } else {
                   20121:         if ($uselink) {
                   20122:             $result = 1;
                   20123:         } else {
                   20124:             $result = 0;
                   20125:         }
                   20126:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20127:     }
1.1328    raeburn  20128:     return $uselink;
                   20129: }
                   20130: 
1.1359    raeburn  20131: sub page_menu {
                   20132:     my ($menucolls,$menunum) = @_;
                   20133:     my %menu;
                   20134:     foreach my $item (split(/;/,$menucolls)) {
                   20135:         my ($num,$value) = split(/\%/,$item);
                   20136:         if ($num eq $menunum) {
                   20137:             my @entries = split(/\&/,$value);
                   20138:             foreach my $entry (@entries) {
                   20139:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20140:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20141:                     $menu{$name} = $fields;
                   20142:                 } else {
                   20143:                     my @shown;
                   20144:                     if ($fields =~ /,/) {
                   20145:                         @shown = split(/,/,$fields);
                   20146:                     } else {
                   20147:                         @shown = ($fields);
                   20148:                     }
                   20149:                     if (@shown) {
                   20150:                         foreach my $field (@shown) {
                   20151:                             next if ($field eq '');
                   20152:                             $menu{$field} = 1;
                   20153:                         }
                   20154:                     }
                   20155:                 }
                   20156:             }
                   20157:         }
                   20158:     }
                   20159:     return %menu;
                   20160: }
                   20161: 
1.112     bowersj2 20162: 1;
                   20163: __END__;
1.41      ng       20164: 

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