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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.692.4.14! raeburn     4: # $Id: loncommon.pm,v 1.692.4.13 2009/08/14 17:08:48 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.479     albertel   70: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    71: use DateTime::TimeZone;
1.687     raeburn    72: use DateTime::Locale::Catalog;
1.117     www        73: 
1.517     raeburn    74: # ---------------------------------------------- Designs
                     75: use vars qw(%defaultdesign);
                     76: 
1.22      www        77: my $readit;
                     78: 
1.517     raeburn    79: 
1.157     matthew    80: ##
                     81: ## Global Variables
                     82: ##
1.46      matthew    83: 
1.643     foxr       84: 
                     85: # ----------------------------------------------- SSI with retries:
                     86: #
                     87: 
                     88: =pod
                     89: 
1.648     raeburn    90: =head1 Server Side include with retries:
1.643     foxr       91: 
                     92: =over 4
                     93: 
1.648     raeburn    94: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       95: 
                     96: Performs an ssi with some number of retries.  Retries continue either
                     97: until the result is ok or until the retry count supplied by the
                     98: caller is exhausted.  
                     99: 
                    100: Inputs:
1.648     raeburn   101: 
                    102: =over 4
                    103: 
1.643     foxr      104: resource   - Identifies the resource to insert.
1.648     raeburn   105: 
1.643     foxr      106: retries    - Count of the number of retries allowed.
1.648     raeburn   107: 
1.643     foxr      108: form       - Hash that identifies the rendering options.
                    109: 
1.648     raeburn   110: =back
                    111: 
                    112: Returns:
                    113: 
                    114: =over 4
                    115: 
1.643     foxr      116: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   117: 
1.643     foxr      118: response   - The response from the last attempt (which may or may not have been successful.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: =back
                    123: 
1.643     foxr      124: =cut
                    125: 
                    126: sub ssi_with_retries {
                    127:     my ($resource, $retries, %form) = @_;
                    128: 
                    129: 
                    130:     my $ok = 0;			# True if we got a good response.
                    131:     my $content;
                    132:     my $response;
                    133: 
                    134:     # Try to get the ssi done. within the retries count:
                    135: 
                    136:     do {
                    137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    138: 	$ok      = $response->is_success;
1.650     www       139:         if (!$ok) {
                    140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    141:         }
1.643     foxr      142: 	$retries--;
                    143:     } while (!$ok && ($retries > 0));
                    144: 
                    145:     if (!$ok) {
                    146: 	$content = '';		# On error return an empty content.
                    147:     }
                    148:     return ($content, $response);
                    149: 
                    150: }
                    151: 
                    152: 
                    153: 
1.20      www       154: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  155: my %language;
1.124     www       156: my %supported_language;
1.12      harris41  157: my %cprtag;
1.192     taceyjo1  158: my %scprtag;
1.351     www       159: my %fe; my %fd; my %fm;
1.41      ng        160: my %category_extensions;
1.12      harris41  161: 
1.46      matthew   162: # ---------------------------------------------- Thesaurus variables
1.144     matthew   163: #
                    164: # %Keywords:
                    165: #      A hash used by &keyword to determine if a word is considered a keyword.
                    166: # $thesaurus_db_file 
                    167: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   168: 
                    169: my %Keywords;
                    170: my $thesaurus_db_file;
                    171: 
1.144     matthew   172: #
                    173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    174: # thesaurus.tab, and filecategories.tab.
                    175: #
1.18      www       176: BEGIN {
1.46      matthew   177:     # Variable initialization
                    178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    179:     #
1.22      www       180:     unless ($readit) {
1.12      harris41  181: # ------------------------------------------------------------------- languages
                    182:     {
1.158     raeburn   183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    184:                                    '/language.tab';
                    185:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  186:             while (my $line = <$fh>) {
                    187:                 next if ($line=~/^\#/);
                    188:                 chomp($line);
                    189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
1.158     raeburn   190:                 $language{$key}=$val.' - '.$enc;
                    191:                 if ($sup) {
                    192:                     $supported_language{$key}=$sup;
                    193:                 }
                    194:             }
                    195:             close($fh);
                    196:         }
1.12      harris41  197:     }
                    198: # ------------------------------------------------------------------ copyrights
                    199:     {
1.158     raeburn   200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    201:                                   '/copyright.tab';
                    202:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
                    206:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   207:                 $cprtag{$key}=$val;
                    208:             }
                    209:             close($fh);
                    210:         }
1.12      harris41  211:     }
1.351     www       212: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  213:     {
                    214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    215:                                   '/source_copyright.tab';
                    216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  217:             while (my $line = <$fh>) {
                    218:                 next if ($line =~ /^\#/);
                    219:                 chomp($line);
                    220:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  221:                 $scprtag{$key}=$val;
                    222:             }
                    223:             close($fh);
                    224:         }
                    225:     }
1.63      www       226: 
1.517     raeburn   227: # -------------------------------------------------------------- default domain designs
1.63      www       228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   229:     my $designfile = $designdir.'/default.tab';
                    230:     if ( open (my $fh,"<$designfile") ) {
                    231:         while (my $line = <$fh>) {
                    232:             next if ($line =~ /^\#/);
                    233:             chomp($line);
                    234:             my ($key,$val)=(split(/\=/,$line));
                    235:             if ($val) { $defaultdesign{$key}=$val; }
                    236:         }
                    237:         close($fh);
1.63      www       238:     }
                    239: 
1.15      harris41  240: # ------------------------------------------------------------- file categories
                    241:     {
1.158     raeburn   242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    243:                                   '/filecategories.tab';
                    244:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  245: 	    while (my $line = <$fh>) {
                    246: 		next if ($line =~ /^\#/);
                    247: 		chomp($line);
                    248:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   249:                 push @{$category_extensions{lc($category)}},$extension;
                    250:             }
                    251:             close($fh);
                    252:         }
                    253: 
1.15      harris41  254:     }
1.12      harris41  255: # ------------------------------------------------------------------ file types
                    256:     {
1.158     raeburn   257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    258:                '/filetypes.tab';
                    259:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  260:             while (my $line = <$fh>) {
                    261: 		next if ($line =~ /^\#/);
                    262: 		chomp($line);
                    263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   264:                 if ($descr ne '') {
                    265:                     $fe{$ending}=lc($emb);
                    266:                     $fd{$ending}=$descr;
1.351     www       267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   268:                 }
                    269:             }
                    270:             close($fh);
                    271:         }
1.12      harris41  272:     }
1.22      www       273:     &Apache::lonnet::logthis(
1.46      matthew   274:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       275:     $readit=1;
1.46      matthew   276:     }  # end of unless($readit) 
1.32      matthew   277:     
                    278: }
1.112     bowersj2  279: 
1.42      matthew   280: ###############################################################
                    281: ##           HTML and Javascript Helper Functions            ##
                    282: ###############################################################
                    283: 
                    284: =pod 
                    285: 
1.112     bowersj2  286: =head1 HTML and Javascript Functions
1.42      matthew   287: 
1.112     bowersj2  288: =over 4
                    289: 
1.648     raeburn   290: =item * &browser_and_searcher_javascript()
1.112     bowersj2  291: 
                    292: X<browsing, javascript>X<searching, javascript>Returns a string
                    293: containing javascript with two functions, C<openbrowser> and
                    294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    295: tags.
1.42      matthew   296: 
1.648     raeburn   297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   298: 
                    299: inputs: formname, elementname, only, omit
                    300: 
                    301: formname and elementname indicate the name of the html form and name of
                    302: the element that the results of the browsing selection are to be placed in. 
                    303: 
                    304: Specifying 'only' will restrict the browser to displaying only files
1.185     www       305: with the given extension.  Can be a comma separated list.
1.42      matthew   306: 
                    307: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       308: with the given extension.  Can be a comma separated list.
1.42      matthew   309: 
1.648     raeburn   310: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   311: 
                    312: Inputs: formname, elementname
                    313: 
                    314: formname and elementname specify the name of the html form and the name
                    315: of the element the selection from the search results will be placed in.
1.542     raeburn   316: 
1.42      matthew   317: =cut
                    318: 
                    319: sub browser_and_searcher_javascript {
1.199     albertel  320:     my ($mode)=@_;
                    321:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  322:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   323:     return <<END;
1.219     albertel  324: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   325:     var editbrowser = null;
1.135     albertel  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       327:         var url = '$resurl/?';
1.42      matthew   328:         if (editbrowser == null) {
                    329:             url += 'launch=1&';
                    330:         }
                    331:         url += 'catalogmode=interactive&';
1.199     albertel  332:         url += 'mode=$mode&';
1.611     albertel  333:         url += 'inhibitmenu=yes&';
1.42      matthew   334:         url += 'form=' + formname + '&';
                    335:         if (only != null) {
                    336:             url += 'only=' + only + '&';
1.217     albertel  337:         } else {
                    338:             url += 'only=&';
                    339: 	}
1.42      matthew   340:         if (omit != null) {
                    341:             url += 'omit=' + omit + '&';
1.217     albertel  342:         } else {
                    343:             url += 'omit=&';
                    344: 	}
1.135     albertel  345:         if (titleelement != null) {
                    346:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  347:         } else {
                    348: 	    url += 'titleelement=&';
                    349: 	}
1.42      matthew   350:         url += 'element=' + elementname + '';
                    351:         var title = 'Browser';
1.435     albertel  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   353:         options += ',width=700,height=600';
                    354:         editbrowser = open(url,title,options,'1');
                    355:         editbrowser.focus();
                    356:     }
                    357:     var editsearcher;
1.135     albertel  358:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   359:         var url = '/adm/searchcat?';
                    360:         if (editsearcher == null) {
                    361:             url += 'launch=1&';
                    362:         }
                    363:         url += 'catalogmode=interactive&';
1.199     albertel  364:         url += 'mode=$mode&';
1.42      matthew   365:         url += 'form=' + formname + '&';
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Search';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editsearcher = open(url,title,options,'1');
                    376:         editsearcher.focus();
                    377:     }
1.219     albertel  378: // END LON-CAPA Internal -->
1.42      matthew   379: END
1.170     www       380: }
                    381: 
                    382: sub lastresurl {
1.258     albertel  383:     if ($env{'environment.lastresurl'}) {
                    384: 	return $env{'environment.lastresurl'}
1.170     www       385:     } else {
                    386: 	return '/res';
                    387:     }
                    388: }
                    389: 
                    390: sub storeresurl {
                    391:     my $resurl=&Apache::lonnet::clutter(shift);
                    392:     unless ($resurl=~/^\/res/) { return 0; }
                    393:     $resurl=~s/\/$//;
                    394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       396:     return 1;
1.42      matthew   397: }
                    398: 
1.74      www       399: sub studentbrowser_javascript {
1.111     www       400:    unless (
1.258     albertel  401:             (($env{'request.course.id'}) && 
1.302     albertel  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    404: 					  '/'.$env{'request.course.sec'})
                    405: 	      ))
1.258     albertel  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       407:           ) { return ''; }  
1.74      www       408:    return (<<'ENDSTDBRW');
1.692.4.2  raeburn   409: <script type="text/javascript" language="Javascript">
1.692.4.4  raeburn   410: // <![CDATA[
1.74      www       411:     var stdeditbrowser;
1.692.4.2  raeburn   412:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
1.74      www       413:         var url = '/adm/pickstudent?';
                    414:         var filter;
1.558     albertel  415: 	if (!ignorefilter) {
                    416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    417: 	}
1.74      www       418:         if (filter != null) {
                    419:            if (filter != '') {
                    420:                url += 'filter='+filter+'&';
                    421: 	   }
                    422:         }
                    423:         url += 'form=' + formname + '&unameelement='+uname+
                    424:                                     '&udomelement='+udom;
1.111     www       425: 	if (roleflag) { url+="&roles=1"; }
1.692.4.2  raeburn   426:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       427:         var title = 'Student_Browser';
1.74      www       428:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    429:         options += ',width=700,height=600';
                    430:         stdeditbrowser = open(url,title,options,'1');
                    431:         stdeditbrowser.focus();
                    432:     }
1.692.4.4  raeburn   433: // ]]>
1.74      www       434: </script>
                    435: ENDSTDBRW
                    436: }
1.42      matthew   437: 
1.74      www       438: sub selectstudent_link {
1.692.4.2  raeburn   439:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
                    440:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
1.258     albertel  441:    if ($env{'request.course.id'}) {  
1.302     albertel  442:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    443: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    444: 					'/'.$env{'request.course.sec'})) {
1.111     www       445: 	   return '';
                    446:        }
1.692.4.2  raeburn   447:        if ($courseadvonly)  {
                    448:            $callargs .= ",'',1,1";
                    449:        }
                    450:        return '<span class="LC_nobreak">'.
                    451:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    452:               &mt('Select User').'</a></span>';
1.74      www       453:    }
1.258     albertel  454:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.692.4.2  raeburn   455:        $callargs .= ",1";
                    456:        return '<span class="LC_nobreak">'.
                    457:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    458:               &mt('Select User').'</a></span>';
1.111     www       459:    }
                    460:    return '';
1.91      www       461: }
                    462: 
1.653     raeburn   463: sub authorbrowser_javascript {
                    464:     return <<"ENDAUTHORBRW";
                    465: <script type="text/javascript">
1.692.4.4  raeburn   466: // <![CDATA[
1.653     raeburn   467: var stdeditbrowser;
                    468: 
                    469: function openauthorbrowser(formname,udom) {
                    470:     var url = '/adm/pickauthor?';
                    471:     url += 'form='+formname+'&roledom='+udom;
                    472:     var title = 'Author_Browser';
                    473:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    474:     options += ',width=700,height=600';
                    475:     stdeditbrowser = open(url,title,options,'1');
                    476:     stdeditbrowser.focus();
                    477: }
1.692.4.4  raeburn   478: // ]]>
1.653     raeburn   479: </script>
                    480: ENDAUTHORBRW
                    481: }
                    482: 
1.91      www       483: sub coursebrowser_javascript {
1.468     raeburn   484:     my ($domainfilter,$sec_element,$formname)=@_;
1.692.4.6  raeburn   485:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Community - for which you wish to add/modify a user role');
1.692.4.9  raeburn   486:     my $id_functions = &javascript_index_functions();
                    487:     my $output = '
1.692.4.2  raeburn   488: <script type="text/javascript" language="JavaScript">
1.692.4.4  raeburn   489: // <![CDATA[
1.468     raeburn   490:     var stdeditbrowser;'."\n";
1.692.4.9  raeburn   491: 
                    492:     $output .= <<"ENDSTDBRW";
1.377     raeburn   493:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
1.91      www       494:         var url = '/adm/pickcourse?';
1.692.4.9  raeburn   495:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  496:         if (domainfilter != null) {
                    497:            if (domainfilter != '') {
                    498:                url += 'domainfilter='+domainfilter+'&';
                    499: 	   }
                    500:         }
1.91      www       501:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  502: 	                            '&cdomelement='+udom+
                    503:                                     '&cnameelement='+desc;
1.468     raeburn   504:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   505:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   506:                 url += '&roleelement='+extra_element;
                    507:                 if (domainfilter == null || domainfilter == '') {
                    508:                     url += '&domainfilter='+extra_element;
                    509:                 }
1.234     raeburn   510:             }
1.468     raeburn   511:             else {
                    512:                 if (formname == 'portform') {
                    513:                     url += '&setroles='+extra_element;
                    514:                 }
                    515:             }     
1.230     raeburn   516:         }
1.692.4.7  raeburn   517:         if (formname == 'ccrs') {
                    518:             var ownername = document.forms[formid].ccuname.value;
                    519:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    520:             url += '&cloner='+ownername+':'+ownerdom;
                    521:         }
1.293     raeburn   522:         if (multflag !=null && multflag != '') {
                    523:             url += '&multiple='+multflag;
                    524:         }
1.692.4.6  raeburn   525:         if (crstype == 'Course/Community') {
1.377     raeburn   526:             if (formname == 'cu') {
                    527:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
                    528:                 if (crstype == "") {
                    529:                     alert("$crs_or_grp_alert");
                    530:                     return;
                    531:                 }
                    532:             }
                    533:         }
                    534:         if (crstype !=null && crstype != '') {
                    535:             url += '&type='+crstype;
                    536:         }
1.102     www       537:         var title = 'Course_Browser';
1.91      www       538:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    539:         options += ',width=700,height=600';
                    540:         stdeditbrowser = open(url,title,options,'1');
                    541:         stdeditbrowser.focus();
                    542:     }
1.692.4.9  raeburn   543: $id_functions
1.91      www       544: ENDSTDBRW
1.468     raeburn   545:     if ($sec_element ne '') {
                    546:         $output .= &setsec_javascript($sec_element,$formname);
                    547:     }
                    548:     $output .= '
1.692.4.4  raeburn   549: // ]]>
1.468     raeburn   550: </script>';
                    551:     return $output;
                    552: }
                    553: 
1.692.4.9  raeburn   554: sub javascript_index_functions {
                    555:     return <<"ENDJS";
                    556: 
                    557: function getFormIdByName(formname) {
                    558:     for (var i=0;i<document.forms.length;i++) {
                    559:         if (document.forms[i].name == formname) {
                    560:             return i;
                    561:         }
                    562:     }
                    563:     return -1;
                    564: }
                    565: 
                    566: function getIndexByName(formid,item) {
                    567:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    568:         if (document.forms[formid].elements[i].name == item) {
                    569:             return i;
                    570:         }
                    571:     }
                    572:     return -1;
                    573: }
                    574: 
                    575: function getDomainFromSelectbox(formname,udom) {
                    576:     var userdom;
                    577:     var formid = getFormIdByName(formname);
                    578:     if (formid > -1) {
                    579:         var domid = getIndexByName(formid,udom);
                    580:         if (domid > -1) {
                    581:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    582:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    583:             }
                    584:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    585:                 userdom=document.forms[formid].elements[domid].value;
                    586:             }
                    587:         }
                    588:     }
                    589:     return userdom;
                    590: }
                    591: 
                    592: ENDJS
                    593: 
                    594: }
                    595: 
                    596: sub userbrowser_javascript {
                    597:     my $id_functions = &javascript_index_functions();
                    598:     return <<"ENDUSERBRW";
                    599: 
                    600: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom) {
                    601:     var url = '/adm/pickuser?';
                    602:     var userdom = getDomainFromSelectbox(formname,udom);
                    603:     if (userdom != null) {
                    604:        if (userdom != '') {
                    605:            url += 'srchdom='+userdom+'&';
                    606:        }
                    607:     }
                    608:     url += 'form=' + formname + '&unameelement='+uname+
                    609:                                 '&udomelement='+udom+
                    610:                                 '&ulastelement='+ulast+
                    611:                                 '&ufirstelement='+ufirst+
                    612:                                 '&uemailelement='+uemail+
                    613:                                 '&hideudomelement='+hideudom+
                    614:                                 '&coursedom='+crsdom;
                    615:     var title = 'User_Browser';
                    616:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    617:     options += ',width=700,height=600';
                    618:     var stdeditbrowser = open(url,title,options,'1');
                    619:     stdeditbrowser.focus();
                    620: }
                    621: 
                    622: function fix_domain (formname,udom,origdom) {
                    623:     var formid = getFormIdByName(formname);
                    624:     if (formid > -1) {
                    625:         var domid = getIndexByName(formid,udom);
                    626:         var hidedomid = getIndexByName(formid,origdom);
                    627:         if (hidedomid > -1) {
                    628:             var fixeddom = document.forms[formid].elements[hidedomid].value;
                    629:             if (domid > -1) {
                    630:                 var slct = document.forms[formid].elements[domid];
                    631:                 if (slct.type == 'select-one') {
                    632:                     var i;
                    633:                     for (i=0;i<slct.length;i++) {
                    634:                         if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    635:                     }
                    636:                 }
                    637:                 if (slct.type == 'hidden') {
                    638:                     slct.value = fixeddom;
                    639:                 }
                    640:             }
                    641:         }
                    642:     }
                    643:     return;
                    644: }
                    645: 
                    646: $id_functions
                    647: ENDUSERBRW
                    648: }
                    649: 
                    650: 
1.468     raeburn   651: sub setsec_javascript {
                    652:     my ($sec_element,$formname) = @_;
                    653:     my $setsections = qq|
                    654: function setSect(sectionlist) {
1.629     raeburn   655:     var sectionsArray = new Array();
                    656:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    657:         sectionsArray = sectionlist.split(",");
                    658:     }
1.468     raeburn   659:     var numSections = sectionsArray.length;
                    660:     document.$formname.$sec_element.length = 0;
                    661:     if (numSections == 0) {
                    662:         document.$formname.$sec_element.multiple=false;
                    663:         document.$formname.$sec_element.size=1;
                    664:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    665:     } else {
                    666:         if (numSections == 1) {
                    667:             document.$formname.$sec_element.multiple=false;
                    668:             document.$formname.$sec_element.size=1;
                    669:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    670:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    671:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    672:         } else {
                    673:             for (var i=0; i<numSections; i++) {
                    674:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    675:             }
                    676:             document.$formname.$sec_element.multiple=true
                    677:             if (numSections < 3) {
                    678:                 document.$formname.$sec_element.size=numSections;
                    679:             } else {
                    680:                 document.$formname.$sec_element.size=3;
                    681:             }
                    682:             document.$formname.$sec_element.options[0].selected = false
                    683:         }
                    684:     }
1.91      www       685: }
1.468     raeburn   686: |;
                    687:     return $setsections;
                    688: }
                    689: 
1.91      www       690: 
                    691: sub selectcourse_link {
1.377     raeburn   692:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
1.692.4.6  raeburn   693:    my $linktext = &mt('Select Course');
                    694:    if ($selecttype eq 'Community') {
                    695:        $linktext = &mt('Select Community');
                    696:    }
1.692.4.2  raeburn   697:    return '<span class="LC_nobreak">'
                    698:          ."<a href='"
                    699:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    700:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
                    701:          .'","'.$multflag.'","'.$selecttype.'");'
1.692.4.6  raeburn   702:          ."'>".$linktext.'</a>'
1.692.4.2  raeburn   703:          .'</span>';
1.74      www       704: }
1.42      matthew   705: 
1.653     raeburn   706: sub selectauthor_link {
                    707:    my ($form,$udom)=@_;
                    708:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    709:           &mt('Select Author').'</a>';
                    710: }
                    711: 
1.692.4.9  raeburn   712: sub selectuser_link {
                    713:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
                    714:         $coursedom,$linktext) = @_;
                    715:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
                    716:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom'".
                    717:            ');">'.$linktext.'</a>';
                    718: }
                    719: 
1.273     raeburn   720: sub check_uncheck_jscript {
                    721:     my $jscript = <<"ENDSCRT";
                    722: function checkAll(field) {
                    723:     if (field.length > 0) {
                    724:         for (i = 0; i < field.length; i++) {
                    725:             field[i].checked = true ;
                    726:         }
                    727:     } else {
                    728:         field.checked = true
                    729:     }
                    730: }
                    731:  
                    732: function uncheckAll(field) {
                    733:     if (field.length > 0) {
                    734:         for (i = 0; i < field.length; i++) {
                    735:             field[i].checked = false ;
1.543     albertel  736:         }
                    737:     } else {
1.273     raeburn   738:         field.checked = false ;
                    739:     }
                    740: }
                    741: ENDSCRT
                    742:     return $jscript;
                    743: }
                    744: 
1.656     www       745: sub select_timezone {
1.659     raeburn   746:    my ($name,$selected,$onchange,$includeempty)=@_;
                    747:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    748:    if ($includeempty) {
                    749:        $output .= '<option value=""';
                    750:        if (($selected eq '') || ($selected eq 'local')) {
                    751:            $output .= ' selected="selected" ';
                    752:        }
                    753:        $output .= '> </option>';
                    754:    }
1.657     raeburn   755:    my @timezones = DateTime::TimeZone->all_names;
                    756:    foreach my $tzone (@timezones) {
                    757:        $output.= '<option value="'.$tzone.'"';
                    758:        if ($tzone eq $selected) {
                    759:            $output.=' selected="selected"';
                    760:        }
                    761:        $output.=">$tzone</option>\n";
1.656     www       762:    }
                    763:    $output.="</select>";
                    764:    return $output;
                    765: }
1.273     raeburn   766: 
1.687     raeburn   767: sub select_datelocale {
                    768:     my ($name,$selected,$onchange,$includeempty)=@_;
                    769:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    770:     if ($includeempty) {
                    771:         $output .= '<option value=""';
                    772:         if ($selected eq '') {
                    773:             $output .= ' selected="selected" ';
                    774:         }
                    775:         $output .= '> </option>';
                    776:     }
                    777:     my (@possibles,%locale_names);
                    778:     my @locales = DateTime::Locale::Catalog::Locales;
                    779:     foreach my $locale (@locales) {
                    780:         if (ref($locale) eq 'HASH') {
                    781:             my $id = $locale->{'id'};
                    782:             if ($id ne '') {
                    783:                 my $en_terr = $locale->{'en_territory'};
                    784:                 my $native_terr = $locale->{'native_territory'};
1.692.4.1  raeburn   785:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   786:                 if (grep(/^en$/,@languages) || !@languages) {
                    787:                     if ($en_terr ne '') {
                    788:                         $locale_names{$id} = '('.$en_terr.')';
                    789:                     } elsif ($native_terr ne '') {
                    790:                         $locale_names{$id} = $native_terr;
                    791:                     }
                    792:                 } else {
                    793:                     if ($native_terr ne '') {
                    794:                         $locale_names{$id} = $native_terr.' ';
                    795:                     } elsif ($en_terr ne '') {
                    796:                         $locale_names{$id} = '('.$en_terr.')';
                    797:                     }
                    798:                 }
                    799:                 push (@possibles,$id);
                    800:             }
                    801:         }
                    802:     }
                    803:     foreach my $item (sort(@possibles)) {
                    804:         $output.= '<option value="'.$item.'"';
                    805:         if ($item eq $selected) {
                    806:             $output.=' selected="selected"';
                    807:         }
                    808:         $output.=">$item";
                    809:         if ($locale_names{$item} ne '') {
                    810:             $output.="  $locale_names{$item}</option>\n";
                    811:         }
                    812:         $output.="</option>\n";
                    813:     }
                    814:     $output.="</select>";
                    815:     return $output;
                    816: }
                    817: 
1.692.4.2  raeburn   818: sub select_language {
                    819:     my ($name,$selected,$includeempty) = @_;
                    820:     my %langchoices;
                    821:     if ($includeempty) {
                    822:         %langchoices = ('' => 'No language preference');
                    823:     }
                    824:     foreach my $id (&languageids()) {
                    825:         my $code = &supportedlanguagecode($id);
                    826:         if ($code) {
                    827:             $langchoices{$code} = &plainlanguagedescription($id);
                    828:         }
                    829:     }
                    830:     return &select_form($selected,$name,%langchoices);
                    831: }
                    832: 
1.42      matthew   833: =pod
1.36      matthew   834: 
1.648     raeburn   835: =item * &linked_select_forms(...)
1.36      matthew   836: 
                    837: linked_select_forms returns a string containing a <script></script> block
                    838: and html for two <select> menus.  The select menus will be linked in that
                    839: changing the value of the first menu will result in new values being placed
                    840: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn   841: order unless a defined order is provided.
1.36      matthew   842: 
                    843: linked_select_forms takes the following ordered inputs:
                    844: 
                    845: =over 4
                    846: 
1.112     bowersj2  847: =item * $formname, the name of the <form> tag
1.36      matthew   848: 
1.112     bowersj2  849: =item * $middletext, the text which appears between the <select> tags
1.36      matthew   850: 
1.112     bowersj2  851: =item * $firstdefault, the default value for the first menu
1.36      matthew   852: 
1.112     bowersj2  853: =item * $firstselectname, the name of the first <select> tag
1.36      matthew   854: 
1.112     bowersj2  855: =item * $secondselectname, the name of the second <select> tag
1.36      matthew   856: 
1.112     bowersj2  857: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew   858: 
1.609     raeburn   859: =item * $menuorder, the order of values in the first menu
                    860: 
1.41      ng        861: =back 
                    862: 
1.36      matthew   863: Below is an example of such a hash.  Only the 'text', 'default', and 
                    864: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                    865: values for the first select menu.  The text that coincides with the 
1.41      ng        866: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   867: and text for the second menu are given in the hash pointed to by 
                    868: $menu{$choice1}->{'select2'}.  
                    869: 
1.112     bowersj2  870:  my %menu = ( A1 => { text =>"Choice A1" ,
                    871:                        default => "B3",
                    872:                        select2 => { 
                    873:                            B1 => "Choice B1",
                    874:                            B2 => "Choice B2",
                    875:                            B3 => "Choice B3",
                    876:                            B4 => "Choice B4"
1.609     raeburn   877:                            },
                    878:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2  879:                    },
                    880:                A2 => { text =>"Choice A2" ,
                    881:                        default => "C2",
                    882:                        select2 => { 
                    883:                            C1 => "Choice C1",
                    884:                            C2 => "Choice C2",
                    885:                            C3 => "Choice C3"
1.609     raeburn   886:                            },
                    887:                        order => ['C2','C1','C3'],
1.112     bowersj2  888:                    },
                    889:                A3 => { text =>"Choice A3" ,
                    890:                        default => "D6",
                    891:                        select2 => { 
                    892:                            D1 => "Choice D1",
                    893:                            D2 => "Choice D2",
                    894:                            D3 => "Choice D3",
                    895:                            D4 => "Choice D4",
                    896:                            D5 => "Choice D5",
                    897:                            D6 => "Choice D6",
                    898:                            D7 => "Choice D7"
1.609     raeburn   899:                            },
                    900:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2  901:                    }
                    902:                );
1.36      matthew   903: 
                    904: =cut
                    905: 
                    906: sub linked_select_forms {
                    907:     my ($formname,
                    908:         $middletext,
                    909:         $firstdefault,
                    910:         $firstselectname,
                    911:         $secondselectname, 
1.609     raeburn   912:         $hashref,
                    913:         $menuorder,
1.36      matthew   914:         ) = @_;
                    915:     my $second = "document.$formname.$secondselectname";
                    916:     my $first = "document.$formname.$firstselectname";
                    917:     # output the javascript to do the changing
                    918:     my $result = '';
1.692.4.2  raeburn   919:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.692.4.4  raeburn   920:     $result.="// <![CDATA[\n";
1.36      matthew   921:     $result.="var select2data = new Object();\n";
                    922:     $" = '","';
                    923:     my $debug = '';
                    924:     foreach my $s1 (sort(keys(%$hashref))) {
                    925:         $result.="select2data.d_$s1 = new Object();\n";        
                    926:         $result.="select2data.d_$s1.def = new String('".
                    927:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn   928:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew   929:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn   930:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                    931:             @s2values = @{$hashref->{$s1}->{'order'}};
                    932:         }
1.36      matthew   933:         $result.="\"@s2values\");\n";
                    934:         $result.="select2data.d_$s1.texts = new Array(";        
                    935:         my @s2texts;
                    936:         foreach my $value (@s2values) {
                    937:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                    938:         }
                    939:         $result.="\"@s2texts\");\n";
                    940:     }
                    941:     $"=' ';
                    942:     $result.= <<"END";
                    943: 
                    944: function select1_changed() {
                    945:     // Determine new choice
                    946:     var newvalue = "d_" + $first.value;
                    947:     // update select2
                    948:     var values     = select2data[newvalue].values;
                    949:     var texts      = select2data[newvalue].texts;
                    950:     var select2def = select2data[newvalue].def;
                    951:     var i;
                    952:     // out with the old
                    953:     for (i = 0; i < $second.options.length; i++) {
                    954:         $second.options[i] = null;
                    955:     }
                    956:     // in with the nuclear
                    957:     for (i=0;i<values.length; i++) {
                    958:         $second.options[i] = new Option(values[i]);
1.143     matthew   959:         $second.options[i].value = values[i];
1.36      matthew   960:         $second.options[i].text = texts[i];
                    961:         if (values[i] == select2def) {
                    962:             $second.options[i].selected = true;
                    963:         }
                    964:     }
                    965: }
1.692.4.4  raeburn   966: // ]]>
1.36      matthew   967: </script>
                    968: END
                    969:     # output the initial values for the selection lists
                    970:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1.609     raeburn   971:     my @order = sort(keys(%{$hashref}));
                    972:     if (ref($menuorder) eq 'ARRAY') {
                    973:         @order = @{$menuorder};
                    974:     }
                    975:     foreach my $value (@order) {
1.36      matthew   976:         $result.="    <option value=\"$value\" ";
1.253     albertel  977:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www       978:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew   979:     }
                    980:     $result .= "</select>\n";
                    981:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                    982:     $result .= $middletext;
                    983:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                    984:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn   985:     
                    986:     my @secondorder = sort(keys(%select2));
                    987:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                    988:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                    989:     }
                    990:     foreach my $value (@secondorder) {
1.36      matthew   991:         $result.="    <option value=\"$value\" ";        
1.253     albertel  992:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www       993:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew   994:     }
                    995:     $result .= "</select>\n";
                    996:     #    return $debug;
                    997:     return $result;
                    998: }   #  end of sub linked_select_forms {
                    999: 
1.45      matthew  1000: =pod
1.44      bowersj2 1001: 
1.648     raeburn  1002: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
1.44      bowersj2 1003: 
1.112     bowersj2 1004: Returns a string corresponding to an HTML link to the given help
                   1005: $topic, where $topic corresponds to the name of a .tex file in
                   1006: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1007: spaces. 
                   1008: 
                   1009: $text will optionally be linked to the same topic, allowing you to
                   1010: link text in addition to the graphic. If you do not want to link
                   1011: text, but wish to specify one of the later parameters, pass an
                   1012: empty string. 
                   1013: 
                   1014: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1015: the link will not open a new window. If false, the link will open
                   1016: a new window using Javascript. (Default is false.) 
                   1017: 
                   1018: $width and $height are optional numerical parameters that will
                   1019: override the width and height of the popped up window, which may
                   1020: be useful for certain help topics with big pictures included. 
1.44      bowersj2 1021: 
                   1022: =cut
                   1023: 
                   1024: sub help_open_topic {
1.48      bowersj2 1025:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                   1026:     $text = "" if (not defined $text);
1.44      bowersj2 1027:     $stayOnPage = 0 if (not defined $stayOnPage);
1.552     banghart 1028:     if ($env{'browser.interface'} eq 'textual') {
1.79      www      1029: 	$stayOnPage=1;
                   1030:     }
1.44      bowersj2 1031:     $width = 350 if (not defined $width);
                   1032:     $height = 400 if (not defined $height);
                   1033:     my $filename = $topic;
                   1034:     $filename =~ s/ /_/g;
                   1035: 
1.48      bowersj2 1036:     my $template = "";
                   1037:     my $link;
1.572     banghart 1038:     
1.159     www      1039:     $topic=~s/\W/\_/g;
1.44      bowersj2 1040: 
1.572     banghart 1041:     if (!$stayOnPage) {
1.72      bowersj2 1042: 	$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 1043:     } else {
1.48      bowersj2 1044: 	$link = "/adm/help/${filename}.hlp";
                   1045:     }
                   1046: 
                   1047:     # Add the text
1.572     banghart 1048:     if ($text ne "") {
1.77      www      1049: 	$template .= 
1.572     banghart 1050:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.691     bisitz   1051:             "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2 1052:     }
                   1053: 
                   1054:     # Add the graphic
1.179     matthew  1055:     my $title = &mt('Online Help');
1.667     raeburn  1056:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.692.4.2  raeburn  1057:     $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
                   1058:                  '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
                   1059:                  '" title="'.$title.'" /></a>';
                   1060:     if ($text ne '') {
                   1061:         $template.='</span></td></tr></table>';
                   1062:     }
1.44      bowersj2 1063:     return $template;
                   1064: 
1.106     bowersj2 1065: }
                   1066: 
                   1067: # This is a quicky function for Latex cheatsheet editing, since it 
                   1068: # appears in at least four places
                   1069: sub helpLatexCheatsheet {
1.692.4.2  raeburn  1070:     my ($topic,$text,$not_author) = @_;
                   1071:     my $out;
1.106     bowersj2 1072:     my $addOther = '';
1.692.4.3  raeburn  1073:     if ($topic) {
1.692.4.2  raeburn  1074: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
1.106     bowersj2 1075: 						       undef, undef, 600) .
                   1076: 							   '</td><td>';
                   1077:     }
1.692.4.2  raeburn  1078:     $out = '<table><tr><td>'.
                   1079:            $addOther .
                   1080:            &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
                   1081:                                                undef,undef,600).
                   1082:            '</td><td>'.
                   1083:            &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
                   1084:                                                undef,undef,600).
                   1085:            '</td>';
                   1086:     unless ($not_author) {
                   1087:         $out .= '<td>'.
                   1088:                 &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
                   1089:                                                     undef,undef,600).
                   1090:                 '</td>';
                   1091:     }
                   1092:     $out .= '</tr></table>';
                   1093:     return $out;
1.172     www      1094: }
                   1095: 
1.430     albertel 1096: sub general_help {
                   1097:     my $helptopic='Student_Intro';
                   1098:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1099: 	$helptopic='Authoring_Intro';
                   1100:     } elsif ($env{'request.role'}=~/^cc/) {
                   1101: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1102:     } elsif ($env{'request.role'}=~/^dc/) {
                   1103:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1104:     }
                   1105:     return $helptopic;
                   1106: }
                   1107: 
                   1108: sub update_help_link {
                   1109:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1110:     my $origurl = $ENV{'REQUEST_URI'};
                   1111:     $origurl=~s|^/~|/priv/|;
                   1112:     my $timestamp = time;
                   1113:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1114:         $$datum = &escape($$datum);
                   1115:     }
                   1116: 
                   1117:     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";
                   1118:     my $output .= <<"ENDOUTPUT";
                   1119: <script type="text/javascript">
1.692.4.4  raeburn  1120: // <![CDATA[
1.430     albertel 1121: banner_link = '$banner_link';
1.692.4.4  raeburn  1122: // ]]>
1.430     albertel 1123: </script>
                   1124: ENDOUTPUT
                   1125:     return $output;
                   1126: }
                   1127: 
                   1128: # now just updates the help link and generates a blue icon
1.193     raeburn  1129: sub help_open_menu {
1.430     albertel 1130:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1131: 	= @_;    
1.430     albertel 1132:     $stayOnPage = 0 if (not defined $stayOnPage);
1.572     banghart 1133:     # only use pop-up help (stayOnPage == 0)
1.552     banghart 1134:     # if environment.remote is on (using remote control UI)
1.572     banghart 1135:     if ($env{'browser.interface'} eq 'textual' ||
                   1136:     	$env{'environment.remote'} eq 'off' ) {
1.552     banghart 1137:         $stayOnPage=1;
1.430     albertel 1138:     }
                   1139:     my $output;
                   1140:     if ($component_help) {
                   1141: 	if (!$text) {
                   1142: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1143: 				       $width,$height);
                   1144: 	} else {
                   1145: 	    my $help_text;
                   1146: 	    $help_text=&unescape($topic);
                   1147: 	    $output='<table><tr><td>'.
                   1148: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1149: 				 $width,$height).'</td></tr></table>';
                   1150: 	}
                   1151:     }
                   1152:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1153:     return $output.$banner_link;
                   1154: }
                   1155: 
                   1156: sub top_nav_help {
                   1157:     my ($text) = @_;
1.436     albertel 1158:     $text = &mt($text);
1.572     banghart 1159:     my $stay_on_page = 
1.436     albertel 1160: 	($env{'browser.interface'}  eq 'textual' ||
                   1161: 	 $env{'environment.remote'} eq 'off' );
1.572     banghart 1162:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1163: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1164:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1165: 
1.201     raeburn  1166:     my $title = &mt('Get help');
1.436     albertel 1167: 
                   1168:     return <<"END";
                   1169: $banner_link
                   1170:  <a href="$link" title="$title">$text</a>
                   1171: END
                   1172: }
                   1173: 
                   1174: sub help_menu_js {
                   1175:     my ($text) = @_;
                   1176: 
                   1177:     my $stayOnPage = 
                   1178: 	($env{'browser.interface'}  eq 'textual' ||
                   1179: 	 $env{'environment.remote'} eq 'off' );
                   1180: 
                   1181:     my $width = 620;
                   1182:     my $height = 600;
1.430     albertel 1183:     my $helptopic=&general_help();
                   1184:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1185:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1186:     my $start_page =
                   1187:         &Apache::loncommon::start_page('Help Menu', undef,
                   1188: 				       {'frameset'    => 1,
                   1189: 					'js_ready'    => 1,
                   1190: 					'add_entries' => {
                   1191: 					    'border' => '0',
1.579     raeburn  1192: 					    'rows'   => "110,*",},});
1.331     albertel 1193:     my $end_page =
                   1194:         &Apache::loncommon::end_page({'frameset' => 1,
                   1195: 				      'js_ready' => 1,});
                   1196: 
1.436     albertel 1197:     my $template .= <<"ENDTEMPLATE";
                   1198: <script type="text/javascript">
1.253     albertel 1199: // <![CDATA[
1.692.4.10  raeburn  1200: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1201: var banner_link = '';
1.243     raeburn  1202: function helpMenu(target) {
                   1203:     var caller = this;
                   1204:     if (target == 'open') {
                   1205:         var newWindow = null;
                   1206:         try {
1.262     albertel 1207:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1208:         }
                   1209:         catch(error) {
                   1210:             writeHelp(caller);
                   1211:             return;
                   1212:         }
                   1213:         if (newWindow) {
                   1214:             caller = newWindow;
                   1215:         }
1.193     raeburn  1216:     }
1.243     raeburn  1217:     writeHelp(caller);
                   1218:     return;
                   1219: }
                   1220: function writeHelp(caller) {
1.430     albertel 1221:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1.243     raeburn  1222:     caller.document.close()
                   1223:     caller.focus()
1.193     raeburn  1224: }
1.219     albertel 1225: // END LON-CAPA Internal -->
1.692.4.10  raeburn  1226: // ]]>
1.436     albertel 1227: </script>
1.193     raeburn  1228: ENDTEMPLATE
                   1229:     return $template;
                   1230: }
                   1231: 
1.172     www      1232: sub help_open_bug {
                   1233:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1234:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1235:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1236:     $text = "" if (not defined $text);
                   1237:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1238:     if ($env{'browser.interface'} eq 'textual' ||
                   1239: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1240: 	$stayOnPage=1;
                   1241:     }
1.184     albertel 1242:     $width = 600 if (not defined $width);
                   1243:     $height = 600 if (not defined $height);
1.172     www      1244: 
                   1245:     $topic=~s/\W+/\+/g;
                   1246:     my $link='';
                   1247:     my $template='';
1.379     albertel 1248:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1249: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1250:     if (!$stayOnPage)
                   1251:     {
                   1252: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1253:     }
                   1254:     else
                   1255:     {
                   1256: 	$link = $url;
                   1257:     }
                   1258:     # Add the text
                   1259:     if ($text ne "")
                   1260:     {
                   1261: 	$template .= 
                   1262:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1263:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1264:     }
                   1265: 
                   1266:     # Add the graphic
1.179     matthew  1267:     my $title = &mt('Report a Bug');
1.215     albertel 1268:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1269:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1270:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1271: ENDTEMPLATE
                   1272:     if ($text ne '') { $template.='</td></tr></table>' };
                   1273:     return $template;
                   1274: 
                   1275: }
                   1276: 
                   1277: sub help_open_faq {
                   1278:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1279:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1280:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1281:     $text = "" if (not defined $text);
                   1282:     $stayOnPage = 0 if (not defined $stayOnPage);
1.258     albertel 1283:     if ($env{'browser.interface'} eq 'textual' ||
                   1284: 	$env{'environment.remote'} eq 'off' ) {
1.172     www      1285: 	$stayOnPage=1;
                   1286:     }
                   1287:     $width = 350 if (not defined $width);
                   1288:     $height = 400 if (not defined $height);
                   1289: 
                   1290:     $topic=~s/\W+/\+/g;
                   1291:     my $link='';
                   1292:     my $template='';
                   1293:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1294:     if (!$stayOnPage)
                   1295:     {
                   1296: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1297:     }
                   1298:     else
                   1299:     {
                   1300: 	$link = $url;
                   1301:     }
                   1302: 
                   1303:     # Add the text
                   1304:     if ($text ne "")
                   1305:     {
                   1306: 	$template .= 
1.173     www      1307:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.436     albertel 1308:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.172     www      1309:     }
                   1310: 
                   1311:     # Add the graphic
1.179     matthew  1312:     my $title = &mt('View the FAQ');
1.215     albertel 1313:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1314:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1315:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1316: ENDTEMPLATE
                   1317:     if ($text ne '') { $template.='</td></tr></table>' };
                   1318:     return $template;
                   1319: 
1.44      bowersj2 1320: }
1.37      matthew  1321: 
1.180     matthew  1322: ###############################################################
                   1323: ###############################################################
                   1324: 
1.45      matthew  1325: =pod
                   1326: 
1.648     raeburn  1327: =item * &change_content_javascript():
1.256     matthew  1328: 
                   1329: This and the next function allow you to create small sections of an
                   1330: otherwise static HTML page that you can update on the fly with
                   1331: Javascript, even in Netscape 4.
                   1332: 
                   1333: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1334: must be written to the HTML page once. It will prove the Javascript
                   1335: function "change(name, content)". Calling the change function with the
                   1336: name of the section 
                   1337: you want to update, matching the name passed to C<changable_area>, and
                   1338: the new content you want to put in there, will put the content into
                   1339: that area.
                   1340: 
                   1341: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1342: to contain room for the original contents. You need to "make space"
                   1343: for whatever changes you wish to make, and be B<sure> to check your
                   1344: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1345: it's adequate for updating a one-line status display, but little more.
                   1346: This script will set the space to 100% width, so you only need to
                   1347: worry about height in Netscape 4.
                   1348: 
                   1349: Modern browsers are much less limiting, and if you can commit to the
                   1350: user not using Netscape 4, this feature may be used freely with
                   1351: pretty much any HTML.
                   1352: 
                   1353: =cut
                   1354: 
                   1355: sub change_content_javascript {
                   1356:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1357:     if ($env{'browser.type'} eq 'netscape' &&
                   1358: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1359: 	return (<<NETSCAPE4);
                   1360: 	function change(name, content) {
                   1361: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1362: 	    doc.open();
                   1363: 	    doc.write(content);
                   1364: 	    doc.close();
                   1365: 	}
                   1366: NETSCAPE4
                   1367:     } else {
                   1368: 	# Otherwise, we need to use semi-standards-compliant code
                   1369: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1370: 	# is really scary, and every useful browser supports it
                   1371: 	return (<<DOMBASED);
                   1372: 	function change(name, content) {
                   1373: 	    element = document.getElementById(name);
                   1374: 	    element.innerHTML = content;
                   1375: 	}
                   1376: DOMBASED
                   1377:     }
                   1378: }
                   1379: 
                   1380: =pod
                   1381: 
1.648     raeburn  1382: =item * &changable_area($name,$origContent):
1.256     matthew  1383: 
                   1384: This provides a "changable area" that can be modified on the fly via
                   1385: the Javascript code provided in C<change_content_javascript>. $name is
                   1386: the name you will use to reference the area later; do not repeat the
                   1387: same name on a given HTML page more then once. $origContent is what
                   1388: the area will originally contain, which can be left blank.
                   1389: 
                   1390: =cut
                   1391: 
                   1392: sub changable_area {
                   1393:     my ($name, $origContent) = @_;
                   1394: 
1.258     albertel 1395:     if ($env{'browser.type'} eq 'netscape' &&
                   1396: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1397: 	# If this is netscape 4, we need to use the Layer tag
                   1398: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1399:     } else {
                   1400: 	return "<span id='$name'>$origContent</span>";
                   1401:     }
                   1402: }
                   1403: 
                   1404: =pod
                   1405: 
1.648     raeburn  1406: =item * &viewport_geometry_js 
1.590     raeburn  1407: 
                   1408: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1409: 
                   1410: =cut
                   1411: 
                   1412: 
                   1413: sub viewport_geometry_js { 
                   1414:     return <<"GEOMETRY";
                   1415: var Geometry = {};
                   1416: function init_geometry() {
                   1417:     if (Geometry.init) { return };
                   1418:     Geometry.init=1;
                   1419:     if (window.innerHeight) {
                   1420:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1421:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1422:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1423:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1424:     }
                   1425:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1426:         Geometry.getViewportHeight =
                   1427:             function() { return document.documentElement.clientHeight; };
                   1428:         Geometry.getViewportWidth =
                   1429:             function() { return document.documentElement.clientWidth; };
                   1430: 
                   1431:         Geometry.getHorizontalScroll =
                   1432:             function() { return document.documentElement.scrollLeft; };
                   1433:         Geometry.getVerticalScroll =
                   1434:             function() { return document.documentElement.scrollTop; };
                   1435:     }
                   1436:     else if (document.body.clientHeight) {
                   1437:         Geometry.getViewportHeight =
                   1438:             function() { return document.body.clientHeight; };
                   1439:         Geometry.getViewportWidth =
                   1440:             function() { return document.body.clientWidth; };
                   1441:         Geometry.getHorizontalScroll =
                   1442:             function() { return document.body.scrollLeft; };
                   1443:         Geometry.getVerticalScroll =
                   1444:             function() { return document.body.scrollTop; };
                   1445:     }
                   1446: }
                   1447: 
                   1448: GEOMETRY
                   1449: }
                   1450: 
                   1451: =pod
                   1452: 
1.648     raeburn  1453: =item * &viewport_size_js()
1.590     raeburn  1454: 
                   1455: 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. 
                   1456: 
                   1457: =cut
                   1458: 
                   1459: sub viewport_size_js {
                   1460:     my $geometry = &viewport_geometry_js();
                   1461:     return <<"DIMS";
                   1462: 
                   1463: $geometry
                   1464: 
                   1465: function getViewportDims(width,height) {
                   1466:     init_geometry();
                   1467:     width.value = Geometry.getViewportWidth();
                   1468:     height.value = Geometry.getViewportHeight();
                   1469:     return;
                   1470: }
                   1471: 
                   1472: DIMS
                   1473: }
                   1474: 
                   1475: =pod
                   1476: 
1.648     raeburn  1477: =item * &resize_textarea_js()
1.565     albertel 1478: 
                   1479: emits the needed javascript to resize a textarea to be as big as possible
                   1480: 
                   1481: creates a function resize_textrea that takes two IDs first should be
                   1482: the id of the element to resize, second should be the id of a div that
                   1483: surrounds everything that comes after the textarea, this routine needs
                   1484: to be attached to the <body> for the onload and onresize events.
                   1485: 
1.648     raeburn  1486: =back
1.565     albertel 1487: 
                   1488: =cut
                   1489: 
                   1490: sub resize_textarea_js {
1.590     raeburn  1491:     my $geometry = &viewport_geometry_js();
1.565     albertel 1492:     return <<"RESIZE";
                   1493:     <script type="text/javascript">
1.692.4.4  raeburn  1494: // <![CDATA[
1.590     raeburn  1495: $geometry
1.565     albertel 1496: 
1.588     albertel 1497: function getX(element) {
                   1498:     var x = 0;
                   1499:     while (element) {
                   1500: 	x += element.offsetLeft;
                   1501: 	element = element.offsetParent;
                   1502:     }
                   1503:     return x;
                   1504: }
                   1505: function getY(element) {
                   1506:     var y = 0;
                   1507:     while (element) {
                   1508: 	y += element.offsetTop;
                   1509: 	element = element.offsetParent;
                   1510:     }
                   1511:     return y;
                   1512: }
                   1513: 
                   1514: 
1.565     albertel 1515: function resize_textarea(textarea_id,bottom_id) {
                   1516:     init_geometry();
                   1517:     var textarea        = document.getElementById(textarea_id);
                   1518:     //alert(textarea);
                   1519: 
1.588     albertel 1520:     var textarea_top    = getY(textarea);
1.565     albertel 1521:     var textarea_height = textarea.offsetHeight;
                   1522:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1523:     var bottom_top      = getY(bottom);
1.565     albertel 1524:     var bottom_height   = bottom.offsetHeight;
                   1525:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1526:     var fudge           = 23;
1.565     albertel 1527:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1528:     if (new_height < 300) {
                   1529: 	new_height = 300;
                   1530:     }
                   1531:     textarea.style.height=new_height+'px';
                   1532: }
1.692.4.4  raeburn  1533: // ]]>
1.565     albertel 1534: </script>
                   1535: RESIZE
                   1536: 
                   1537: }
                   1538: 
                   1539: =pod
                   1540: 
1.256     matthew  1541: =head1 Excel and CSV file utility routines
                   1542: 
                   1543: =over 4
                   1544: 
                   1545: =cut
                   1546: 
                   1547: ###############################################################
                   1548: ###############################################################
                   1549: 
                   1550: =pod
                   1551: 
1.648     raeburn  1552: =item * &csv_translate($text) 
1.37      matthew  1553: 
1.185     www      1554: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1555: format.
                   1556: 
                   1557: =cut
                   1558: 
1.180     matthew  1559: ###############################################################
                   1560: ###############################################################
1.37      matthew  1561: sub csv_translate {
                   1562:     my $text = shift;
                   1563:     $text =~ s/\"/\"\"/g;
1.209     albertel 1564:     $text =~ s/\n/ /g;
1.37      matthew  1565:     return $text;
                   1566: }
1.180     matthew  1567: 
                   1568: ###############################################################
                   1569: ###############################################################
                   1570: 
                   1571: =pod
                   1572: 
1.648     raeburn  1573: =item * &define_excel_formats()
1.180     matthew  1574: 
                   1575: Define some commonly used Excel cell formats.
                   1576: 
                   1577: Currently supported formats:
                   1578: 
                   1579: =over 4
                   1580: 
                   1581: =item header
                   1582: 
                   1583: =item bold
                   1584: 
                   1585: =item h1
                   1586: 
                   1587: =item h2
                   1588: 
                   1589: =item h3
                   1590: 
1.256     matthew  1591: =item h4
                   1592: 
                   1593: =item i
                   1594: 
1.180     matthew  1595: =item date
                   1596: 
                   1597: =back
                   1598: 
                   1599: Inputs: $workbook
                   1600: 
                   1601: Returns: $format, a hash reference.
                   1602: 
                   1603: =cut
                   1604: 
                   1605: ###############################################################
                   1606: ###############################################################
                   1607: sub define_excel_formats {
                   1608:     my ($workbook) = @_;
                   1609:     my $format;
                   1610:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1611:                                                 bottom    => 1,
                   1612:                                                 align     => 'center');
                   1613:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1614:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1615:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1616:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1617:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1618:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1619:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1620:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1621:     return $format;
                   1622: }
                   1623: 
                   1624: ###############################################################
                   1625: ###############################################################
1.113     bowersj2 1626: 
                   1627: =pod
                   1628: 
1.648     raeburn  1629: =item * &create_workbook()
1.255     matthew  1630: 
                   1631: Create an Excel worksheet.  If it fails, output message on the
                   1632: request object and return undefs.
                   1633: 
                   1634: Inputs: Apache request object
                   1635: 
                   1636: Returns (undef) on failure, 
                   1637:     Excel worksheet object, scalar with filename, and formats 
                   1638:     from &Apache::loncommon::define_excel_formats on success
                   1639: 
                   1640: =cut
                   1641: 
                   1642: ###############################################################
                   1643: ###############################################################
                   1644: sub create_workbook {
                   1645:     my ($r) = @_;
                   1646:         #
                   1647:     # Create the excel spreadsheet
                   1648:     my $filename = '/prtspool/'.
1.258     albertel 1649:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1650:         time.'_'.rand(1000000000).'.xls';
                   1651:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1652:     if (! defined($workbook)) {
                   1653:         $r->log_error("Error creating excel spreadsheet $filename: $!");
                   1654:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
                   1655:                             "This error has been logged.  ".
                   1656:                             "Please alert your LON-CAPA administrator").
                   1657:                   '</p>');
                   1658:         return (undef);
                   1659:     }
                   1660:     #
                   1661:     $workbook->set_tempdir('/home/httpd/perl/tmp');
                   1662:     #
                   1663:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1664:     return ($workbook,$filename,$format);
                   1665: }
                   1666: 
                   1667: ###############################################################
                   1668: ###############################################################
                   1669: 
                   1670: =pod
                   1671: 
1.648     raeburn  1672: =item * &create_text_file()
1.113     bowersj2 1673: 
1.542     raeburn  1674: Create a file to write to and eventually make available to the user.
1.256     matthew  1675: If file creation fails, outputs an error message on the request object and 
                   1676: return undefs.
1.113     bowersj2 1677: 
1.256     matthew  1678: Inputs: Apache request object, and file suffix
1.113     bowersj2 1679: 
1.256     matthew  1680: Returns (undef) on failure, 
                   1681:     Filehandle and filename on success.
1.113     bowersj2 1682: 
                   1683: =cut
                   1684: 
1.256     matthew  1685: ###############################################################
                   1686: ###############################################################
                   1687: sub create_text_file {
                   1688:     my ($r,$suffix) = @_;
                   1689:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1690:     my $fh;
                   1691:     my $filename = '/prtspool/'.
1.258     albertel 1692:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1693:         time.'_'.rand(1000000000).'.'.$suffix;
                   1694:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1695:     if (! defined($fh)) {
                   1696:         $r->log_error("Couldn't open $filename for output $!");
1.683     bisitz   1697:         $r->print(&mt('Problems occurred in creating the output file. '
                   1698:                      .'This error has been logged. '
                   1699:                      .'Please alert your LON-CAPA administrator.'));
1.113     bowersj2 1700:     }
1.256     matthew  1701:     return ($fh,$filename)
1.113     bowersj2 1702: }
                   1703: 
                   1704: 
1.256     matthew  1705: =pod 
1.113     bowersj2 1706: 
                   1707: =back
                   1708: 
                   1709: =cut
1.37      matthew  1710: 
                   1711: ###############################################################
1.33      matthew  1712: ##        Home server <option> list generating code          ##
                   1713: ###############################################################
1.35      matthew  1714: 
1.169     www      1715: # ------------------------------------------
                   1716: 
                   1717: sub domain_select {
                   1718:     my ($name,$value,$multiple)=@_;
                   1719:     my %domains=map { 
1.514     albertel 1720: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1721:     } &Apache::lonnet::all_domains();
1.169     www      1722:     if ($multiple) {
                   1723: 	$domains{''}=&mt('Any domain');
1.550     albertel 1724: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1725: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1726:     } else {
1.550     albertel 1727: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.169     www      1728: 	return &select_form($name,$value,%domains);
                   1729:     }
                   1730: }
                   1731: 
1.282     albertel 1732: #-------------------------------------------
                   1733: 
                   1734: =pod
                   1735: 
1.519     raeburn  1736: =head1 Routines for form select boxes
                   1737: 
                   1738: =over 4
                   1739: 
1.648     raeburn  1740: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1741: 
                   1742: Returns a string containing a <select> element int multiple mode
                   1743: 
                   1744: 
                   1745: Args:
                   1746:   $name - name of the <select> element
1.506     raeburn  1747:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1748:   $size - number of rows long the select element is
1.283     albertel 1749:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1750:           (shown text should already have been &mt())
1.506     raeburn  1751:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1752: 
1.282     albertel 1753: =cut
                   1754: 
                   1755: #-------------------------------------------
1.169     www      1756: sub multiple_select_form {
1.284     albertel 1757:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1758:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1759:     my $output='';
1.191     matthew  1760:     if (! defined($size)) {
                   1761:         $size = 4;
1.283     albertel 1762:         if (scalar(keys(%$hash))<4) {
                   1763:             $size = scalar(keys(%$hash));
1.191     matthew  1764:         }
                   1765:     }
1.692.4.2  raeburn  1766:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1767:     my @order;
1.506     raeburn  1768:     if (ref($order) eq 'ARRAY')  {
                   1769:         @order = @{$order};
                   1770:     } else {
                   1771:         @order = sort(keys(%$hash));
1.501     banghart 1772:     }
                   1773:     if (exists($$hash{'select_form_order'})) {
                   1774:         @order = @{$$hash{'select_form_order'}};
                   1775:     }
                   1776:         
1.284     albertel 1777:     foreach my $key (@order) {
1.356     albertel 1778:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1779:         $output.='selected="selected" ' if ($selected{$key});
                   1780:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1781:     }
                   1782:     $output.="</select>\n";
                   1783:     return $output;
                   1784: }
                   1785: 
1.88      www      1786: #-------------------------------------------
                   1787: 
                   1788: =pod
                   1789: 
1.648     raeburn  1790: =item * &select_form($defdom,$name,%hash)
1.88      www      1791: 
                   1792: Returns a string containing a <select name='$name' size='1'> form to 
                   1793: allow a user to select options from a hash option_name => displayed text.  
                   1794: See lonrights.pm for an example invocation and use.
                   1795: 
                   1796: =cut
                   1797: 
                   1798: #-------------------------------------------
                   1799: sub select_form {
                   1800:     my ($def,$name,%hash) = @_;
                   1801:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128     albertel 1802:     my @keys;
                   1803:     if (exists($hash{'select_form_order'})) {
                   1804: 	@keys=@{$hash{'select_form_order'}};
                   1805:     } else {
                   1806: 	@keys=sort(keys(%hash));
                   1807:     }
1.356     albertel 1808:     foreach my $key (@keys) {
                   1809:         $selectform.=
                   1810: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   1811:             ($key eq $def ? 'selected="selected" ' : '').
                   1812:                 ">".&mt($hash{$key})."</option>\n";
1.88      www      1813:     }
                   1814:     $selectform.="</select>";
                   1815:     return $selectform;
                   1816: }
                   1817: 
1.475     www      1818: # For display filters
                   1819: 
                   1820: sub display_filter {
                   1821:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      1822:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.692.4.2  raeburn  1823:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1.475     www      1824: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   1825: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.692.4.2  raeburn  1826: 	   '</label></span> <span class="LC_nobreak">'.
1.475     www      1827:            &mt('Filter [_1]',
1.477     www      1828: 	   &select_form($env{'form.displayfilter'},
                   1829: 			'displayfilter',
                   1830: 			('currentfolder' => 'Current folder/page',
                   1831: 			 'containing' => 'Containing phrase',
                   1832: 			 'none' => 'None'))).
1.692.4.2  raeburn  1833: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1.475     www      1834: }
                   1835: 
1.167     www      1836: sub gradeleveldescription {
                   1837:     my $gradelevel=shift;
                   1838:     my %gradelevels=(0 => 'Not specified',
                   1839: 		     1 => 'Grade 1',
                   1840: 		     2 => 'Grade 2',
                   1841: 		     3 => 'Grade 3',
                   1842: 		     4 => 'Grade 4',
                   1843: 		     5 => 'Grade 5',
                   1844: 		     6 => 'Grade 6',
                   1845: 		     7 => 'Grade 7',
                   1846: 		     8 => 'Grade 8',
                   1847: 		     9 => 'Grade 9',
                   1848: 		     10 => 'Grade 10',
                   1849: 		     11 => 'Grade 11',
                   1850: 		     12 => 'Grade 12',
                   1851: 		     13 => 'Grade 13',
                   1852: 		     14 => '100 Level',
                   1853: 		     15 => '200 Level',
                   1854: 		     16 => '300 Level',
                   1855: 		     17 => '400 Level',
                   1856: 		     18 => 'Graduate Level');
                   1857:     return &mt($gradelevels{$gradelevel});
                   1858: }
                   1859: 
1.163     www      1860: sub select_level_form {
                   1861:     my ($deflevel,$name)=@_;
                   1862:     unless ($deflevel) { $deflevel=0; }
1.167     www      1863:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   1864:     for (my $i=0; $i<=18; $i++) {
                   1865:         $selectform.="<option value=\"$i\" ".
1.253     albertel 1866:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      1867:                 ">".&gradeleveldescription($i)."</option>\n";
                   1868:     }
                   1869:     $selectform.="</select>";
                   1870:     return $selectform;
1.163     www      1871: }
1.167     www      1872: 
1.35      matthew  1873: #-------------------------------------------
                   1874: 
1.45      matthew  1875: =pod
                   1876: 
1.692.4.7  raeburn  1877: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
1.35      matthew  1878: 
                   1879: Returns a string containing a <select name='$name' size='1'> form to 
                   1880: allow a user to select the domain to preform an operation in.  
                   1881: See loncreateuser.pm for an example invocation and use.
                   1882: 
1.90      www      1883: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   1884: selected");
                   1885: 
1.692.4.2  raeburn  1886: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   1887: 
1.692.4.7  raeburn  1888: 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.
1.563     raeburn  1889: 
1.35      matthew  1890: =cut
                   1891: 
                   1892: #-------------------------------------------
1.34      matthew  1893: sub select_dom_form {
1.692.4.7  raeburn  1894:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
                   1895:     if ($onchange) {
                   1896:         $onchange = ' onchange="'.$onchange.'"';
1.692.4.2  raeburn  1897:     }
1.550     albertel 1898:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1.90      www      1899:     if ($includeempty) { @domains=('',@domains); }
1.692.4.2  raeburn  1900:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 1901:     foreach my $dom (@domains) {
                   1902:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  1903:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   1904:         if ($showdomdesc) {
                   1905:             if ($dom ne '') {
                   1906:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   1907:                 if ($domdesc ne '') {
                   1908:                     $selectdomain .= ' ('.$domdesc.')';
                   1909:                 }
                   1910:             } 
                   1911:         }
                   1912:         $selectdomain .= "</option>\n";
1.34      matthew  1913:     }
                   1914:     $selectdomain.="</select>";
                   1915:     return $selectdomain;
                   1916: }
                   1917: 
1.35      matthew  1918: #-------------------------------------------
                   1919: 
1.45      matthew  1920: =pod
                   1921: 
1.648     raeburn  1922: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  1923: 
1.586     raeburn  1924: input: 4 arguments (two required, two optional) - 
                   1925:     $domain - domain of new user
                   1926:     $name - name of form element
                   1927:     $default - Value of 'default' causes a default item to be first 
                   1928:                             option, and selected by default. 
                   1929:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   1930:                             if 1 server found, or default, if 0 found.
1.594     raeburn  1931: output: returns 2 items: 
1.586     raeburn  1932: (a) form element which contains either:
                   1933:    (i) <select name="$name">
                   1934:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   1935:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   1936:        </select>
                   1937:        form item if there are multiple library servers in $domain, or
                   1938:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   1939:        if there is only one library server in $domain.
                   1940: 
                   1941: (b) number of library servers found.
                   1942: 
                   1943: See loncreateuser.pm for example of use.
1.35      matthew  1944: 
                   1945: =cut
                   1946: 
                   1947: #-------------------------------------------
1.586     raeburn  1948: sub home_server_form_item {
                   1949:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 1950:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  1951:     my $result;
                   1952:     my $numlib = keys(%servers);
                   1953:     if ($numlib > 1) {
                   1954:         $result .= '<select name="'.$name.'" />'."\n";
                   1955:         if ($default) {
1.692.4.2  raeburn  1956:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  1957:                        '</option>'."\n";
                   1958:         }
                   1959:         foreach my $hostid (sort(keys(%servers))) {
                   1960:             $result.= '<option value="'.$hostid.'">'.
                   1961: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   1962:         }
                   1963:         $result .= '</select>'."\n";
                   1964:     } elsif ($numlib == 1) {
                   1965:         my $hostid;
                   1966:         foreach my $item (keys(%servers)) {
                   1967:             $hostid = $item;
                   1968:         }
                   1969:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   1970:                    $hostid.'" />';
                   1971:                    if (!$hide) {
                   1972:                        $result .= $hostid.' '.$servers{$hostid};
                   1973:                    }
                   1974:                    $result .= "\n";
                   1975:     } elsif ($default) {
                   1976:         $result .= '<input type="hidden" name="'.$name.
                   1977:                    '" value="default" />';
                   1978:                    if (!$hide) {
                   1979:                        $result .= &mt('default');
                   1980:                    }
                   1981:                    $result .= "\n";
1.33      matthew  1982:     }
1.586     raeburn  1983:     return ($result,$numlib);
1.33      matthew  1984: }
1.112     bowersj2 1985: 
                   1986: =pod
                   1987: 
1.534     albertel 1988: =back 
                   1989: 
1.112     bowersj2 1990: =cut
1.87      matthew  1991: 
                   1992: ###############################################################
1.112     bowersj2 1993: ##                  Decoding User Agent                      ##
1.87      matthew  1994: ###############################################################
                   1995: 
                   1996: =pod
                   1997: 
1.112     bowersj2 1998: =head1 Decoding the User Agent
                   1999: 
                   2000: =over 4
                   2001: 
                   2002: =item * &decode_user_agent()
1.87      matthew  2003: 
                   2004: Inputs: $r
                   2005: 
                   2006: Outputs:
                   2007: 
                   2008: =over 4
                   2009: 
1.112     bowersj2 2010: =item * $httpbrowser
1.87      matthew  2011: 
1.112     bowersj2 2012: =item * $clientbrowser
1.87      matthew  2013: 
1.112     bowersj2 2014: =item * $clientversion
1.87      matthew  2015: 
1.112     bowersj2 2016: =item * $clientmathml
1.87      matthew  2017: 
1.112     bowersj2 2018: =item * $clientunicode
1.87      matthew  2019: 
1.112     bowersj2 2020: =item * $clientos
1.87      matthew  2021: 
                   2022: =back
                   2023: 
1.157     matthew  2024: =back 
                   2025: 
1.87      matthew  2026: =cut
                   2027: 
                   2028: ###############################################################
                   2029: ###############################################################
                   2030: sub decode_user_agent {
1.247     albertel 2031:     my ($r)=@_;
1.87      matthew  2032:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2033:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2034:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2035:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2036:     my $clientbrowser='unknown';
                   2037:     my $clientversion='0';
                   2038:     my $clientmathml='';
                   2039:     my $clientunicode='0';
                   2040:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2041:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2042: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2043: 	    $clientbrowser=$bname;
                   2044:             $httpbrowser=~/$vreg/i;
                   2045: 	    $clientversion=$1;
                   2046:             $clientmathml=($clientversion>=$minv);
                   2047:             $clientunicode=($clientversion>=$univ);
                   2048: 	}
                   2049:     }
                   2050:     my $clientos='unknown';
                   2051:     if (($httpbrowser=~/linux/i) ||
                   2052:         ($httpbrowser=~/unix/i) ||
                   2053:         ($httpbrowser=~/ux/i) ||
                   2054:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2055:     if (($httpbrowser=~/vax/i) ||
                   2056:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2057:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2058:     if (($httpbrowser=~/mac/i) ||
                   2059:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2060:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2061:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2062:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2063:             $clientunicode,$clientos,);
                   2064: }
                   2065: 
1.32      matthew  2066: ###############################################################
                   2067: ##    Authentication changing form generation subroutines    ##
                   2068: ###############################################################
                   2069: ##
                   2070: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2071: ## hash, and have reasonable default values.
                   2072: ##
                   2073: ##    formname = the name given in the <form> tag.
1.35      matthew  2074: #-------------------------------------------
                   2075: 
1.45      matthew  2076: =pod
                   2077: 
1.112     bowersj2 2078: =head1 Authentication Routines
                   2079: 
                   2080: =over 4
                   2081: 
1.648     raeburn  2082: =item * &authform_xxxxxx()
1.35      matthew  2083: 
                   2084: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2085: handle some of the conveniences required for authentication forms.  
                   2086: This is not an optimal method, but it works.  
                   2087: 
                   2088: =over 4
                   2089: 
1.112     bowersj2 2090: =item * authform_header
1.35      matthew  2091: 
1.112     bowersj2 2092: =item * authform_authorwarning
1.35      matthew  2093: 
1.112     bowersj2 2094: =item * authform_nochange
1.35      matthew  2095: 
1.112     bowersj2 2096: =item * authform_kerberos
1.35      matthew  2097: 
1.112     bowersj2 2098: =item * authform_internal
1.35      matthew  2099: 
1.112     bowersj2 2100: =item * authform_filesystem
1.35      matthew  2101: 
                   2102: =back
                   2103: 
1.648     raeburn  2104: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2105: 
1.35      matthew  2106: =cut
                   2107: 
                   2108: #-------------------------------------------
1.32      matthew  2109: sub authform_header{  
                   2110:     my %in = (
                   2111:         formname => 'cu',
1.80      albertel 2112:         kerb_def_dom => '',
1.32      matthew  2113:         @_,
                   2114:     );
                   2115:     $in{'formname'} = 'document.' . $in{'formname'};
                   2116:     my $result='';
1.80      albertel 2117: 
                   2118: #---------------------------------------------- Code for upper case translation
                   2119:     my $Javascript_toUpperCase;
                   2120:     unless ($in{kerb_def_dom}) {
                   2121:         $Javascript_toUpperCase =<<"END";
                   2122:         switch (choice) {
                   2123:            case 'krb': currentform.elements[choicearg].value =
                   2124:                currentform.elements[choicearg].value.toUpperCase();
                   2125:                break;
                   2126:            default:
                   2127:         }
                   2128: END
                   2129:     } else {
                   2130:         $Javascript_toUpperCase = "";
                   2131:     }
                   2132: 
1.165     raeburn  2133:     my $radioval = "'nochange'";
1.591     raeburn  2134:     if (defined($in{'curr_authtype'})) {
                   2135:         if ($in{'curr_authtype'} ne '') {
                   2136:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2137:         }
1.174     matthew  2138:     }
1.165     raeburn  2139:     my $argfield = 'null';
1.591     raeburn  2140:     if (defined($in{'mode'})) {
1.165     raeburn  2141:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2142:             if (defined($in{'curr_autharg'})) {
                   2143:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2144:                     $argfield = "'$in{'curr_autharg'}'";
                   2145:                 }
                   2146:             }
                   2147:         }
                   2148:     }
                   2149: 
1.32      matthew  2150:     $result.=<<"END";
                   2151: var current = new Object();
1.165     raeburn  2152: current.radiovalue = $radioval;
                   2153: current.argfield = $argfield;
1.32      matthew  2154: 
                   2155: function changed_radio(choice,currentform) {
                   2156:     var choicearg = choice + 'arg';
                   2157:     // If a radio button in changed, we need to change the argfield
                   2158:     if (current.radiovalue != choice) {
                   2159:         current.radiovalue = choice;
                   2160:         if (current.argfield != null) {
                   2161:             currentform.elements[current.argfield].value = '';
                   2162:         }
                   2163:         if (choice == 'nochange') {
                   2164:             current.argfield = null;
                   2165:         } else {
                   2166:             current.argfield = choicearg;
                   2167:             switch(choice) {
                   2168:                 case 'krb': 
                   2169:                     currentform.elements[current.argfield].value = 
                   2170:                         "$in{'kerb_def_dom'}";
                   2171:                 break;
                   2172:               default:
                   2173:                 break;
                   2174:             }
                   2175:         }
                   2176:     }
                   2177:     return;
                   2178: }
1.22      www      2179: 
1.32      matthew  2180: function changed_text(choice,currentform) {
                   2181:     var choicearg = choice + 'arg';
                   2182:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2183:         $Javascript_toUpperCase
1.32      matthew  2184:         // clear old field
                   2185:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2186:             currentform.elements[current.argfield].value = '';
                   2187:         }
                   2188:         current.argfield = choicearg;
                   2189:     }
                   2190:     set_auth_radio_buttons(choice,currentform);
                   2191:     return;
1.20      www      2192: }
1.32      matthew  2193: 
                   2194: function set_auth_radio_buttons(newvalue,currentform) {
                   2195:     var i=0;
                   2196:     while (i < currentform.login.length) {
                   2197:         if (currentform.login[i].value == newvalue) { break; }
                   2198:         i++;
                   2199:     }
                   2200:     if (i == currentform.login.length) {
                   2201:         return;
                   2202:     }
                   2203:     current.radiovalue = newvalue;
                   2204:     currentform.login[i].checked = true;
                   2205:     return;
                   2206: }
                   2207: END
                   2208:     return $result;
                   2209: }
                   2210: 
                   2211: sub authform_authorwarning{
                   2212:     my $result='';
1.144     matthew  2213:     $result='<i>'.
                   2214:         &mt('As a general rule, only authors or co-authors should be '.
                   2215:             'filesystem authenticated '.
                   2216:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2217:     return $result;
                   2218: }
                   2219: 
                   2220: sub authform_nochange{  
                   2221:     my %in = (
                   2222:               formname => 'document.cu',
                   2223:               kerb_def_dom => 'MSU.EDU',
                   2224:               @_,
                   2225:           );
1.586     raeburn  2226:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
                   2227:     my $result;
                   2228:     if (keys(%can_assign) == 0) {
                   2229:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
                   2230:     } else {
                   2231:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2232:                   '<input type="radio" name="login" value="nochange" '.
                   2233:                   'checked="checked" onclick="'.
1.281     albertel 2234:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2235: 	    '</label>';
1.586     raeburn  2236:     }
1.32      matthew  2237:     return $result;
                   2238: }
                   2239: 
1.591     raeburn  2240: sub authform_kerberos {
1.32      matthew  2241:     my %in = (
                   2242:               formname => 'document.cu',
                   2243:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2244:               kerb_def_auth => 'krb4',
1.32      matthew  2245:               @_,
                   2246:               );
1.586     raeburn  2247:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2248:         $autharg,$jscall);
                   2249:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.80      albertel 2250:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.692.4.2  raeburn  2251:        $check5 = ' checked="checked"';
1.80      albertel 2252:     } else {
1.692.4.2  raeburn  2253:        $check4 = ' checked="checked"';
1.80      albertel 2254:     }
1.165     raeburn  2255:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2256:     if (defined($in{'curr_authtype'})) {
                   2257:         if ($in{'curr_authtype'} eq 'krb') {
1.692.4.2  raeburn  2258:             $krbcheck = ' checked="checked"';
1.623     raeburn  2259:             if (defined($in{'mode'})) {
                   2260:                 if ($in{'mode'} eq 'modifyuser') {
                   2261:                     $krbcheck = '';
                   2262:                 }
                   2263:             }
1.591     raeburn  2264:             if (defined($in{'curr_kerb_ver'})) {
                   2265:                 if ($in{'curr_krb_ver'} eq '5') {
1.692.4.2  raeburn  2266:                     $check5 = ' checked="checked"';
1.591     raeburn  2267:                     $check4 = '';
                   2268:                 } else {
1.692.4.2  raeburn  2269:                     $check4 = ' checked="checked"';
1.591     raeburn  2270:                     $check5 = '';
                   2271:                 }
1.586     raeburn  2272:             }
1.591     raeburn  2273:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2274:                 $krbarg = $in{'curr_autharg'};
                   2275:             }
1.586     raeburn  2276:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2277:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2278:                     $result = 
                   2279:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2280:         $in{'curr_autharg'},$krbver);
                   2281:                 } else {
                   2282:                     $result =
                   2283:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2284:                 }
                   2285:                 return $result; 
                   2286:             }
                   2287:         }
                   2288:     } else {
                   2289:         if ($authnum == 1) {
1.692.4.2  raeburn  2290:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2291:         }
                   2292:     }
1.586     raeburn  2293:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2294:         return;
1.587     raeburn  2295:     } elsif ($authtype eq '') {
1.591     raeburn  2296:         if (defined($in{'mode'})) {
1.587     raeburn  2297:             if ($in{'mode'} eq 'modifycourse') {
                   2298:                 if ($authnum == 1) {
1.692.4.2  raeburn  2299:                     $authtype = '<input type="hidden" name="login" value="krb" />';
1.587     raeburn  2300:                 }
                   2301:             }
                   2302:         }
1.586     raeburn  2303:     }
                   2304:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2305:     if ($authtype eq '') {
                   2306:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2307:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2308:                     $krbcheck.' />';
                   2309:     }
                   2310:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
                   2311:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
                   2312:          $in{'curr_authtype'} eq 'krb5') ||
                   2313:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
                   2314:          $in{'curr_authtype'} eq 'krb4')) {
                   2315:         $result .= &mt
1.144     matthew  2316:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2317:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2318:          '<label>'.$authtype,
1.281     albertel 2319:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2320:              'value="'.$krbarg.'" '.
1.144     matthew  2321:              'onchange="'.$jscall.'" />',
1.281     albertel 2322:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2323:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2324: 	 '</label>');
1.586     raeburn  2325:     } elsif ($can_assign{'krb4'}) {
                   2326:         $result .= &mt
                   2327:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2328:          '[_3] Version 4 [_4]',
                   2329:          '<label>'.$authtype,
                   2330:          '</label><input type="text" size="10" name="krbarg" '.
                   2331:              'value="'.$krbarg.'" '.
                   2332:              'onchange="'.$jscall.'" />',
                   2333:          '<label><input type="hidden" name="krbver" value="4" />',
                   2334:          '</label>');
                   2335:     } elsif ($can_assign{'krb5'}) {
                   2336:         $result .= &mt
                   2337:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2338:          '[_3] Version 5 [_4]',
                   2339:          '<label>'.$authtype,
                   2340:          '</label><input type="text" size="10" name="krbarg" '.
                   2341:              'value="'.$krbarg.'" '.
                   2342:              'onchange="'.$jscall.'" />',
                   2343:          '<label><input type="hidden" name="krbver" value="5" />',
                   2344:          '</label>');
                   2345:     }
1.32      matthew  2346:     return $result;
                   2347: }
                   2348: 
                   2349: sub authform_internal{  
1.586     raeburn  2350:     my %in = (
1.32      matthew  2351:                 formname => 'document.cu',
                   2352:                 kerb_def_dom => 'MSU.EDU',
                   2353:                 @_,
                   2354:                 );
1.586     raeburn  2355:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
                   2356:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2357:     if (defined($in{'curr_authtype'})) {
                   2358:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2359:             if ($can_assign{'int'}) {
1.692.4.2  raeburn  2360:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2361:                 if (defined($in{'mode'})) {
                   2362:                     if ($in{'mode'} eq 'modifyuser') {
                   2363:                         $intcheck = '';
                   2364:                     }
                   2365:                 }
1.591     raeburn  2366:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2367:                     $intarg = $in{'curr_autharg'};
                   2368:                 }
                   2369:             } else {
                   2370:                 $result = &mt('Currently internally authenticated.');
                   2371:                 return $result;
1.165     raeburn  2372:             }
                   2373:         }
1.586     raeburn  2374:     } else {
                   2375:         if ($authnum == 1) {
1.692.4.2  raeburn  2376:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2377:         }
                   2378:     }
                   2379:     if (!$can_assign{'int'}) {
                   2380:         return;
1.587     raeburn  2381:     } elsif ($authtype eq '') {
1.591     raeburn  2382:         if (defined($in{'mode'})) {
1.587     raeburn  2383:             if ($in{'mode'} eq 'modifycourse') {
                   2384:                 if ($authnum == 1) {
1.692.4.2  raeburn  2385:                     $authtype = '<input type="hidden" name="login" value="int" />';
1.587     raeburn  2386:                 }
                   2387:             }
                   2388:         }
1.165     raeburn  2389:     }
1.586     raeburn  2390:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2391:     if ($authtype eq '') {
                   2392:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2393:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2394:     }
1.605     bisitz   2395:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2396:                $intarg.'" onchange="'.$jscall.'" />';
                   2397:     $result = &mt
1.144     matthew  2398:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2399:          '<label>'.$authtype,'</label>'.$autharg);
1.692.4.4  raeburn  2400:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  2401:     return $result;
                   2402: }
                   2403: 
                   2404: sub authform_local{  
                   2405:     my %in = (
                   2406:               formname => 'document.cu',
                   2407:               kerb_def_dom => 'MSU.EDU',
                   2408:               @_,
                   2409:               );
1.586     raeburn  2410:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
                   2411:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2412:     if (defined($in{'curr_authtype'})) {
                   2413:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2414:             if ($can_assign{'loc'}) {
1.692.4.2  raeburn  2415:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2416:                 if (defined($in{'mode'})) {
                   2417:                     if ($in{'mode'} eq 'modifyuser') {
                   2418:                         $loccheck = '';
                   2419:                     }
                   2420:                 }
1.591     raeburn  2421:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2422:                     $locarg = $in{'curr_autharg'};
                   2423:                 }
                   2424:             } else {
                   2425:                 $result = &mt('Currently using local (institutional) authentication.');
                   2426:                 return $result;
1.165     raeburn  2427:             }
                   2428:         }
1.586     raeburn  2429:     } else {
                   2430:         if ($authnum == 1) {
1.692.4.2  raeburn  2431:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2432:         }
                   2433:     }
                   2434:     if (!$can_assign{'loc'}) {
                   2435:         return;
1.587     raeburn  2436:     } elsif ($authtype eq '') {
1.591     raeburn  2437:         if (defined($in{'mode'})) {
1.587     raeburn  2438:             if ($in{'mode'} eq 'modifycourse') {
                   2439:                 if ($authnum == 1) {
1.692.4.2  raeburn  2440:                     $authtype = '<input type="hidden" name="login" value="loc" />';
1.587     raeburn  2441:                 }
                   2442:             }
                   2443:         }
1.165     raeburn  2444:     }
1.586     raeburn  2445:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2446:     if ($authtype eq '') {
                   2447:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2448:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2449:                     $jscall.'" />';
                   2450:     }
                   2451:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2452:                $locarg.'" onchange="'.$jscall.'" />';
                   2453:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2454:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2455:     return $result;
                   2456: }
                   2457: 
                   2458: sub authform_filesystem{  
                   2459:     my %in = (
                   2460:               formname => 'document.cu',
                   2461:               kerb_def_dom => 'MSU.EDU',
                   2462:               @_,
                   2463:               );
1.586     raeburn  2464:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
                   2465:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2466:     if (defined($in{'curr_authtype'})) {
                   2467:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2468:             if ($can_assign{'fsys'}) {
1.692.4.2  raeburn  2469:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2470:                 if (defined($in{'mode'})) {
                   2471:                     if ($in{'mode'} eq 'modifyuser') {
                   2472:                         $fsyscheck = '';
                   2473:                     }
                   2474:                 }
1.586     raeburn  2475:             } else {
                   2476:                 $result = &mt('Currently Filesystem Authenticated.');
                   2477:                 return $result;
                   2478:             }           
                   2479:         }
                   2480:     } else {
                   2481:         if ($authnum == 1) {
1.692.4.2  raeburn  2482:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2483:         }
                   2484:     }
                   2485:     if (!$can_assign{'fsys'}) {
                   2486:         return;
1.587     raeburn  2487:     } elsif ($authtype eq '') {
1.591     raeburn  2488:         if (defined($in{'mode'})) {
1.587     raeburn  2489:             if ($in{'mode'} eq 'modifycourse') {
                   2490:                 if ($authnum == 1) {
1.692.4.2  raeburn  2491:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
1.587     raeburn  2492:                 }
                   2493:             }
                   2494:         }
1.586     raeburn  2495:     }
                   2496:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2497:     if ($authtype eq '') {
                   2498:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2499:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2500:                     $jscall.'" />';
                   2501:     }
                   2502:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2503:                ' onchange="'.$jscall.'" />';
                   2504:     $result = &mt
1.144     matthew  2505:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2506:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2507:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2508:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2509:                   'onchange="'.$jscall.'" />');
1.32      matthew  2510:     return $result;
                   2511: }
                   2512: 
1.586     raeburn  2513: sub get_assignable_auth {
                   2514:     my ($dom) = @_;
                   2515:     if ($dom eq '') {
                   2516:         $dom = $env{'request.role.domain'};
                   2517:     }
                   2518:     my %can_assign = (
                   2519:                           krb4 => 1,
                   2520:                           krb5 => 1,
                   2521:                           int  => 1,
                   2522:                           loc  => 1,
                   2523:                      );
                   2524:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2525:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2526:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2527:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2528:             my $context;
                   2529:             if ($env{'request.role'} =~ /^au/) {
                   2530:                 $context = 'author';
                   2531:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2532:                 $context = 'domain';
                   2533:             } elsif ($env{'request.course.id'}) {
                   2534:                 $context = 'course';
                   2535:             }
                   2536:             if ($context) {
                   2537:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2538:                    %can_assign = %{$authhash->{$context}}; 
                   2539:                 }
                   2540:             }
                   2541:         }
                   2542:     }
                   2543:     my $authnum = 0;
                   2544:     foreach my $key (keys(%can_assign)) {
                   2545:         if ($can_assign{$key}) {
                   2546:             $authnum ++;
                   2547:         }
                   2548:     }
                   2549:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2550:         $authnum --;
                   2551:     }
                   2552:     return ($authnum,%can_assign);
                   2553: }
                   2554: 
1.80      albertel 2555: ###############################################################
                   2556: ##    Get Kerberos Defaults for Domain                 ##
                   2557: ###############################################################
                   2558: ##
                   2559: ## Returns default kerberos version and an associated argument
                   2560: ## as listed in file domain.tab. If not listed, provides
                   2561: ## appropriate default domain and kerberos version.
                   2562: ##
                   2563: #-------------------------------------------
                   2564: 
                   2565: =pod
                   2566: 
1.648     raeburn  2567: =item * &get_kerberos_defaults()
1.80      albertel 2568: 
                   2569: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2570: version and domain. If not found, it defaults to version 4 and the 
                   2571: domain of the server.
1.80      albertel 2572: 
1.648     raeburn  2573: =over 4
                   2574: 
1.80      albertel 2575: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2576: 
1.648     raeburn  2577: =back
                   2578: 
                   2579: =back
                   2580: 
1.80      albertel 2581: =cut
                   2582: 
                   2583: #-------------------------------------------
                   2584: sub get_kerberos_defaults {
                   2585:     my $domain=shift;
1.641     raeburn  2586:     my ($krbdef,$krbdefdom);
                   2587:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2588:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2589:         $krbdef = $domdefaults{'auth_def'};
                   2590:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2591:     } else {
1.80      albertel 2592:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2593:         my $krbdefdom=$1;
                   2594:         $krbdefdom=~tr/a-z/A-Z/;
                   2595:         $krbdef = "krb4";
                   2596:     }
                   2597:     return ($krbdef,$krbdefdom);
                   2598: }
1.112     bowersj2 2599: 
1.32      matthew  2600: 
1.46      matthew  2601: ###############################################################
                   2602: ##                Thesaurus Functions                        ##
                   2603: ###############################################################
1.20      www      2604: 
1.46      matthew  2605: =pod
1.20      www      2606: 
1.112     bowersj2 2607: =head1 Thesaurus Functions
                   2608: 
                   2609: =over 4
                   2610: 
1.648     raeburn  2611: =item * &initialize_keywords()
1.46      matthew  2612: 
                   2613: Initializes the package variable %Keywords if it is empty.  Uses the
                   2614: package variable $thesaurus_db_file.
                   2615: 
                   2616: =cut
                   2617: 
                   2618: ###################################################
                   2619: 
                   2620: sub initialize_keywords {
                   2621:     return 1 if (scalar keys(%Keywords));
                   2622:     # If we are here, %Keywords is empty, so fill it up
                   2623:     #   Make sure the file we need exists...
                   2624:     if (! -e $thesaurus_db_file) {
                   2625:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2626:                                  " failed because it does not exist");
                   2627:         return 0;
                   2628:     }
                   2629:     #   Set up the hash as a database
                   2630:     my %thesaurus_db;
                   2631:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2632:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2633:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2634:                                  $thesaurus_db_file);
                   2635:         return 0;
                   2636:     } 
                   2637:     #  Get the average number of appearances of a word.
                   2638:     my $avecount = $thesaurus_db{'average.count'};
                   2639:     #  Put keywords (those that appear > average) into %Keywords
                   2640:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2641:         my ($count,undef) = split /:/,$data;
                   2642:         $Keywords{$word}++ if ($count > $avecount);
                   2643:     }
                   2644:     untie %thesaurus_db;
                   2645:     # Remove special values from %Keywords.
1.356     albertel 2646:     foreach my $value ('total.count','average.count') {
                   2647:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2648:   }
1.46      matthew  2649:     return 1;
                   2650: }
                   2651: 
                   2652: ###################################################
                   2653: 
                   2654: =pod
                   2655: 
1.648     raeburn  2656: =item * &keyword($word)
1.46      matthew  2657: 
                   2658: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2659: than the average number of times in the thesaurus database.  Calls 
                   2660: &initialize_keywords
                   2661: 
                   2662: =cut
                   2663: 
                   2664: ###################################################
1.20      www      2665: 
                   2666: sub keyword {
1.46      matthew  2667:     return if (!&initialize_keywords());
                   2668:     my $word=lc(shift());
                   2669:     $word=~s/\W//g;
                   2670:     return exists($Keywords{$word});
1.20      www      2671: }
1.46      matthew  2672: 
                   2673: ###############################################################
                   2674: 
                   2675: =pod 
1.20      www      2676: 
1.648     raeburn  2677: =item * &get_related_words()
1.46      matthew  2678: 
1.160     matthew  2679: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2680: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2681: will be returned.  The order of the words returned is determined by the
                   2682: database which holds them.
                   2683: 
                   2684: Uses global $thesaurus_db_file.
                   2685: 
                   2686: =cut
                   2687: 
                   2688: ###############################################################
                   2689: sub get_related_words {
                   2690:     my $keyword = shift;
                   2691:     my %thesaurus_db;
                   2692:     if (! -e $thesaurus_db_file) {
                   2693:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2694:                                  "failed because the file does not exist");
                   2695:         return ();
                   2696:     }
                   2697:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2698:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2699:         return ();
                   2700:     } 
                   2701:     my @Words=();
1.429     www      2702:     my $count=0;
1.46      matthew  2703:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 2704: 	# The first element is the number of times
                   2705: 	# the word appears.  We do not need it now.
1.429     www      2706: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   2707: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   2708: 	my $threshold=$mostfrequentcount/10;
                   2709:         foreach my $possibleword (@RelatedWords) {
                   2710:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   2711:             if ($wordcount>$threshold) {
                   2712: 		push(@Words,$word);
                   2713:                 $count++;
                   2714:                 if ($count>10) { last; }
                   2715: 	    }
1.20      www      2716:         }
                   2717:     }
1.46      matthew  2718:     untie %thesaurus_db;
                   2719:     return @Words;
1.14      harris41 2720: }
1.46      matthew  2721: 
1.112     bowersj2 2722: =pod
                   2723: 
                   2724: =back
                   2725: 
                   2726: =cut
1.61      www      2727: 
                   2728: # -------------------------------------------------------------- Plaintext name
1.81      albertel 2729: =pod
                   2730: 
1.112     bowersj2 2731: =head1 User Name Functions
                   2732: 
                   2733: =over 4
                   2734: 
1.648     raeburn  2735: =item * &plainname($uname,$udom,$first)
1.81      albertel 2736: 
1.112     bowersj2 2737: Takes a users logon name and returns it as a string in
1.226     albertel 2738: "first middle last generation" form 
                   2739: if $first is set to 'lastname' then it returns it as
                   2740: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 2741: 
                   2742: =cut
1.61      www      2743: 
1.295     www      2744: 
1.81      albertel 2745: ###############################################################
1.61      www      2746: sub plainname {
1.226     albertel 2747:     my ($uname,$udom,$first)=@_;
1.537     albertel 2748:     return if (!defined($uname) || !defined($udom));
1.295     www      2749:     my %names=&getnames($uname,$udom);
1.226     albertel 2750:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   2751: 					  $names{'middlename'},
                   2752: 					  $names{'lastname'},
                   2753: 					  $names{'generation'},$first);
                   2754:     $name=~s/^\s+//;
1.62      www      2755:     $name=~s/\s+$//;
                   2756:     $name=~s/\s+/ /g;
1.353     albertel 2757:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      2758:     return $name;
1.61      www      2759: }
1.66      www      2760: 
                   2761: # -------------------------------------------------------------------- Nickname
1.81      albertel 2762: =pod
                   2763: 
1.648     raeburn  2764: =item * &nickname($uname,$udom)
1.81      albertel 2765: 
                   2766: Gets a users name and returns it as a string as
                   2767: 
                   2768: "&quot;nickname&quot;"
1.66      www      2769: 
1.81      albertel 2770: if the user has a nickname or
                   2771: 
                   2772: "first middle last generation"
                   2773: 
                   2774: if the user does not
                   2775: 
                   2776: =cut
1.66      www      2777: 
                   2778: sub nickname {
                   2779:     my ($uname,$udom)=@_;
1.537     albertel 2780:     return if (!defined($uname) || !defined($udom));
1.295     www      2781:     my %names=&getnames($uname,$udom);
1.68      albertel 2782:     my $name=$names{'nickname'};
1.66      www      2783:     if ($name) {
                   2784:        $name='&quot;'.$name.'&quot;'; 
                   2785:     } else {
                   2786:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   2787: 	     $names{'lastname'}.' '.$names{'generation'};
                   2788:        $name=~s/\s+$//;
                   2789:        $name=~s/\s+/ /g;
                   2790:     }
                   2791:     return $name;
                   2792: }
                   2793: 
1.295     www      2794: sub getnames {
                   2795:     my ($uname,$udom)=@_;
1.537     albertel 2796:     return if (!defined($uname) || !defined($udom));
1.433     albertel 2797:     if ($udom eq 'public' && $uname eq 'public') {
                   2798: 	return ('lastname' => &mt('Public'));
                   2799:     }
1.295     www      2800:     my $id=$uname.':'.$udom;
                   2801:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   2802:     if ($cached) {
                   2803: 	return %{$names};
                   2804:     } else {
                   2805: 	my %loadnames=&Apache::lonnet::get('environment',
                   2806:                     ['firstname','middlename','lastname','generation','nickname'],
                   2807: 					 $udom,$uname);
                   2808: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   2809: 	return %loadnames;
                   2810:     }
                   2811: }
1.61      www      2812: 
1.542     raeburn  2813: # -------------------------------------------------------------------- getemails
1.648     raeburn  2814: 
1.542     raeburn  2815: =pod
                   2816: 
1.648     raeburn  2817: =item * &getemails($uname,$udom)
1.542     raeburn  2818: 
                   2819: Gets a user's email information and returns it as a hash with keys:
                   2820: notification, critnotification, permanentemail
                   2821: 
                   2822: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  2823: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  2824:  
1.648     raeburn  2825: 
1.542     raeburn  2826: =cut
                   2827: 
1.648     raeburn  2828: 
1.466     albertel 2829: sub getemails {
                   2830:     my ($uname,$udom)=@_;
                   2831:     if ($udom eq 'public' && $uname eq 'public') {
                   2832: 	return;
                   2833:     }
1.467     www      2834:     if (!$udom) { $udom=$env{'user.domain'}; }
                   2835:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 2836:     my $id=$uname.':'.$udom;
                   2837:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   2838:     if ($cached) {
                   2839: 	return %{$names};
                   2840:     } else {
                   2841: 	my %loadnames=&Apache::lonnet::get('environment',
                   2842:                     			   ['notification','critnotification',
                   2843: 					    'permanentemail'],
                   2844: 					   $udom,$uname);
                   2845: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   2846: 	return %loadnames;
                   2847:     }
                   2848: }
                   2849: 
1.551     albertel 2850: sub flush_email_cache {
                   2851:     my ($uname,$udom)=@_;
                   2852:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   2853:     if (!$uname) { $uname=$env{'user.name'};   }
                   2854:     return if ($udom eq 'public' && $uname eq 'public');
                   2855:     my $id=$uname.':'.$udom;
                   2856:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   2857: }
                   2858: 
1.692.4.2  raeburn  2859: # -------------------------------------------------------------------- getlangs
                   2860: 
                   2861: =pod
                   2862: 
                   2863: =item * &getlangs($uname,$udom)
                   2864: 
                   2865: Gets a user's language preference and returns it as a hash with key:
                   2866: language.
                   2867: 
                   2868: =cut
                   2869: 
                   2870: 
                   2871: sub getlangs {
                   2872:     my ($uname,$udom) = @_;
                   2873:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   2874:     if (!$uname) { $uname=$env{'user.name'};   }
                   2875:     my $id=$uname.':'.$udom;
                   2876:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   2877:     if ($cached) {
                   2878:         return %{$langs};
                   2879:     } else {
                   2880:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   2881:                                            $udom,$uname);
                   2882:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   2883:         return %loadlangs;
                   2884:     }
                   2885: }
                   2886: 
                   2887: sub flush_langs_cache {
                   2888:     my ($uname,$udom)=@_;
                   2889:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   2890:     if (!$uname) { $uname=$env{'user.name'};   }
                   2891:     return if ($udom eq 'public' && $uname eq 'public');
                   2892:     my $id=$uname.':'.$udom;
                   2893:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   2894: }
                   2895: 
1.61      www      2896: # ------------------------------------------------------------------ Screenname
1.81      albertel 2897: 
                   2898: =pod
                   2899: 
1.648     raeburn  2900: =item * &screenname($uname,$udom)
1.81      albertel 2901: 
                   2902: Gets a users screenname and returns it as a string
                   2903: 
                   2904: =cut
1.61      www      2905: 
                   2906: sub screenname {
                   2907:     my ($uname,$udom)=@_;
1.258     albertel 2908:     if ($uname eq $env{'user.name'} &&
                   2909: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 2910:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 2911:     return $names{'screenname'};
1.62      www      2912: }
                   2913: 
1.692.4.2  raeburn  2914: # ------------------------------------------------------------- Confirm Wrapper
                   2915: =pod
                   2916: 
                   2917: =item confirmwrapper
                   2918: 
                   2919: Wrap messages about completion of operation in box
                   2920: 
                   2921: =cut
                   2922: 
                   2923: sub confirmwrapper {
                   2924:     my ($message)=@_;
                   2925:     if ($message) {
                   2926:         return "\n".'<div class="LC_confirm_box">'."\n"
                   2927:                .$message."\n"
                   2928:                .'</div>'."\n";
                   2929:     } else {
                   2930:         return $message;
                   2931:     }
                   2932: }
1.212     albertel 2933: 
1.62      www      2934: # ------------------------------------------------------------- Message Wrapper
                   2935: 
                   2936: sub messagewrapper {
1.369     www      2937:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      2938:     return 
1.441     albertel 2939:         '<a href="/adm/email?compose=individual&amp;'.
                   2940:         'recname='.$username.'&amp;recdom='.$domain.
                   2941: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  2942:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      2943: }
                   2944: # --------------------------------------------------------------- Notes Wrapper
                   2945: 
                   2946: sub noteswrapper {
                   2947:     my ($link,$un,$do)=@_;
                   2948:     return 
                   2949: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      2950: }
                   2951: # ------------------------------------------------------------- Aboutme Wrapper
                   2952: 
                   2953: sub aboutmewrapper {
1.166     www      2954:     my ($link,$username,$domain,$target)=@_;
1.447     raeburn  2955:     if (!defined($username)  && !defined($domain)) {
                   2956:         return;
                   2957:     }
1.205     www      2958:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.692.4.2  raeburn  2959: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      2960: }
                   2961: 
                   2962: # ------------------------------------------------------------ Syllabus Wrapper
                   2963: 
                   2964: 
                   2965: sub syllabuswrapper {
1.109     matthew  2966:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   2967:     if ($fontcolor) { 
                   2968:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   2969:     }
1.208     matthew  2970:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      2971: }
1.14      harris41 2972: 
1.208     matthew  2973: sub track_student_link {
1.268     albertel 2974:     my ($linktext,$sname,$sdom,$target,$start) = @_;
                   2975:     my $link ="/adm/trackstudent?";
1.208     matthew  2976:     my $title = 'View recent activity';
                   2977:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   2978:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 2979:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  2980:         $title .= ' of this student';
1.268     albertel 2981:     } 
1.208     matthew  2982:     if (defined($target) && $target !~ /^\s*$/) {
                   2983:         $target = qq{target="$target"};
                   2984:     } else {
                   2985:         $target = '';
                   2986:     }
1.268     albertel 2987:     if ($start) { $link.='&amp;start='.$start; }
1.554     albertel 2988:     $title = &mt($title);
                   2989:     $linktext = &mt($linktext);
1.448     albertel 2990:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   2991: 	&help_open_topic('View_recent_activity');
1.208     matthew  2992: }
                   2993: 
1.692.4.2  raeburn  2994: sub slot_reservations_link {
                   2995:     my ($linktext,$sname,$sdom,$target) = @_;
                   2996:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   2997:     my $title = 'View slot reservation history';
                   2998:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   2999:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3000:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3001:         $title .= ' of this student';
                   3002:     }
                   3003:     if (defined($target) && $target !~ /^\s*$/) {
                   3004:         $target = qq{target="$target"};
                   3005:     } else {
                   3006:         $target = '';
                   3007:     }
                   3008:     $title = &mt($title);
                   3009:     $linktext = &mt($linktext);
                   3010:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3011: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3012: 
                   3013: }
                   3014: 
1.508     www      3015: # ===================================================== Display a student photo
                   3016: 
                   3017: 
1.509     albertel 3018: sub student_image_tag {
1.508     www      3019:     my ($domain,$user)=@_;
                   3020:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3021:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3022: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3023:     } else {
                   3024: 	return '';
                   3025:     }
                   3026: }
                   3027: 
1.112     bowersj2 3028: =pod
                   3029: 
                   3030: =back
                   3031: 
                   3032: =head1 Access .tab File Data
                   3033: 
                   3034: =over 4
                   3035: 
1.648     raeburn  3036: =item * &languageids() 
1.112     bowersj2 3037: 
                   3038: returns list of all language ids
                   3039: 
                   3040: =cut
                   3041: 
1.14      harris41 3042: sub languageids {
1.16      harris41 3043:     return sort(keys(%language));
1.14      harris41 3044: }
                   3045: 
1.112     bowersj2 3046: =pod
                   3047: 
1.648     raeburn  3048: =item * &languagedescription() 
1.112     bowersj2 3049: 
                   3050: returns description of a specified language id
                   3051: 
                   3052: =cut
                   3053: 
1.14      harris41 3054: sub languagedescription {
1.125     www      3055:     my $code=shift;
                   3056:     return  ($supported_language{$code}?'* ':'').
                   3057:             $language{$code}.
1.126     www      3058: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3059: }
                   3060: 
                   3061: sub plainlanguagedescription {
                   3062:     my $code=shift;
                   3063:     return $language{$code};
                   3064: }
                   3065: 
                   3066: sub supportedlanguagecode {
                   3067:     my $code=shift;
                   3068:     return $supported_language{$code};
1.97      www      3069: }
                   3070: 
1.112     bowersj2 3071: =pod
                   3072: 
1.648     raeburn  3073: =item * &copyrightids() 
1.112     bowersj2 3074: 
                   3075: returns list of all copyrights
                   3076: 
                   3077: =cut
                   3078: 
                   3079: sub copyrightids {
                   3080:     return sort(keys(%cprtag));
                   3081: }
                   3082: 
                   3083: =pod
                   3084: 
1.648     raeburn  3085: =item * &copyrightdescription() 
1.112     bowersj2 3086: 
                   3087: returns description of a specified copyright id
                   3088: 
                   3089: =cut
                   3090: 
                   3091: sub copyrightdescription {
1.166     www      3092:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3093: }
1.197     matthew  3094: 
                   3095: =pod
                   3096: 
1.648     raeburn  3097: =item * &source_copyrightids() 
1.192     taceyjo1 3098: 
                   3099: returns list of all source copyrights
                   3100: 
                   3101: =cut
                   3102: 
                   3103: sub source_copyrightids {
                   3104:     return sort(keys(%scprtag));
                   3105: }
                   3106: 
                   3107: =pod
                   3108: 
1.648     raeburn  3109: =item * &source_copyrightdescription() 
1.192     taceyjo1 3110: 
                   3111: returns description of a specified source copyright id
                   3112: 
                   3113: =cut
                   3114: 
                   3115: sub source_copyrightdescription {
                   3116:     return &mt($scprtag{shift(@_)});
                   3117: }
1.112     bowersj2 3118: 
                   3119: =pod
                   3120: 
1.648     raeburn  3121: =item * &filecategories() 
1.112     bowersj2 3122: 
                   3123: returns list of all file categories
                   3124: 
                   3125: =cut
                   3126: 
                   3127: sub filecategories {
                   3128:     return sort(keys(%category_extensions));
                   3129: }
                   3130: 
                   3131: =pod
                   3132: 
1.648     raeburn  3133: =item * &filecategorytypes() 
1.112     bowersj2 3134: 
                   3135: returns list of file types belonging to a given file
                   3136: category
                   3137: 
                   3138: =cut
                   3139: 
                   3140: sub filecategorytypes {
1.356     albertel 3141:     my ($cat) = @_;
                   3142:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3143: }
                   3144: 
                   3145: =pod
                   3146: 
1.648     raeburn  3147: =item * &fileembstyle() 
1.112     bowersj2 3148: 
                   3149: returns embedding style for a specified file type
                   3150: 
                   3151: =cut
                   3152: 
                   3153: sub fileembstyle {
                   3154:     return $fe{lc(shift(@_))};
1.169     www      3155: }
                   3156: 
1.351     www      3157: sub filemimetype {
                   3158:     return $fm{lc(shift(@_))};
                   3159: }
                   3160: 
1.169     www      3161: 
                   3162: sub filecategoryselect {
                   3163:     my ($name,$value)=@_;
1.189     matthew  3164:     return &select_form($value,$name,
1.169     www      3165: 			'' => &mt('Any category'),
                   3166: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 3167: }
                   3168: 
                   3169: =pod
                   3170: 
1.648     raeburn  3171: =item * &filedescription() 
1.112     bowersj2 3172: 
                   3173: returns description for a specified file type
                   3174: 
                   3175: =cut
                   3176: 
                   3177: sub filedescription {
1.188     matthew  3178:     my $file_description = $fd{lc(shift())};
                   3179:     $file_description =~ s:([\[\]]):~$1:g;
                   3180:     return &mt($file_description);
1.112     bowersj2 3181: }
                   3182: 
                   3183: =pod
                   3184: 
1.648     raeburn  3185: =item * &filedescriptionex() 
1.112     bowersj2 3186: 
                   3187: returns description for a specified file type with
                   3188: extra formatting
                   3189: 
                   3190: =cut
                   3191: 
                   3192: sub filedescriptionex {
                   3193:     my $ex=shift;
1.188     matthew  3194:     my $file_description = $fd{lc($ex)};
                   3195:     $file_description =~ s:([\[\]]):~$1:g;
                   3196:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3197: }
                   3198: 
                   3199: # End of .tab access
                   3200: =pod
                   3201: 
                   3202: =back
                   3203: 
                   3204: =cut
                   3205: 
                   3206: # ------------------------------------------------------------------ File Types
                   3207: sub fileextensions {
                   3208:     return sort(keys(%fe));
                   3209: }
                   3210: 
1.97      www      3211: # ----------------------------------------------------------- Display Languages
                   3212: # returns a hash with all desired display languages
                   3213: #
                   3214: 
                   3215: sub display_languages {
                   3216:     my %languages=();
1.692.4.1  raeburn  3217:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3218: 	$languages{$lang}=1;
1.97      www      3219:     }
                   3220:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3221:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3222: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3223: 	    $languages{$lang}=1;
1.97      www      3224:         }
                   3225:     }
                   3226:     return %languages;
1.14      harris41 3227: }
                   3228: 
1.582     albertel 3229: sub languages {
                   3230:     my ($possible_langs) = @_;
1.692.4.1  raeburn  3231:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3232:     if (!ref($possible_langs)) {
                   3233: 	if( wantarray ) {
                   3234: 	    return @preferred_langs;
                   3235: 	} else {
                   3236: 	    return $preferred_langs[0];
                   3237: 	}
                   3238:     }
                   3239:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3240:     my @preferred_possibilities;
                   3241:     foreach my $preferred_lang (@preferred_langs) {
                   3242: 	if (exists($possibilities{$preferred_lang})) {
                   3243: 	    push(@preferred_possibilities, $preferred_lang);
                   3244: 	}
                   3245:     }
                   3246:     if( wantarray ) {
                   3247: 	return @preferred_possibilities;
                   3248:     }
                   3249:     return $preferred_possibilities[0];
                   3250: }
                   3251: 
1.692.4.2  raeburn  3252: sub user_lang {
                   3253:     my ($touname,$toudom,$fromcid) = @_;
                   3254:     my @userlangs;
                   3255:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3256:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3257:                     $env{'course.'.$fromcid.'.languages'}));
                   3258:     } else {
                   3259:         my %langhash = &getlangs($touname,$toudom);
                   3260:         if ($langhash{'languages'} ne '') {
                   3261:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3262:         } else {
                   3263:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3264:             if ($domdefs{'lang_def'} ne '') {
                   3265:                 @userlangs = ($domdefs{'lang_def'});
                   3266:             }
                   3267:         }
                   3268:     }
                   3269:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3270:     my $user_lh = Apache::localize->get_handle(@languages);
                   3271:     return $user_lh;
                   3272: }
                   3273: 
1.112     bowersj2 3274: ###############################################################
                   3275: ##               Student Answer Attempts                     ##
                   3276: ###############################################################
                   3277: 
                   3278: =pod
                   3279: 
                   3280: =head1 Alternate Problem Views
                   3281: 
                   3282: =over 4
                   3283: 
1.648     raeburn  3284: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3285:     $getattempt, $regexp, $gradesub)
                   3286: 
                   3287: Return string with previous attempt on problem. Arguments:
                   3288: 
                   3289: =over 4
                   3290: 
                   3291: =item * $symb: Problem, including path
                   3292: 
                   3293: =item * $username: username of the desired student
                   3294: 
                   3295: =item * $domain: domain of the desired student
1.14      harris41 3296: 
1.112     bowersj2 3297: =item * $course: Course ID
1.14      harris41 3298: 
1.112     bowersj2 3299: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3300:     something
1.14      harris41 3301: 
1.112     bowersj2 3302: =item * $regexp: if string matches this regexp, the string will be
                   3303:     sent to $gradesub
1.14      harris41 3304: 
1.112     bowersj2 3305: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3306: 
1.112     bowersj2 3307: =back
1.14      harris41 3308: 
1.112     bowersj2 3309: The output string is a table containing all desired attempts, if any.
1.16      harris41 3310: 
1.112     bowersj2 3311: =cut
1.1       albertel 3312: 
                   3313: sub get_previous_attempt {
1.43      ng       3314:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3315:   my $prevattempts='';
1.43      ng       3316:   no strict 'refs';
1.1       albertel 3317:   if ($symb) {
1.3       albertel 3318:     my (%returnhash)=
                   3319:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3320:     if ($returnhash{'version'}) {
                   3321:       my %lasthash=();
                   3322:       my $version;
                   3323:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3324:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3325: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3326:         }
1.1       albertel 3327:       }
1.596     albertel 3328:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3329:       $prevattempts.='<th>'.&mt('History').'</th>';
1.356     albertel 3330:       foreach my $key (sort(keys(%lasthash))) {
                   3331: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3332: 	if ($#parts > 0) {
1.31      albertel 3333: 	  my $data=$parts[-1];
                   3334: 	  pop(@parts);
1.596     albertel 3335: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.31      albertel 3336: 	} else {
1.41      ng       3337: 	  if ($#parts == 0) {
                   3338: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3339: 	  } else {
                   3340: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3341: 	  }
1.31      albertel 3342: 	}
1.16      harris41 3343:       }
1.596     albertel 3344:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3345:       if ($getattempt eq '') {
                   3346: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.596     albertel 3347: 	  $prevattempts.=&start_data_table_row().
                   3348: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
1.356     albertel 3349: 	    foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3350: 		my $value = &format_previous_attempt_value($key,
                   3351: 							   $returnhash{$version.':'.$key});
                   3352: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
1.40      ng       3353: 	    }
1.596     albertel 3354: 	  $prevattempts.=&end_data_table_row();
1.40      ng       3355: 	 }
1.1       albertel 3356:       }
1.596     albertel 3357:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3358:       foreach my $key (sort(keys(%lasthash))) {
1.581     albertel 3359: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
1.356     albertel 3360: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       3361: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 3362:       }
1.596     albertel 3363:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3364:     } else {
1.596     albertel 3365:       $prevattempts=
                   3366: 	  &start_data_table().&start_data_table_row().
                   3367: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3368: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3369:     }
                   3370:   } else {
1.596     albertel 3371:     $prevattempts=
                   3372: 	  &start_data_table().&start_data_table_row().
                   3373: 	  '<td>'.&mt('No data.').'</td>'.
                   3374: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3375:   }
1.10      albertel 3376: }
                   3377: 
1.581     albertel 3378: sub format_previous_attempt_value {
                   3379:     my ($key,$value) = @_;
                   3380:     if ($key =~ /timestamp/) {
                   3381: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3382:     } elsif (ref($value) eq 'ARRAY') {
                   3383: 	$value = '('.join(', ', @{ $value }).')';
                   3384:     } else {
                   3385: 	$value = &unescape($value);
                   3386:     }
                   3387:     return $value;
                   3388: }
                   3389: 
                   3390: 
1.107     albertel 3391: sub relative_to_absolute {
                   3392:     my ($url,$output)=@_;
                   3393:     my $parser=HTML::TokeParser->new(\$output);
                   3394:     my $token;
                   3395:     my $thisdir=$url;
                   3396:     my @rlinks=();
                   3397:     while ($token=$parser->get_token) {
                   3398: 	if ($token->[0] eq 'S') {
                   3399: 	    if ($token->[1] eq 'a') {
                   3400: 		if ($token->[2]->{'href'}) {
                   3401: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3402: 		}
                   3403: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3404: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3405: 	    } elsif ($token->[1] eq 'base') {
                   3406: 		$thisdir=$token->[2]->{'href'};
                   3407: 	    }
                   3408: 	}
                   3409:     }
                   3410:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3411:     foreach my $link (@rlinks) {
1.692.4.2  raeburn  3412: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3413: 		($link=~/^\//) ||
                   3414: 		($link=~/^javascript:/i) ||
                   3415: 		($link=~/^mailto:/i) ||
                   3416: 		($link=~/^\#/)) {
                   3417: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3418: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3419: 	}
                   3420:     }
                   3421: # -------------------------------------------------- Deal with Applet codebases
                   3422:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3423:     return $output;
                   3424: }
                   3425: 
1.112     bowersj2 3426: =pod
                   3427: 
1.648     raeburn  3428: =item * &get_student_view()
1.112     bowersj2 3429: 
                   3430: show a snapshot of what student was looking at
                   3431: 
                   3432: =cut
                   3433: 
1.10      albertel 3434: sub get_student_view {
1.186     albertel 3435:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3436:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3437:   my (%form);
1.10      albertel 3438:   my @elements=('symb','courseid','domain','username');
                   3439:   foreach my $element (@elements) {
1.186     albertel 3440:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3441:   }
1.186     albertel 3442:   if (defined($moreenv)) {
                   3443:       %form=(%form,%{$moreenv});
                   3444:   }
1.236     albertel 3445:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3446:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3447:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3448:   $userview=~s/\<body[^\>]*\>//gi;
                   3449:   $userview=~s/\<\/body\>//gi;
                   3450:   $userview=~s/\<html\>//gi;
                   3451:   $userview=~s/\<\/html\>//gi;
                   3452:   $userview=~s/\<head\>//gi;
                   3453:   $userview=~s/\<\/head\>//gi;
                   3454:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3455:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3456:   if (wantarray) {
                   3457:      return ($userview,$response);
                   3458:   } else {
                   3459:      return $userview;
                   3460:   }
                   3461: }
                   3462: 
                   3463: sub get_student_view_with_retries {
                   3464:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3465: 
                   3466:     my $ok = 0;                 # True if we got a good response.
                   3467:     my $content;
                   3468:     my $response;
                   3469: 
                   3470:     # Try to get the student_view done. within the retries count:
                   3471:     
                   3472:     do {
                   3473:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3474:          $ok      = $response->is_success;
                   3475:          if (!$ok) {
                   3476:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3477:          }
                   3478:          $retries--;
                   3479:     } while (!$ok && ($retries > 0));
                   3480:     
                   3481:     if (!$ok) {
                   3482:        $content = '';          # On error return an empty content.
                   3483:     }
1.651     www      3484:     if (wantarray) {
                   3485:        return ($content, $response);
                   3486:     } else {
                   3487:        return $content;
                   3488:     }
1.11      albertel 3489: }
                   3490: 
1.112     bowersj2 3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &get_student_answers() 
1.112     bowersj2 3494: 
                   3495: show a snapshot of how student was answering problem
                   3496: 
                   3497: =cut
                   3498: 
1.11      albertel 3499: sub get_student_answers {
1.100     sakharuk 3500:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3501:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3502:   my (%moreenv);
1.11      albertel 3503:   my @elements=('symb','courseid','domain','username');
                   3504:   foreach my $element (@elements) {
1.186     albertel 3505:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3506:   }
1.186     albertel 3507:   $moreenv{'grade_target'}='answer';
                   3508:   %moreenv=(%form,%moreenv);
1.497     raeburn  3509:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3510:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3511:   return $userview;
1.1       albertel 3512: }
1.116     albertel 3513: 
                   3514: =pod
                   3515: 
                   3516: =item * &submlink()
                   3517: 
1.242     albertel 3518: Inputs: $text $uname $udom $symb $target
1.116     albertel 3519: 
                   3520: Returns: A link to grades.pm such as to see the SUBM view of a student
                   3521: 
                   3522: =cut
                   3523: 
                   3524: ###############################################
                   3525: sub submlink {
1.242     albertel 3526:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 3527:     if (!($uname && $udom)) {
                   3528: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3529: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 3530: 	if (!$symb) { $symb=$cursymb; }
                   3531:     }
1.254     matthew  3532:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3533:     $symb=&escape($symb);
1.242     albertel 3534:     if ($target) { $target="target=\"$target\""; }
                   3535:     return '<a href="/adm/grades?&command=submission&'.
                   3536: 	'symb='.$symb.'&student='.$uname.
                   3537: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
                   3538: }
                   3539: ##############################################
                   3540: 
                   3541: =pod
                   3542: 
                   3543: =item * &pgrdlink()
                   3544: 
                   3545: Inputs: $text $uname $udom $symb $target
                   3546: 
                   3547: Returns: A link to grades.pm such as to see the PGRD view of a student
                   3548: 
                   3549: =cut
                   3550: 
                   3551: ###############################################
                   3552: sub pgrdlink {
                   3553:     my $link=&submlink(@_);
                   3554:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   3555:     return $link;
                   3556: }
                   3557: ##############################################
                   3558: 
                   3559: =pod
                   3560: 
                   3561: =item * &pprmlink()
                   3562: 
                   3563: Inputs: $text $uname $udom $symb $target
                   3564: 
                   3565: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 3566: student and a specific resource
1.242     albertel 3567: 
                   3568: =cut
                   3569: 
                   3570: ###############################################
                   3571: sub pprmlink {
                   3572:     my ($text,$uname,$udom,$symb,$target)=@_;
                   3573:     if (!($uname && $udom)) {
                   3574: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3575: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 3576: 	if (!$symb) { $symb=$cursymb; }
                   3577:     }
1.254     matthew  3578:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3579:     $symb=&escape($symb);
1.242     albertel 3580:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 3581:     return '<a href="/adm/parmset?command=set&amp;'.
                   3582: 	'symb='.$symb.'&amp;uname='.$uname.
                   3583: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 3584: }
                   3585: ##############################################
1.37      matthew  3586: 
1.112     bowersj2 3587: =pod
                   3588: 
                   3589: =back
                   3590: 
                   3591: =cut
                   3592: 
1.37      matthew  3593: ###############################################
1.51      www      3594: 
                   3595: 
                   3596: sub timehash {
1.687     raeburn  3597:     my ($thistime) = @_;
                   3598:     my $timezone = &Apache::lonlocal::gettimezone();
                   3599:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   3600:                      ->set_time_zone($timezone);
                   3601:     my $wday = $dt->day_of_week();
                   3602:     if ($wday == 7) { $wday = 0; }
                   3603:     return ( 'second' => $dt->second(),
                   3604:              'minute' => $dt->minute(),
                   3605:              'hour'   => $dt->hour(),
                   3606:              'day'     => $dt->day_of_month(),
                   3607:              'month'   => $dt->month(),
                   3608:              'year'    => $dt->year(),
                   3609:              'weekday' => $wday,
                   3610:              'dayyear' => $dt->day_of_year(),
                   3611:              'dlsav'   => $dt->is_dst() );
1.51      www      3612: }
                   3613: 
1.370     www      3614: sub utc_string {
                   3615:     my ($date)=@_;
1.371     www      3616:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      3617: }
                   3618: 
1.51      www      3619: sub maketime {
                   3620:     my %th=@_;
1.687     raeburn  3621:     my ($epoch_time,$timezone,$dt);
                   3622:     $timezone = &Apache::lonlocal::gettimezone();
                   3623:     eval {
                   3624:         $dt = DateTime->new( year   => $th{'year'},
                   3625:                              month  => $th{'month'},
                   3626:                              day    => $th{'day'},
                   3627:                              hour   => $th{'hour'},
                   3628:                              minute => $th{'minute'},
                   3629:                              second => $th{'second'},
                   3630:                              time_zone => $timezone,
                   3631:                          );
                   3632:     };
                   3633:     if (!$@) {
                   3634:         $epoch_time = $dt->epoch;
                   3635:         if ($epoch_time) {
                   3636:             return $epoch_time;
                   3637:         }
                   3638:     }
1.51      www      3639:     return POSIX::mktime(
                   3640:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      3641:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      3642: }
                   3643: 
                   3644: #########################################
1.51      www      3645: 
                   3646: sub findallcourses {
1.482     raeburn  3647:     my ($roles,$uname,$udom) = @_;
1.355     albertel 3648:     my %roles;
                   3649:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 3650:     my %courses;
1.51      www      3651:     my $now=time;
1.482     raeburn  3652:     if (!defined($uname)) {
                   3653:         $uname = $env{'user.name'};
                   3654:     }
                   3655:     if (!defined($udom)) {
                   3656:         $udom = $env{'user.domain'};
                   3657:     }
                   3658:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   3659:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
                   3660:         if (!%roles) {
                   3661:             %roles = (
                   3662:                        cc => 1,
                   3663:                        in => 1,
                   3664:                        ep => 1,
                   3665:                        ta => 1,
                   3666:                        cr => 1,
                   3667:                        st => 1,
                   3668:              );
                   3669:         }
                   3670:         foreach my $entry (keys(%roleshash)) {
                   3671:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   3672:             if ($trole =~ /^cr/) { 
                   3673:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   3674:             } else {
                   3675:                 next if (!exists($roles{$trole}));
                   3676:             }
                   3677:             if ($tend) {
                   3678:                 next if ($tend < $now);
                   3679:             }
                   3680:             if ($tstart) {
                   3681:                 next if ($tstart > $now);
                   3682:             }
                   3683:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
                   3684:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
                   3685:             if ($secpart eq '') {
                   3686:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   3687:                 $sec = 'none';
                   3688:                 $realsec = '';
                   3689:             } else {
                   3690:                 $cnum = $cnumpart;
                   3691:                 ($sec,$role) = split(/_/,$secpart);
                   3692:                 $realsec = $sec;
1.490     raeburn  3693:             }
1.482     raeburn  3694:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
                   3695:         }
                   3696:     } else {
                   3697:         foreach my $key (keys(%env)) {
1.483     albertel 3698: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   3699:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  3700: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   3701: 	        next if ($role eq 'ca' || $role eq 'aa');
                   3702: 	        next if (%roles && !exists($roles{$role}));
                   3703: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   3704:                 my $active=1;
                   3705:                 if ($starttime) {
                   3706: 		    if ($now<$starttime) { $active=0; }
                   3707:                 }
                   3708:                 if ($endtime) {
                   3709:                     if ($now>$endtime) { $active=0; }
                   3710:                 }
                   3711:                 if ($active) {
                   3712:                     if ($sec eq '') {
                   3713:                         $sec = 'none';
                   3714:                     }
                   3715:                     $courses{$cdom.'_'.$cnum}{$sec} = 
                   3716:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
1.474     raeburn  3717:                 }
                   3718:             }
1.51      www      3719:         }
                   3720:     }
1.474     raeburn  3721:     return %courses;
1.51      www      3722: }
1.37      matthew  3723: 
1.54      www      3724: ###############################################
1.474     raeburn  3725: 
                   3726: sub blockcheck {
1.482     raeburn  3727:     my ($setters,$activity,$uname,$udom) = @_;
1.490     raeburn  3728: 
                   3729:     if (!defined($udom)) {
                   3730:         $udom = $env{'user.domain'};
                   3731:     }
                   3732:     if (!defined($uname)) {
                   3733:         $uname = $env{'user.name'};
                   3734:     }
                   3735: 
                   3736:     # If uname and udom are for a course, check for blocks in the course.
                   3737: 
                   3738:     if (&Apache::lonnet::is_course($udom,$uname)) {
                   3739:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
1.502     raeburn  3740:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
1.490     raeburn  3741:         return ($startblock,$endblock);
                   3742:     }
1.474     raeburn  3743: 
1.502     raeburn  3744:     my $startblock = 0;
                   3745:     my $endblock = 0;
1.482     raeburn  3746:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  3747: 
1.490     raeburn  3748:     # If uname is for a user, and activity is course-specific, i.e.,
                   3749:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  3750: 
1.490     raeburn  3751:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   3752:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   3753:         foreach my $key (keys(%live_courses)) {
                   3754:             if ($key ne $env{'request.course.id'}) {
                   3755:                 delete($live_courses{$key});
                   3756:             }
                   3757:         }
                   3758:     }
                   3759: 
                   3760:     my $otheruser = 0;
                   3761:     my %own_courses;
                   3762:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   3763:         # Resource belongs to user other than current user.
                   3764:         $otheruser = 1;
                   3765:         # Gather courses for current user
                   3766:         %own_courses = 
                   3767:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   3768:     }
                   3769: 
                   3770:     # Gather active course roles - course coordinator, instructor, 
                   3771:     # exam proctor, ta, student, or custom role.
1.474     raeburn  3772: 
                   3773:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  3774:         my ($cdom,$cnum);
                   3775:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   3776:             $cdom = $env{'course.'.$course.'.domain'};
                   3777:             $cnum = $env{'course.'.$course.'.num'};
                   3778:         } else {
1.490     raeburn  3779:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  3780:         }
                   3781:         my $no_ownblock = 0;
                   3782:         my $no_userblock = 0;
1.533     raeburn  3783:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  3784:             # Check if current user has 'evb' priv for this
                   3785:             if (defined($own_courses{$course})) {
                   3786:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   3787:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   3788:                     if ($sec ne 'none') {
                   3789:                         $checkrole .= '/'.$sec;
                   3790:                     }
                   3791:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3792:                         $no_ownblock = 1;
                   3793:                         last;
                   3794:                     }
                   3795:                 }
                   3796:             }
                   3797:             # if they have 'evb' priv and are currently not playing student
                   3798:             next if (($no_ownblock) &&
                   3799:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   3800:         }
1.474     raeburn  3801:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  3802:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  3803:             if ($sec ne 'none') {
1.482     raeburn  3804:                 $checkrole .= '/'.$sec;
1.474     raeburn  3805:             }
1.490     raeburn  3806:             if ($otheruser) {
                   3807:                 # Resource belongs to user other than current user.
                   3808:                 # Assemble privs for that user, and check for 'evb' priv.
1.482     raeburn  3809:                 my ($trole,$tdom,$tnum,$tsec);
                   3810:                 my $entry = $live_courses{$course}{$sec};
                   3811:                 if ($entry =~ /^cr/) {
                   3812:                     ($trole,$tdom,$tnum,$tsec) = 
                   3813:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   3814:                 } else {
                   3815:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   3816:                 }
                   3817:                 my ($spec,$area,$trest,%allroles,%userroles);
                   3818:                 $area = '/'.$tdom.'/'.$tnum;
                   3819:                 $trest = $tnum;
                   3820:                 if ($tsec ne '') {
                   3821:                     $area .= '/'.$tsec;
                   3822:                     $trest .= '/'.$tsec;
                   3823:                 }
                   3824:                 $spec = $trole.'.'.$area;
                   3825:                 if ($trole =~ /^cr/) {
                   3826:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   3827:                                                       $tdom,$spec,$trest,$area);
                   3828:                 } else {
                   3829:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   3830:                                                        $tdom,$spec,$trest,$area);
                   3831:                 }
                   3832:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.486     raeburn  3833:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   3834:                     if ($1) {
                   3835:                         $no_userblock = 1;
                   3836:                         last;
                   3837:                     }
                   3838:                 }
1.490     raeburn  3839:             } else {
                   3840:                 # Resource belongs to current user
                   3841:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  3842:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   3843:                     $no_ownblock = 1;
                   3844:                     last;
                   3845:                 }
1.474     raeburn  3846:             }
                   3847:         }
                   3848:         # if they have the evb priv and are currently not playing student
1.482     raeburn  3849:         next if (($no_ownblock) &&
1.491     albertel 3850:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  3851:         next if ($no_userblock);
1.474     raeburn  3852: 
1.490     raeburn  3853:         # Retrieve blocking times and identity of blocker for course
                   3854:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  3855:         
                   3856:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
                   3857:         if (($start != 0) && 
                   3858:             (($startblock == 0) || ($startblock > $start))) {
                   3859:             $startblock = $start;
                   3860:         }
                   3861:         if (($end != 0)  &&
                   3862:             (($endblock == 0) || ($endblock < $end))) {
                   3863:             $endblock = $end;
                   3864:         }
1.490     raeburn  3865:     }
                   3866:     return ($startblock,$endblock);
                   3867: }
                   3868: 
                   3869: sub get_blocks {
                   3870:     my ($setters,$activity,$cdom,$cnum) = @_;
                   3871:     my $startblock = 0;
                   3872:     my $endblock = 0;
                   3873:     my $course = $cdom.'_'.$cnum;
                   3874:     $setters->{$course} = {};
                   3875:     $setters->{$course}{'staff'} = [];
                   3876:     $setters->{$course}{'times'} = [];
                   3877:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   3878:     foreach my $record (keys(%records)) {
                   3879:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
                   3880:         if ($start <= time && $end >= time) {
                   3881:             my ($staff_name,$staff_dom,$title,$blocks) =
                   3882:                 &parse_block_record($records{$record});
                   3883:             if ($blocks->{$activity} eq 'on') {
                   3884:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   3885:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
1.491     albertel 3886:                 if ( ($startblock == 0) || ($startblock > $start) ) {
                   3887:                     $startblock = $start;
1.490     raeburn  3888:                 }
1.491     albertel 3889:                 if ( ($endblock == 0) || ($endblock < $end) ) {
                   3890:                     $endblock = $end;
1.474     raeburn  3891:                 }
                   3892:             }
                   3893:         }
                   3894:     }
                   3895:     return ($startblock,$endblock);
                   3896: }
                   3897: 
                   3898: sub parse_block_record {
                   3899:     my ($record) = @_;
                   3900:     my ($setuname,$setudom,$title,$blocks);
                   3901:     if (ref($record) eq 'HASH') {
                   3902:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   3903:         $title = &unescape($record->{'event'});
                   3904:         $blocks = $record->{'blocks'};
                   3905:     } else {
                   3906:         my @data = split(/:/,$record,3);
                   3907:         if (scalar(@data) eq 2) {
                   3908:             $title = $data[1];
                   3909:             ($setuname,$setudom) = split(/@/,$data[0]);
                   3910:         } else {
                   3911:             ($setuname,$setudom,$title) = @data;
                   3912:         }
                   3913:         $blocks = { 'com' => 'on' };
                   3914:     }
                   3915:     return ($setuname,$setudom,$title,$blocks);
                   3916: }
                   3917: 
                   3918: sub build_block_table {
                   3919:     my ($startblock,$endblock,$setters) = @_;
                   3920:     my %lt = &Apache::lonlocal::texthash(
                   3921:         'cacb' => 'Currently active communication blocks',
                   3922:         'cour' => 'Course',
                   3923:         'dura' => 'Duration',
                   3924:         'blse' => 'Block set by'
                   3925:     );
                   3926:     my $output;
1.476     raeburn  3927:     $output = '<br />'.$lt{'cacb'}.':<br />';
1.474     raeburn  3928:     $output .= &start_data_table();
                   3929:     $output .= '
                   3930: <tr>
                   3931:  <th>'.$lt{'cour'}.'</th>
                   3932:  <th>'.$lt{'dura'}.'</th>
                   3933:  <th>'.$lt{'blse'}.'</th>
                   3934: </tr>
                   3935: ';
                   3936:     foreach my $course (keys(%{$setters})) {
                   3937:         my %courseinfo=&Apache::lonnet::coursedescription($course);
                   3938:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
                   3939:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
1.490     raeburn  3940:             my $fullname = &plainname($uname,$udom);
                   3941:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
                   3942:                 && $env{'user.name'} ne 'public' 
                   3943:                 && $env{'user.domain'} ne 'public') {
                   3944:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
                   3945:             }
1.474     raeburn  3946:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
                   3947:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
                   3948:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
                   3949:             $output .= &Apache::loncommon::start_data_table_row().
                   3950:                        '<td>'.$courseinfo{'description'}.'</td>'.
                   3951:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
1.490     raeburn  3952:                        '<td>'.$fullname.'</td>'.
1.474     raeburn  3953:                         &Apache::loncommon::end_data_table_row();
                   3954:         }
                   3955:     }
                   3956:     $output .= &end_data_table();
                   3957: }
                   3958: 
1.490     raeburn  3959: sub blocking_status {
                   3960:     my ($activity,$uname,$udom) = @_;
                   3961:     my %setters;
                   3962:     my ($blocked,$output,$ownitem,$is_course);
                   3963:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
                   3964:     if ($startblock && $endblock) {
                   3965:         $blocked = 1;
                   3966:         if (wantarray) {
                   3967:             my $category;
                   3968:             if ($activity eq 'boards') {
                   3969:                 $category = 'Discussion posts in this course';
                   3970:             } elsif ($activity eq 'blogs') {
                   3971:                 $category = 'Blogs';
                   3972:             } elsif ($activity eq 'port') {
                   3973:                 if (defined($uname) && defined($udom)) {
                   3974:                     if ($uname eq $env{'user.name'} &&
                   3975:                         $udom eq $env{'user.domain'}) {
                   3976:                         $ownitem = 1;
                   3977:                     }
                   3978:                 }
                   3979:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
                   3980:                 if ($ownitem) { 
                   3981:                     $category = 'Your portfolio files';  
                   3982:                 } elsif ($is_course) {
                   3983:                     my $coursedesc;
                   3984:                     foreach my $course (keys(%setters)) {
                   3985:                         my %courseinfo =
                   3986:                              &Apache::lonnet::coursedescription($course);
                   3987:                         $coursedesc = $courseinfo{'description'};
                   3988:                     }
1.692.4.2  raeburn  3989:                     $category = "Group portfolio files in the course '$coursedesc'";
1.490     raeburn  3990:                 } else {
                   3991:                     $category = 'Portfolio files belonging to ';
                   3992:                     if ($env{'user.name'} eq 'public' && 
                   3993:                         $env{'user.domain'} eq 'public') {
                   3994:                         $category .= &plainname($uname,$udom);
                   3995:                     } else {
                   3996:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
                   3997:                     }
                   3998:                 }
                   3999:             } elsif ($activity eq 'groups') {
                   4000:                 $category = 'Groups in this course';
                   4001:             }
                   4002:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
                   4003:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
                   4004:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
                   4005:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
                   4006:                 $output .= &build_block_table($startblock,$endblock,\%setters);
                   4007:             }
                   4008:         }
                   4009:     }
                   4010:     if (wantarray) {
                   4011:         return ($blocked,$output);
                   4012:     } else {
                   4013:         return $blocked;
                   4014:     }
                   4015: }
                   4016: 
1.60      matthew  4017: ###############################################
                   4018: 
1.682     raeburn  4019: sub check_ip_acc {
                   4020:     my ($acc)=@_;
                   4021:     &Apache::lonxml::debug("acc is $acc");
                   4022:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4023:         return 1;
                   4024:     }
                   4025:     my $allowed=0;
                   4026:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4027: 
                   4028:     my $name;
                   4029:     foreach my $pattern (split(',',$acc)) {
                   4030:         $pattern =~ s/^\s*//;
                   4031:         $pattern =~ s/\s*$//;
                   4032:         if ($pattern =~ /\*$/) {
                   4033:             #35.8.*
                   4034:             $pattern=~s/\*//;
                   4035:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4036:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4037:             #35.8.3.[34-56]
                   4038:             my $low=$2;
                   4039:             my $high=$3;
                   4040:             $pattern=$1;
                   4041:             if ($ip =~ /^\Q$pattern\E/) {
                   4042:                 my $last=(split(/\./,$ip))[3];
                   4043:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4044:             }
                   4045:         } elsif ($pattern =~ /^\*/) {
                   4046:             #*.msu.edu
                   4047:             $pattern=~s/\*//;
                   4048:             if (!defined($name)) {
                   4049:                 use Socket;
                   4050:                 my $netaddr=inet_aton($ip);
                   4051:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4052:             }
                   4053:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4054:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4055:             #127.0.0.1
                   4056:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4057:         } else {
                   4058:             #some.name.com
                   4059:             if (!defined($name)) {
                   4060:                 use Socket;
                   4061:                 my $netaddr=inet_aton($ip);
                   4062:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4063:             }
                   4064:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4065:         }
                   4066:         if ($allowed) { last; }
                   4067:     }
                   4068:     return $allowed;
                   4069: }
                   4070: 
                   4071: ###############################################
                   4072: 
1.60      matthew  4073: =pod
                   4074: 
1.112     bowersj2 4075: =head1 Domain Template Functions
                   4076: 
                   4077: =over 4
                   4078: 
                   4079: =item * &determinedomain()
1.60      matthew  4080: 
                   4081: Inputs: $domain (usually will be undef)
                   4082: 
1.63      www      4083: Returns: Determines which domain should be used for designs
1.60      matthew  4084: 
                   4085: =cut
1.54      www      4086: 
1.60      matthew  4087: ###############################################
1.63      www      4088: sub determinedomain {
                   4089:     my $domain=shift;
1.531     albertel 4090:     if (! $domain) {
1.60      matthew  4091:         # Determine domain if we have not been given one
                   4092:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1.258     albertel 4093:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4094:         if ($env{'request.role.domain'}) { 
                   4095:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4096:         }
                   4097:     }
1.63      www      4098:     return $domain;
                   4099: }
                   4100: ###############################################
1.517     raeburn  4101: 
1.518     albertel 4102: sub devalidate_domconfig_cache {
                   4103:     my ($udom)=@_;
                   4104:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4105: }
                   4106: 
                   4107: # ---------------------- Get domain configuration for a domain
                   4108: sub get_domainconf {
                   4109:     my ($udom) = @_;
                   4110:     my $cachetime=1800;
                   4111:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4112:     if (defined($cached)) { return %{$result}; }
                   4113: 
                   4114:     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   4115: 					     ['login','rolecolors'],$udom);
1.632     raeburn  4116:     my (%designhash,%legacy);
1.518     albertel 4117:     if (keys(%domconfig) > 0) {
                   4118:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4119:             if (keys(%{$domconfig{'login'}})) {
                   4120:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.692.4.2  raeburn  4121:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   4122:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4123:                             $designhash{$udom.'.login.'.$key.'_'.$img} =
                   4124:                                 $domconfig{'login'}{$key}{$img};
                   4125:                         }
                   4126:                     } else {
                   4127:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4128:                     }
1.632     raeburn  4129:                 }
                   4130:             } else {
                   4131:                 $legacy{'login'} = 1;
1.518     albertel 4132:             }
1.632     raeburn  4133:         } else {
                   4134:             $legacy{'login'} = 1;
1.518     albertel 4135:         }
                   4136:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4137:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4138:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4139:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4140:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4141:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4142:                         }
1.518     albertel 4143:                     }
                   4144:                 }
1.632     raeburn  4145:             } else {
                   4146:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4147:             }
1.632     raeburn  4148:         } else {
                   4149:             $legacy{'rolecolors'} = 1;
1.518     albertel 4150:         }
1.632     raeburn  4151:         if (keys(%legacy) > 0) {
                   4152:             my %legacyhash = &get_legacy_domconf($udom);
                   4153:             foreach my $item (keys(%legacyhash)) {
                   4154:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4155:                     if ($legacy{'login'}) { 
                   4156:                         $designhash{$item} = $legacyhash{$item};
                   4157:                     }
                   4158:                 } else {
                   4159:                     if ($legacy{'rolecolors'}) {
                   4160:                         $designhash{$item} = $legacyhash{$item};
                   4161:                     }
1.518     albertel 4162:                 }
                   4163:             }
                   4164:         }
1.632     raeburn  4165:     } else {
                   4166:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4167:     }
                   4168:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4169: 				  $cachetime);
                   4170:     return %designhash;
                   4171: }
                   4172: 
1.632     raeburn  4173: sub get_legacy_domconf {
                   4174:     my ($udom) = @_;
                   4175:     my %legacyhash;
                   4176:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4177:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4178:     if (-e $designfile) {
                   4179:         if ( open (my $fh,"<$designfile") ) {
                   4180:             while (my $line = <$fh>) {
                   4181:                 next if ($line =~ /^\#/);
                   4182:                 chomp($line);
                   4183:                 my ($key,$val)=(split(/\=/,$line));
                   4184:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4185:             }
                   4186:             close($fh);
                   4187:         }
                   4188:     }
                   4189:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
                   4190:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4191:     }
                   4192:     return %legacyhash;
                   4193: }
                   4194: 
1.63      www      4195: =pod
                   4196: 
1.112     bowersj2 4197: =item * &domainlogo()
1.63      www      4198: 
                   4199: Inputs: $domain (usually will be undef)
                   4200: 
                   4201: Returns: A link to a domain logo, if the domain logo exists.
                   4202: If the domain logo does not exist, a description of the domain.
                   4203: 
                   4204: =cut
1.112     bowersj2 4205: 
1.63      www      4206: ###############################################
                   4207: sub domainlogo {
1.517     raeburn  4208:     my $domain = &determinedomain(shift);
1.518     albertel 4209:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4210:     # See if there is a logo
                   4211:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4212:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4213:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4214: 	    if ($imgsrc =~ m{^/res/}) {
                   4215: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4216: 		&Apache::lonnet::repcopy($local_name);
                   4217: 	    }
                   4218: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4219:         } 
                   4220:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4221:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4222:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4223:     } else {
1.60      matthew  4224:         return '';
1.59      www      4225:     }
                   4226: }
1.63      www      4227: ##############################################
                   4228: 
                   4229: =pod
                   4230: 
1.112     bowersj2 4231: =item * &designparm()
1.63      www      4232: 
                   4233: Inputs: $which parameter; $domain (usually will be undef)
                   4234: 
                   4235: Returns: value of designparamter $which
                   4236: 
                   4237: =cut
1.112     bowersj2 4238: 
1.397     albertel 4239: 
1.400     albertel 4240: ##############################################
1.397     albertel 4241: sub designparm {
                   4242:     my ($which,$domain)=@_;
1.258     albertel 4243:     if ($env{'browser.blackwhite'} eq 'on') {
1.635     raeburn  4244: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
1.110     www      4245: 	    return '#000000';
                   4246: 	}
1.635     raeburn  4247: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
1.110     www      4248: 	    return '#FFFFFF';
                   4249: 	}
                   4250: 	if ($which=~/\.tabbg$/) {
                   4251: 	    return '#CCCCCC';
                   4252: 	}
                   4253:     }
1.397     albertel 4254:     if (exists($env{'environment.color.'.$which})) {
1.258     albertel 4255: 	return $env{'environment.color.'.$which};
1.96      www      4256:     }
1.63      www      4257:     $domain=&determinedomain($domain);
1.518     albertel 4258:     my %domdesign = &get_domainconf($domain);
1.520     raeburn  4259:     my $output;
1.517     raeburn  4260:     if ($domdesign{$domain.'.'.$which} ne '') {
1.520     raeburn  4261: 	$output = $domdesign{$domain.'.'.$which};
1.63      www      4262:     } else {
1.520     raeburn  4263:         $output = $defaultdesign{$which};
                   4264:     }
                   4265:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4266:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4267:         if ($output =~ m{^/(adm|res)/}) {
                   4268: 	    if ($output =~ m{^/res/}) {
                   4269: 		my $local_name = &Apache::lonnet::filelocation('',$output);
                   4270: 		&Apache::lonnet::repcopy($local_name);
                   4271: 	    }
1.520     raeburn  4272:             $output = &lonhttpdurl($output);
                   4273:         }
1.63      www      4274:     }
1.520     raeburn  4275:     return $output;
1.63      www      4276: }
1.59      www      4277: 
1.60      matthew  4278: ###############################################
                   4279: ###############################################
                   4280: 
                   4281: =pod
                   4282: 
1.112     bowersj2 4283: =back
                   4284: 
1.549     albertel 4285: =head1 HTML Helpers
1.112     bowersj2 4286: 
                   4287: =over 4
                   4288: 
                   4289: =item * &bodytag()
1.60      matthew  4290: 
                   4291: Returns a uniform header for LON-CAPA web pages.
                   4292: 
                   4293: Inputs: 
                   4294: 
1.112     bowersj2 4295: =over 4
                   4296: 
                   4297: =item * $title, A title to be displayed on the page.
                   4298: 
                   4299: =item * $function, the current role (can be undef).
                   4300: 
                   4301: =item * $addentries, extra parameters for the <body> tag.
                   4302: 
                   4303: =item * $bodyonly, if defined, only return the <body> tag.
                   4304: 
                   4305: =item * $domain, if defined, force a given domain.
                   4306: 
                   4307: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      4308:             text interface only)
1.60      matthew  4309: 
1.326     albertel 4310: =item * $customtitle, alternate text to use instead of $title
                   4311:                       in the title box that appears, this text
                   4312:                       is not auto translated like the $title is
1.309     albertel 4313: 
                   4314: =item * $notopbar, if true, keep the 'what is this' info but remove the
                   4315:                    navigational links
1.317     albertel 4316: 
1.338     albertel 4317: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   4318: 
                   4319: =item * $notitle, if true keep the nav controls, but remove the title bar
                   4320: 
1.361     albertel 4321: =item * $no_inline_link, if true and in remote mode, don't show the 
                   4322:          'Switch To Inline Menu' link
                   4323: 
1.460     albertel 4324: =item * $args, optional argument valid values are
                   4325:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 4326:             inherit_jsmath -> when creating popup window in a page,
                   4327:                               should it have jsmath forced on by the
                   4328:                               current page
1.460     albertel 4329: 
1.112     bowersj2 4330: =back
                   4331: 
1.60      matthew  4332: Returns: A uniform header for LON-CAPA web pages.  
                   4333: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   4334: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   4335: other decorations will be returned.
                   4336: 
                   4337: =cut
                   4338: 
1.54      www      4339: sub bodytag {
1.309     albertel 4340:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
1.460     albertel 4341: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
1.339     albertel 4342: 
1.460     albertel 4343:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 4344: 
1.183     matthew  4345:     $function = &get_users_function() if (!$function);
1.339     albertel 4346:     my $img =    &designparm($function.'.img',$domain);
                   4347:     my $font =   &designparm($function.'.font',$domain);
                   4348:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   4349: 
1.692.4.2  raeburn  4350:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 4351: 		   'bgcolor' => $pgbg,
1.339     albertel 4352: 		   'text'    => $font,
                   4353:                    'alink'   => &designparm($function.'.alink',$domain),
                   4354: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   4355: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 4356:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 4357: 
1.63      www      4358:  # role and realm
1.378     raeburn  4359:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   4360:     if ($role  eq 'ca') {
1.479     albertel 4361:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 4362:         $realm = &plainname($rname,$rdom);
1.378     raeburn  4363:     } 
1.55      www      4364: # realm
1.258     albertel 4365:     if ($env{'request.course.id'}) {
1.378     raeburn  4366:         if ($env{'request.role'} !~ /^cr/) {
                   4367:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   4368:         }
1.359     albertel 4369: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  4370:     } else {
                   4371:         $role = &Apache::lonnet::plaintext($role);
1.54      www      4372:     }
1.433     albertel 4373: 
1.359     albertel 4374:     if (!$realm) { $realm='&nbsp;'; }
1.55      www      4375: # Set messages
1.60      matthew  4376:     my $messages=&domainlogo($domain);
1.330     albertel 4377: 
1.438     albertel 4378:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 4379: 
1.101     www      4380: # construct main body tag
1.359     albertel 4381:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 4382: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 4383: 
1.530     albertel 4384:     if ($bodyonly) {
1.60      matthew  4385:         return $bodytag;
1.258     albertel 4386:     } elsif ($env{'browser.interface'} eq 'textual') {
1.95      www      4387: # Accessibility
1.224     raeburn  4388:           
1.337     albertel 4389: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
1.338     albertel 4390: 	if (!$notitle) {
1.337     albertel 4391: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
                   4392: 	}
                   4393: 	return $bodytag;
1.359     albertel 4394:     }
                   4395: 
1.410     albertel 4396:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.433     albertel 4397:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4398: 	undef($role);
1.434     albertel 4399:     } else {
                   4400: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
1.433     albertel 4401:     }
1.359     albertel 4402:     
                   4403:     my $roleinfo=(<<ENDROLE);
                   4404: <td class="LC_title_bar_who">
                   4405: <div class="LC_title_bar_name">
1.410     albertel 4406:     $name
1.361     albertel 4407:     &nbsp;
1.359     albertel 4408: </div>
                   4409: <div class="LC_title_bar_role">
1.361     albertel 4410: $role&nbsp;
1.359     albertel 4411: </div>
                   4412: <div class="LC_title_bar_realm">
1.361     albertel 4413: $realm&nbsp;
1.359     albertel 4414: </div>
1.206     albertel 4415: </td>
                   4416: ENDROLE
1.235     raeburn  4417: 
1.359     albertel 4418:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
                   4419:     if ($customtitle) {
                   4420:         $titleinfo = $customtitle;
                   4421:     }
                   4422:     #
                   4423:     # Extra info if you are the DC
                   4424:     my $dc_info = '';
                   4425:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   4426:                         $env{'course.'.$env{'request.course.id'}.
                   4427:                                  '.domain'}.'/'})) {
                   4428:         my $cid = $env{'request.course.id'};
                   4429:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      4430:         $dc_info =~ s/\s+$//;
1.359     albertel 4431:         $dc_info = '('.$dc_info.')';
                   4432:     }
                   4433: 
1.644     www      4434:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
1.359     albertel 4435:         # No Remote
1.258     albertel 4436: 	if ($env{'request.state'} eq 'construct') {
1.359     albertel 4437: 	    $forcereg=1;
                   4438: 	}
                   4439: 
                   4440: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
                   4441: 	    # this is for resources; directories have customtitle, and crumbs
                   4442:             # and select recent are created in lonpubdir.pm  
1.229     albertel 4443: 	    my ($uname,$thisdisfn)=
1.258     albertel 4444: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
1.229     albertel 4445: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
                   4446: 	    $formaction=~s/\/+/\//g;
                   4447: 
1.359     albertel 4448: 	    my $parentpath = '';
                   4449: 	    my $lastitem = '';
                   4450: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4451: 		$parentpath = $1;
                   4452: 		$lastitem = $2;
                   4453: 	    } else {
                   4454: 		$lastitem = $thisdisfn;
                   4455: 	    }
                   4456: 	    $titleinfo = 
1.640     bisitz   4457: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
                   4458: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
                   4459: 		.'<form name="dirs" method="post" action="'.$formaction
1.359     albertel 4460: 		.'" target="_top"><tt><b>'
                   4461: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
                   4462: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4463: 		.'</form>'
                   4464: 		.&Apache::lonmenu::constspaceform();
1.235     raeburn  4465:         }
1.359     albertel 4466: 
1.337     albertel 4467:         my $titletable;
1.338     albertel 4468: 	if (!$notitle) {
1.337     albertel 4469: 	    $titletable =
1.359     albertel 4470: 		'<table id="LC_title_bar">'.
                   4471:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
                   4472: 			 '</tr></table>';
1.337     albertel 4473: 	}
1.359     albertel 4474: 	if ($notopbar) {
                   4475: 	    $bodytag .= $titletable;
                   4476: 	} else {
                   4477: 	    if ($env{'request.state'} eq 'construct') {
1.337     albertel 4478:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
                   4479: 							  $titletable);
1.272     raeburn  4480:             } else {
1.336     albertel 4481:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
1.359     albertel 4482: 		    $titletable;
1.272     raeburn  4483:             }
1.235     raeburn  4484:         }
                   4485:         return $bodytag;
1.94      www      4486:     }
1.95      www      4487: 
1.93      www      4488: #
1.95      www      4489: # Top frame rendering, Remote is up
1.93      www      4490: #
1.359     albertel 4491: 
1.517     raeburn  4492:     my $imgsrc = $img;
                   4493:     if ($img =~ /^\/adm/) {
1.575     albertel 4494:         $imgsrc = &lonhttpdurl($img);
1.517     raeburn  4495:     }
                   4496:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
1.359     albertel 4497: 
1.305     www      4498:     # Explicit link to get inline menu
1.361     albertel 4499:     my $menu= ($no_inline_link?''
                   4500: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
1.245     matthew  4501:     #
1.338     albertel 4502:     if ($notitle) {
1.337     albertel 4503: 	return $bodytag;
                   4504:     }
1.94      www      4505:     return(<<ENDBODY);
1.60      matthew  4506: $bodytag
1.359     albertel 4507: <table id="LC_title_bar" class="LC_with_remote">
1.368     albertel 4508: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
1.359     albertel 4509:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
1.54      www      4510: </tr>
1.359     albertel 4511: <tr><td>$titleinfo $dc_info $menu</td>
                   4512: $roleinfo
1.368     albertel 4513: </tr>
1.356     albertel 4514: </table>
1.54      www      4515: ENDBODY
1.182     matthew  4516: }
                   4517: 
1.330     albertel 4518: sub make_attr_string {
                   4519:     my ($register,$attr_ref) = @_;
                   4520: 
                   4521:     if ($attr_ref && !ref($attr_ref)) {
                   4522: 	die("addentries Must be a hash ref ".
                   4523: 	    join(':',caller(1))." ".
                   4524: 	    join(':',caller(0))." ");
                   4525:     }
                   4526: 
                   4527:     if ($register) {
1.339     albertel 4528: 	my ($on_load,$on_unload);
                   4529: 	foreach my $key (keys(%{$attr_ref})) {
                   4530: 	    if      (lc($key) eq 'onload') {
                   4531: 		$on_load.=$attr_ref->{$key}.';';
                   4532: 		delete($attr_ref->{$key});
                   4533: 
                   4534: 	    } elsif (lc($key) eq 'onunload') {
                   4535: 		$on_unload.=$attr_ref->{$key}.';';
                   4536: 		delete($attr_ref->{$key});
                   4537: 	    }
                   4538: 	}
                   4539: 	$attr_ref->{'onload'}  =
                   4540: 	    &Apache::lonmenu::loadevents().  $on_load;
                   4541: 	$attr_ref->{'onunload'}=
                   4542: 	    &Apache::lonmenu::unloadevents().$on_unload;
                   4543:     }
                   4544: 
                   4545: # Accessibility font enhance
                   4546:     if ($env{'browser.fontenhance'} eq 'on') {
                   4547: 	my $style;
                   4548: 	foreach my $key (keys(%{$attr_ref})) {
                   4549: 	    if (lc($key) eq 'style') {
                   4550: 		$style.=$attr_ref->{$key}.';';
                   4551: 		delete($attr_ref->{$key});
                   4552: 	    }
                   4553: 	}
                   4554: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
1.330     albertel 4555:     }
1.339     albertel 4556: 
                   4557:     if ($env{'browser.blackwhite'} eq 'on') {
                   4558: 	delete($attr_ref->{'font'});
                   4559: 	delete($attr_ref->{'link'});
                   4560: 	delete($attr_ref->{'alink'});
                   4561: 	delete($attr_ref->{'vlink'});
                   4562: 	delete($attr_ref->{'bgcolor'});
                   4563: 	delete($attr_ref->{'background'});
                   4564:     }
                   4565: 
1.330     albertel 4566:     my $attr_string;
                   4567:     foreach my $attr (keys(%$attr_ref)) {
                   4568: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   4569:     }
                   4570:     return $attr_string;
                   4571: }
                   4572: 
                   4573: 
1.182     matthew  4574: ###############################################
1.251     albertel 4575: ###############################################
                   4576: 
                   4577: =pod
                   4578: 
                   4579: =item * &endbodytag()
                   4580: 
                   4581: Returns a uniform footer for LON-CAPA web pages.
                   4582: 
1.635     raeburn  4583: Inputs: 1 - optional reference to an args hash
                   4584: If in the hash, key for noredirectlink has a value which evaluates to true,
                   4585: a 'Continue' link is not displayed if the page contains an
                   4586: internal redirect in the <head></head> section,
                   4587: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 4588: 
                   4589: =cut
                   4590: 
                   4591: sub endbodytag {
1.635     raeburn  4592:     my ($args) = @_;
1.251     albertel 4593:     my $endbodytag='</body>';
1.269     albertel 4594:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 4595:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  4596:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   4597: 	    $endbodytag=
                   4598: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   4599: 	        &mt('Continue').'</a>'.
                   4600: 	        $endbodytag;
                   4601:         }
1.315     albertel 4602:     }
1.251     albertel 4603:     return $endbodytag;
                   4604: }
                   4605: 
1.352     albertel 4606: =pod
                   4607: 
                   4608: =item * &standard_css()
                   4609: 
                   4610: Returns a style sheet
                   4611: 
                   4612: Inputs: (all optional)
                   4613:             domain         -> force to color decorate a page for a specific
                   4614:                                domain
                   4615:             function       -> force usage of a specific rolish color scheme
                   4616:             bgcolor        -> override the default page bgcolor
                   4617: 
                   4618: =cut
                   4619: 
1.343     albertel 4620: sub standard_css {
1.345     albertel 4621:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 4622:     $function  = &get_users_function() if (!$function);
                   4623:     my $img    = &designparm($function.'.img',   $domain);
                   4624:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   4625:     my $font   = &designparm($function.'.font',  $domain);
1.345     albertel 4626:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 4627:     my $pgbg_or_bgcolor =
                   4628: 	         $bgcolor ||
1.352     albertel 4629: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 4630:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 4631:     my $alink  = &designparm($function.'.alink', $domain);
                   4632:     my $vlink  = &designparm($function.'.vlink', $domain);
                   4633:     my $link   = &designparm($function.'.link',  $domain);
                   4634: 
1.602     albertel 4635:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 4636:     my $mono                 = 'monospace';
1.692.4.13  raeburn  4637:     my $data_table_head      = $tabbg;
1.692.4.6  raeburn  4638:     my $data_table_light     = '#FAFAFA';
                   4639:     my $data_table_dark      = '#F0F0F0';
1.470     banghart 4640:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 4641:     my $data_table_highlight = '#FFFF00';
1.352     albertel 4642:     my $mail_new             = '#FFBB77';
                   4643:     my $mail_new_hover       = '#DD9955';
                   4644:     my $mail_read            = '#BBBB77';
                   4645:     my $mail_read_hover      = '#999944';
                   4646:     my $mail_replied         = '#AAAA88';
                   4647:     my $mail_replied_hover   = '#888855';
                   4648:     my $mail_other           = '#99BBBB';
                   4649:     my $mail_other_hover     = '#669999';
1.391     albertel 4650:     my $table_header         = '#DDDDDD';
1.489     raeburn  4651:     my $feedback_link_bg     = '#BBBBBB';
1.692.4.3  raeburn  4652:     my $lg_border_color      = '#C8C8C8';
1.392     albertel 4653: 
1.608     albertel 4654:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.692.4.2  raeburn  4655: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   4656: 	                                                 : '0 3px 0 4px';
1.448     albertel 4657: 
1.523     albertel 4658: 
1.343     albertel 4659:     return <<END;
1.345     albertel 4660: h1, h2, h3, th { font-family: $sans }
1.343     albertel 4661: a:focus { color: red; background: yellow } 
1.692.4.6  raeburn  4662: 
                   4663: hr {
                   4664:   clear: both;
                   4665:   color: $tabbg;
                   4666:   background-color: $tabbg;
                   4667:   height: 3px;
                   4668:   border: none;
                   4669: }
                   4670: 
1.510     albertel 4671: table.thinborder,
1.523     albertel 4672: 
1.510     albertel 4673: table.thinborder tr th {
                   4674:   border-style: solid;
                   4675:   border-width: 1px;
                   4676:   background: $tabbg;
                   4677: }
1.523     albertel 4678: table.thinborder tr td {
1.510     albertel 4679:   border-style: solid;
                   4680:   border-width: 1px
                   4681: }
1.426     albertel 4682: 
1.343     albertel 4683: form, .inline { display: inline; }
                   4684: .center { text-align: center; }
1.593     albertel 4685: .LC_filename {font-family: $mono; white-space:pre;}
1.350     albertel 4686: .LC_error {
                   4687:   color: red;
                   4688:   font-size: larger;
                   4689: }
1.457     albertel 4690: .LC_warning,
                   4691: .LC_diff_removed {
1.394     albertel 4692:   color: red;
                   4693: }
1.532     albertel 4694: 
                   4695: .LC_info,
1.457     albertel 4696: .LC_success,
                   4697: .LC_diff_added {
1.350     albertel 4698:   color: green;
                   4699: }
1.692.4.2  raeburn  4700: 
                   4701: div.LC_confirm_box {
                   4702:   background-color: #FAFAFA;
                   4703:   border: 1px solid $lg_border_color;
                   4704:   margin-right: 0;
                   4705:   padding: 5px;
                   4706: }
                   4707: 
                   4708: div.LC_confirm_box .LC_error img,
                   4709: div.LC_confirm_box .LC_success img {
                   4710:   vertical-align: middle;
1.543     albertel 4711: }
                   4712: 
1.440     albertel 4713: .LC_icon {
1.692.4.2  raeburn  4714:   border: none;
1.440     albertel 4715: }
1.539     albertel 4716: .LC_indexer_icon {
1.692.4.2  raeburn  4717:   border: 0;
1.539     albertel 4718:   height: 22px;
                   4719: }
1.543     albertel 4720: .LC_docs_spacer {
                   4721:   width: 25px;
                   4722:   height: 1px;
1.692.4.2  raeburn  4723:   border: none;
1.543     albertel 4724: }
1.346     albertel 4725: 
1.532     albertel 4726: .LC_internal_info {
1.692.4.2  raeburn  4727:   color: #999999;
1.532     albertel 4728: }
                   4729: 
1.458     albertel 4730: table.LC_pastsubmission {
                   4731:   border: 1px solid black;
                   4732:   margin: 2px;
                   4733: }
                   4734: 
1.606     albertel 4735: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
1.345     albertel 4736:   width: 100%;
                   4737:   background: $pgbg;
1.392     albertel 4738:   border: 2px;
1.402     albertel 4739:   border-collapse: separate;
1.692.4.2  raeburn  4740:   padding: 0;
1.345     albertel 4741: }
1.392     albertel 4742: 
1.606     albertel 4743: table#LC_title_bar, table.LC_breadcrumbs, 
1.393     albertel 4744: table#LC_title_bar.LC_with_remote {
1.359     albertel 4745:   width: 100%;
1.392     albertel 4746:   border-color: $pgbg;
                   4747:   border-style: solid;
                   4748:   border-width: $border;
                   4749: 
1.379     albertel 4750:   background: $pgbg;
                   4751:   font-family: $sans;
1.392     albertel 4752:   border-collapse: collapse;
1.692.4.2  raeburn  4753:   padding: 0;
1.359     albertel 4754: }
1.392     albertel 4755: 
1.409     albertel 4756: table.LC_docs_path {
                   4757:   width: 100%;
                   4758:   border: 0;
                   4759:   background: $pgbg;
                   4760:   font-family: $sans;
                   4761:   border-collapse: collapse;
1.692.4.2  raeburn  4762:   padding: 0;
1.409     albertel 4763: }
                   4764: 
1.359     albertel 4765: table#LC_title_bar td {
                   4766:   background: $tabbg;
                   4767: }
                   4768: table#LC_title_bar td.LC_title_bar_who {
                   4769:   background: $tabbg;
                   4770:   color: $font;
1.427     albertel 4771:   font: small $sans;
1.359     albertel 4772:   text-align: right;
                   4773: }
1.469     banghart 4774: span.LC_metadata {
                   4775:     font-family: $sans;
                   4776: }
1.359     albertel 4777: span.LC_title_bar_title {
1.416     albertel 4778:   font: bold x-large $sans;
1.359     albertel 4779: }
                   4780: table#LC_title_bar td.LC_title_bar_domain_logo {
                   4781:   background: $sidebg;
                   4782:   text-align: right;
1.692.4.2  raeburn  4783:   padding: 0;
1.368     albertel 4784: }
                   4785: table#LC_title_bar td.LC_title_bar_role_logo {
                   4786:   background: $sidebg;
1.692.4.2  raeburn  4787:   padding: 0;
1.359     albertel 4788: }
                   4789: 
1.346     albertel 4790: table#LC_menubuttons_mainmenu {
1.526     www      4791:   width: 100%;
1.692.4.2  raeburn  4792:   border: 0;
1.346     albertel 4793:   border-spacing: 1px;
1.692.4.2  raeburn  4794:   padding: 0 1px;
                   4795:   margin: 0;
1.346     albertel 4796:   border-collapse: separate;
                   4797: }
                   4798: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
1.692.4.2  raeburn  4799:   border: none;
1.346     albertel 4800: }
1.345     albertel 4801: table#LC_top_nav td {
                   4802:   background: $tabbg;
1.692.4.2  raeburn  4803:   border: none;
1.407     albertel 4804:   font-size: small;
1.345     albertel 4805: }
                   4806: table#LC_top_nav td a, div#LC_top_nav a {
                   4807:   color: $font;
                   4808:   font-family: $sans;
                   4809: }
1.364     albertel 4810: table#LC_top_nav td.LC_top_nav_logo {
                   4811:   background: $tabbg;
1.432     albertel 4812:   text-align: left;
1.408     albertel 4813:   white-space: nowrap;
1.432     albertel 4814:   width: 31px;
1.408     albertel 4815: }
                   4816: table#LC_top_nav td.LC_top_nav_logo img {
1.692.4.2  raeburn  4817:   border: none;
1.408     albertel 4818:   vertical-align: bottom;
1.364     albertel 4819: }
1.432     albertel 4820: table#LC_top_nav td.LC_top_nav_exit,
                   4821: table#LC_top_nav td.LC_top_nav_help {
                   4822:   width: 2.0em;
                   4823: }
1.442     albertel 4824: table#LC_top_nav td.LC_top_nav_login {
                   4825:   width: 4.0em;
                   4826:   text-align: center;
                   4827: }
1.409     albertel 4828: table.LC_breadcrumbs td, table.LC_docs_path td  {
1.357     albertel 4829:   background: $tabbg;
                   4830:   color: $font;
                   4831:   font-family: $sans;
1.358     albertel 4832:   font-size: smaller;
1.357     albertel 4833: }
1.411     albertel 4834: table.LC_breadcrumbs td.LC_breadcrumbs_component,
1.409     albertel 4835: table.LC_docs_path td.LC_docs_path_component {
1.357     albertel 4836:   background: $tabbg;
                   4837:   color: $font;
                   4838:   font-family: $sans;
                   4839:   font-size: larger;
                   4840:   text-align: right;
                   4841: }
1.383     albertel 4842: td.LC_table_cell_checkbox {
                   4843:   text-align: center;
                   4844: }
1.522     albertel 4845: table#LC_mainmenu td.LC_mainmenu_column {
                   4846:     vertical-align: top;
                   4847: }
                   4848: 
1.346     albertel 4849: .LC_menubuttons_inline_text {
                   4850:   color: $font;
                   4851:   font-family: $sans;
                   4852:   font-size: smaller;
                   4853: }
                   4854: 
1.526     www      4855: .LC_menubuttons_link {
                   4856:   text-decoration: none;
                   4857: }
1.692.4.2  raeburn  4858: /*2008--9-5: new menu style sheet.Changed category*/
1.522     albertel 4859: .LC_menubuttons_category {
1.521     www      4860:   color: $font;
1.526     www      4861:   background: $pgbg;
1.521     www      4862:   font-family: $sans;
                   4863:   font-size: larger;
                   4864:   font-weight: bold;
                   4865: }
                   4866: 
1.346     albertel 4867: td.LC_menubuttons_text {
1.526     www      4868:   width: 90%;
1.346     albertel 4869:   color: $font;
                   4870:   font-family: $sans;
                   4871: }
1.526     www      4872: 
1.346     albertel 4873: td.LC_menubuttons_img {
                   4874: }
1.526     www      4875: 
1.346     albertel 4876: .LC_current_location {
                   4877:   font-family: $sans;
                   4878:   background: $tabbg;
                   4879: }
                   4880: .LC_new_mail {
                   4881:   font-family: $sans;
1.634     www      4882:   background: $tabbg;
1.346     albertel 4883:   font-weight: bold;
                   4884: }
1.347     albertel 4885: 
1.527     www      4886: .LC_dropadd_labeltext {
                   4887:   font-family: $sans;
                   4888:   text-align: right;
                   4889: }
                   4890: 
                   4891: .LC_preferences_labeltext {
                   4892:   font-family: $sans;
                   4893:   text-align: right;
                   4894: }
                   4895: 
1.666     raeburn  4896: .LC_roleslog_note {
                   4897:   font-size: smaller;
                   4898: }
                   4899: 
1.692.4.2  raeburn  4900: .LC_mail_functions {
                   4901:     font-weight: bold;
                   4902: }
                   4903: 
1.440     albertel 4904: table.LC_aboutme_port {
1.692.4.2  raeburn  4905:   border: none;
1.440     albertel 4906:   border-collapse: collapse;
1.692.4.2  raeburn  4907:   border-spacing: 0;
1.440     albertel 4908: }
1.349     albertel 4909: table.LC_data_table, table.LC_mail_list {
1.347     albertel 4910:   border: 1px solid #000000;
1.402     albertel 4911:   border-collapse: separate;
1.426     albertel 4912:   border-spacing: 1px;
1.610     albertel 4913:   background: $pgbg;
1.347     albertel 4914: }
1.422     albertel 4915: .LC_data_table_dense {
                   4916:   font-size: small;
                   4917: }
1.507     raeburn  4918: table.LC_nested_outer {
                   4919:   border: 1px solid #000000;
1.589     raeburn  4920:   border-collapse: collapse;
1.692.4.2  raeburn  4921:   border-spacing: 0;
1.507     raeburn  4922:   width: 100%;
                   4923: }
1.692.4.11  raeburn  4924: table.LC_innerpickbox,
1.507     raeburn  4925: table.LC_nested {
1.692.4.2  raeburn  4926:   border: none;
1.589     raeburn  4927:   border-collapse: collapse;
1.692.4.2  raeburn  4928:   border-spacing: 0;
1.507     raeburn  4929:   width: 100%;
                   4930: }
1.523     albertel 4931: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
1.692.4.11  raeburn  4932: table.LC_prior_tries tr th,
                   4933: table.LC_innerpickbox tr th {
1.349     albertel 4934:   font-weight: bold;
                   4935:   background-color: $data_table_head;
1.421     albertel 4936:   font-size: smaller;
1.347     albertel 4937: }
1.692.4.11  raeburn  4938: table.LC_innerpickbox tr th,
                   4939: table.LC_innerpickbox tr td {
                   4940:   vertical-align: top;
                   4941: }
1.692.4.2  raeburn  4942: table.LC_data_table tr.LC_info_row > td {
                   4943:   background-color: #CCCCCC;
                   4944:   font-weight: bold;
                   4945:   text-align: left;
                   4946: }
1.610     albertel 4947: table.LC_data_table tr.LC_odd_row > td, 
1.692.4.2  raeburn  4948: table.LC_pick_box tr > td.LC_odd_row,
1.440     albertel 4949: table.LC_aboutme_port tr td {
1.349     albertel 4950:   background-color: $data_table_light;
1.425     albertel 4951:   padding: 2px;
1.347     albertel 4952: }
1.610     albertel 4953: table.LC_data_table tr.LC_even_row > td,
1.692.4.2  raeburn  4954: table.LC_pick_box tr > td.LC_even_row,
1.440     albertel 4955: table.LC_aboutme_port tr.LC_even_row td {
1.349     albertel 4956:   background-color: $data_table_dark;
1.692.4.2  raeburn  4957:   padding: 2px;
1.347     albertel 4958: }
1.425     albertel 4959: table.LC_data_table tr.LC_data_table_highlight td {
                   4960:   background-color: $data_table_darker;
                   4961: }
1.639     raeburn  4962: table.LC_data_table tr td.LC_leftcol_header {
                   4963:   background-color: $data_table_head;
                   4964:   font-weight: bold;
                   4965: }
1.451     albertel 4966: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  4967: table.LC_nested tr.LC_empty_row td {
1.347     albertel 4968:   background-color: #FFFFFF;
1.421     albertel 4969:   font-weight: bold;
                   4970:   font-style: italic;
                   4971:   text-align: center;
                   4972:   padding: 8px;
1.347     albertel 4973: }
1.507     raeburn  4974: table.LC_nested tr.LC_empty_row td {
1.465     albertel 4975:   padding: 4ex
                   4976: }
1.507     raeburn  4977: table.LC_nested_outer tr th {
                   4978:   font-weight: bold;
                   4979:   background-color: $data_table_head;
                   4980:   font-size: smaller;
                   4981:   border-bottom: 1px solid #000000;
                   4982: }
                   4983: table.LC_nested_outer tr td.LC_subheader {
                   4984:   background-color: $data_table_head;
                   4985:   font-weight: bold;
                   4986:   font-size: small;
                   4987:   border-bottom: 1px solid #000000;
                   4988:   text-align: right;
1.451     albertel 4989: }
1.507     raeburn  4990: table.LC_nested tr.LC_info_row td {
1.692.4.2  raeburn  4991:   background-color: #CCCCCC;
1.451     albertel 4992:   font-weight: bold;
                   4993:   font-size: small;
1.507     raeburn  4994:   text-align: center;
                   4995: }
1.589     raeburn  4996: table.LC_nested tr.LC_info_row td.LC_left_item,
                   4997: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  4998:   text-align: left;
1.451     albertel 4999: }
1.507     raeburn  5000: table.LC_nested td {
1.692.4.2  raeburn  5001:   background-color: #FFFFFF;
1.451     albertel 5002:   font-size: small;
1.507     raeburn  5003: }
                   5004: table.LC_nested_outer tr th.LC_right_item,
                   5005: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5006: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5007: table.LC_nested tr td.LC_right_item {
1.451     albertel 5008:   text-align: right;
                   5009: }
                   5010: 
1.507     raeburn  5011: table.LC_nested tr.LC_odd_row td {
1.692.4.2  raeburn  5012:   background-color: #EEEEEE;
1.451     albertel 5013: }
                   5014: 
1.473     raeburn  5015: table.LC_createuser {
                   5016: }
                   5017: 
                   5018: table.LC_createuser tr.LC_section_row td {
                   5019:   font-size: smaller;
                   5020: }
                   5021: 
                   5022: table.LC_createuser tr.LC_info_row td  {
1.692.4.2  raeburn  5023:   background-color: #CCCCCC;
1.473     raeburn  5024:   font-weight: bold;
                   5025:   text-align: center;
                   5026: }
                   5027: 
1.349     albertel 5028: table.LC_calendar {
                   5029:   border: 1px solid #000000;
                   5030:   border-collapse: collapse;
                   5031: }
                   5032: table.LC_calendar_pickdate {
                   5033:   font-size: xx-small;
                   5034: }
                   5035: table.LC_calendar tr td {
                   5036:   border: 1px solid #000000;
                   5037:   vertical-align: top;
                   5038: }
                   5039: table.LC_calendar tr td.LC_calendar_day_empty {
                   5040:   background-color: $data_table_dark;
                   5041: }
                   5042: table.LC_calendar tr td.LC_calendar_day_current {
                   5043:   background-color: $data_table_highlight;
                   5044: }
                   5045: 
                   5046: table.LC_mail_list tr.LC_mail_new {
                   5047:   background-color: $mail_new;
                   5048: }
                   5049: table.LC_mail_list tr.LC_mail_new:hover {
                   5050:   background-color: $mail_new_hover;
                   5051: }
                   5052: table.LC_mail_list tr.LC_mail_read {
                   5053:   background-color: $mail_read;
                   5054: }
                   5055: table.LC_mail_list tr.LC_mail_read:hover {
                   5056:   background-color: $mail_read_hover;
                   5057: }
                   5058: table.LC_mail_list tr.LC_mail_replied {
                   5059:   background-color: $mail_replied;
                   5060: }
                   5061: table.LC_mail_list tr.LC_mail_replied:hover {
                   5062:   background-color: $mail_replied_hover;
                   5063: }
                   5064: table.LC_mail_list tr.LC_mail_other {
                   5065:   background-color: $mail_other;
                   5066: }
                   5067: table.LC_mail_list tr.LC_mail_other:hover {
                   5068:   background-color: $mail_other_hover;
                   5069: }
1.494     raeburn  5070: table.LC_mail_list tr.LC_mail_even {
                   5071: }
                   5072: table.LC_mail_list tr.LC_mail_odd {
                   5073: }
                   5074: 
1.385     albertel 5075: 
1.386     albertel 5076: table#LC_portfolio_actions {
                   5077:   width: auto;
                   5078:   background: $pgbg;
1.692.4.2  raeburn  5079:   border: none;
1.386     albertel 5080:   border-spacing: 2px 2px;
1.692.4.2  raeburn  5081:   padding: 0;
                   5082:   margin: 0;
1.386     albertel 5083:   border-collapse: separate;
                   5084: }
                   5085: table#LC_portfolio_actions td.LC_label {
                   5086:   background: $tabbg;
                   5087:   text-align: right;
                   5088: }
                   5089: table#LC_portfolio_actions td.LC_value {
                   5090:   background: $tabbg;
                   5091: }
1.385     albertel 5092: 
1.391     albertel 5093: table#LC_cstr_controls {
                   5094:   width: 100%;
                   5095:   border-collapse: collapse;
                   5096: }
                   5097: table#LC_cstr_controls tr td {
                   5098:   border: 4px solid $pgbg;
                   5099:   padding: 4px;
                   5100:   text-align: center;
                   5101:   background: $tabbg;
                   5102: }
                   5103: table#LC_cstr_controls tr th {
                   5104:   border: 4px solid $pgbg;
                   5105:   background: $table_header;
                   5106:   text-align: center;
                   5107:   font-family: $sans;
                   5108:   font-size: smaller;
                   5109: }
                   5110: 
1.389     albertel 5111: table#LC_browser {
                   5112:  
                   5113: }
                   5114: table#LC_browser tr th {
1.391     albertel 5115:   background: $table_header;
1.389     albertel 5116: }
1.390     albertel 5117: table#LC_browser tr td {
                   5118:   padding: 2px;
                   5119: }
1.389     albertel 5120: table#LC_browser tr.LC_browser_file,
                   5121: table#LC_browser tr.LC_browser_file_published {
                   5122:   background: #CCFF88;
                   5123: }
                   5124: table#LC_browser tr.LC_browser_file_locked,
                   5125: table#LC_browser tr.LC_browser_file_unpublished {
                   5126:   background: #FFAA99;
1.387     albertel 5127: }
1.389     albertel 5128: table#LC_browser tr.LC_browser_file_obsolete {
                   5129:   background: #AAAAAA;
1.387     albertel 5130: }
1.455     albertel 5131: table#LC_browser tr.LC_browser_file_modified,
                   5132: table#LC_browser tr.LC_browser_file_metamodified {
1.389     albertel 5133:   background: #FFFF77;
1.387     albertel 5134: }
1.389     albertel 5135: table#LC_browser tr.LC_browser_folder {
                   5136:   background: #CCCCFF;
1.387     albertel 5137: }
1.692.4.2  raeburn  5138: 
                   5139: table.LC_data_table tr > td.LC_roles_is {
                   5140: /*  background: #77FF77; */
                   5141: }
                   5142: table.LC_data_table tr > td.LC_roles_future {
                   5143:   background: #FFFF77;
                   5144: }
                   5145: table.LC_data_table tr > td.LC_roles_will {
                   5146:   background: #FFAA77;
                   5147: }
                   5148: table.LC_data_table tr > td.LC_roles_expired {
                   5149:   background: #FF7777;
                   5150: }
                   5151: table.LC_data_table tr > td.LC_roles_will_not {
                   5152:   background: #AAFF77;
                   5153: }
                   5154: table.LC_data_table tr > td.LC_roles_selected {
                   5155:   background: #11CC55;
                   5156: }
                   5157: 
1.388     albertel 5158: span.LC_current_location {
                   5159:   font-size: x-large;
                   5160:   background: $pgbg;
                   5161: }
1.387     albertel 5162: 
1.395     albertel 5163: span.LC_parm_menu_item {
                   5164:   font-size: larger;
                   5165:   font-family: $sans;
                   5166: }
                   5167: span.LC_parm_scope_all {
                   5168:   color: red;
                   5169: }
                   5170: span.LC_parm_scope_folder {
                   5171:   color: green;
                   5172: }
                   5173: span.LC_parm_scope_resource {
                   5174:   color: orange;
                   5175: }
                   5176: span.LC_parm_part {
                   5177:   color: blue;
                   5178: }
                   5179: span.LC_parm_folder, span.LC_parm_symb {
                   5180:   font-size: x-small;
                   5181:   font-family: $mono;
                   5182:   color: #AAAAAA;
                   5183: }
                   5184: 
1.396     albertel 5185: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
                   5186: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
                   5187:   border: 1px solid black;
                   5188:   border-collapse: collapse;
                   5189: }
                   5190: table.LC_parm_overview_restrictions td {
                   5191:   border-width: 1px 4px 1px 4px;
                   5192:   border-style: solid;
                   5193:   border-color: $pgbg;
                   5194:   text-align: center;
                   5195: }
                   5196: table.LC_parm_overview_restrictions th {
                   5197:   background: $tabbg;
                   5198:   border-width: 1px 4px 1px 4px;
                   5199:   border-style: solid;
                   5200:   border-color: $pgbg;
                   5201: }
1.398     albertel 5202: table#LC_helpmenu {
1.692.4.2  raeburn  5203:   border: none;
1.398     albertel 5204:   height: 55px;
1.692.4.2  raeburn  5205:   border-spacing: 0;
1.398     albertel 5206: }
                   5207: 
                   5208: table#LC_helpmenu fieldset legend {
                   5209:   font-size: larger;
                   5210:   font-weight: bold;
                   5211: }
1.397     albertel 5212: table#LC_helpmenu_links {
                   5213:   width: 100%;
                   5214:   border: 1px solid black;
                   5215:   background: $pgbg;
1.692.4.2  raeburn  5216:   padding: 0;
1.397     albertel 5217:   border-spacing: 1px;
                   5218: }
                   5219: table#LC_helpmenu_links tr td {
                   5220:   padding: 1px;
                   5221:   background: $tabbg;
1.399     albertel 5222:   text-align: center;
                   5223:   font-weight: bold;
1.397     albertel 5224: }
1.396     albertel 5225: 
1.397     albertel 5226: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
                   5227: table#LC_helpmenu_links a:active {
                   5228:   text-decoration: none;
                   5229:   color: $font;
                   5230: }
                   5231: table#LC_helpmenu_links a:hover {
                   5232:   text-decoration: underline;
                   5233:   color: $vlink;
                   5234: }
1.396     albertel 5235: 
1.417     albertel 5236: .LC_chrt_popup_exists {
                   5237:   border: 1px solid #339933;
                   5238:   margin: -1px;
                   5239: }
                   5240: .LC_chrt_popup_up {
                   5241:   border: 1px solid yellow;
                   5242:   margin: -1px;
                   5243: }
                   5244: .LC_chrt_popup {
                   5245:   border: 1px solid #8888FF;
                   5246:   background: #CCCCFF;
                   5247: }
1.421     albertel 5248: table.LC_pick_box {
                   5249:   border-collapse: separate;
                   5250:   background: white;
                   5251:   border: 1px solid black;
                   5252:   border-spacing: 1px;
                   5253: }
                   5254: table.LC_pick_box td.LC_pick_box_title {
1.692.4.6  raeburn  5255:   background: $sidebg;
1.421     albertel 5256:   font-weight: bold;
                   5257:   text-align: right;
1.692.4.2  raeburn  5258:   vertical-align: top;
1.421     albertel 5259:   width: 184px;
                   5260:   padding: 8px;
                   5261: }
1.645     raeburn  5262: table.LC_pick_box td.LC_selfenroll_pick_box_title {
1.692.4.6  raeburn  5263:   background: $sidebg;
1.645     raeburn  5264:   font-weight: bold;
                   5265:   text-align: right;
                   5266:   width: 350px;
                   5267:   padding: 8px;
                   5268: }
                   5269: 
1.579     raeburn  5270: table.LC_pick_box td.LC_pick_box_value {
                   5271:   text-align: left;
                   5272:   padding: 8px;
                   5273: }
                   5274: table.LC_pick_box td.LC_pick_box_select {
                   5275:   text-align: left;
                   5276:   padding: 8px;
                   5277: }
1.424     albertel 5278: table.LC_pick_box td.LC_pick_box_separator {
1.692.4.2  raeburn  5279:   padding: 0;
1.421     albertel 5280:   height: 1px;
                   5281:   background: black;
                   5282: }
                   5283: table.LC_pick_box td.LC_pick_box_submit {
                   5284:   text-align: right;
                   5285: }
1.579     raeburn  5286: table.LC_pick_box td.LC_evenrow_value {
                   5287:   text-align: left;
                   5288:   padding: 8px;
                   5289:   background-color: $data_table_light;
                   5290: }
                   5291: table.LC_pick_box td.LC_oddrow_value {
                   5292:   text-align: left;
                   5293:   padding: 8px;
                   5294:   background-color: $data_table_light;
                   5295: }
                   5296: table.LC_helpform_receipt {
                   5297:   width: 620px;
                   5298:   border-collapse: separate;
                   5299:   background: white;
                   5300:   border: 1px solid black;
                   5301:   border-spacing: 1px;
                   5302: }
                   5303: table.LC_helpform_receipt td.LC_pick_box_title {
                   5304:   background: $tabbg;
                   5305:   font-weight: bold;
                   5306:   text-align: right;
                   5307:   width: 184px;
                   5308:   padding: 8px;
                   5309: }
                   5310: table.LC_helpform_receipt td.LC_evenrow_value {
                   5311:   text-align: left;
                   5312:   padding: 8px;
                   5313:   background-color: $data_table_light;
                   5314: }
                   5315: table.LC_helpform_receipt td.LC_oddrow_value {
                   5316:   text-align: left;
                   5317:   padding: 8px;
                   5318:   background-color: $data_table_light;
                   5319: }
                   5320: table.LC_helpform_receipt td.LC_pick_box_separator {
1.692.4.2  raeburn  5321:   padding: 0;
1.579     raeburn  5322:   height: 1px;
                   5323:   background: black;
                   5324: }
                   5325: span.LC_helpform_receipt_cat {
                   5326:   font-weight: bold;
                   5327: }
1.424     albertel 5328: table.LC_group_priv_box {
                   5329:   background: white;
                   5330:   border: 1px solid black;
                   5331:   border-spacing: 1px;
                   5332: }
                   5333: table.LC_group_priv_box td.LC_pick_box_title {
                   5334:   background: $tabbg;
                   5335:   font-weight: bold;
                   5336:   text-align: right;
                   5337:   width: 184px;
                   5338: }
                   5339: table.LC_group_priv_box td.LC_groups_fixed {
                   5340:   background: $data_table_light;
                   5341:   text-align: center;
                   5342: }
                   5343: table.LC_group_priv_box td.LC_groups_optional {
                   5344:   background: $data_table_dark;
                   5345:   text-align: center;
                   5346: }
                   5347: table.LC_group_priv_box td.LC_groups_functionality {
                   5348:   background: $data_table_darker;
                   5349:   text-align: center;
                   5350:   font-weight: bold;
                   5351: }
                   5352: table.LC_group_priv td {
                   5353:   text-align: left;
1.692.4.2  raeburn  5354:   padding: 0;
1.424     albertel 5355: }
                   5356: 
1.421     albertel 5357: table.LC_notify_front_page {
                   5358:   background: white;
                   5359:   border: 1px solid black;
                   5360:   padding: 8px;
                   5361: }
                   5362: table.LC_notify_front_page td {
                   5363:   padding: 8px;
                   5364: }
1.424     albertel 5365: .LC_navbuttons {
                   5366:   margin: 2ex 0ex 2ex 0ex;
                   5367: }
1.423     albertel 5368: .LC_topic_bar {
                   5369:   font-family: $sans;
                   5370:   font-weight: bold;
                   5371:   width: 100%;
                   5372:   background: $tabbg;
                   5373:   vertical-align: middle;
                   5374:   margin: 2ex 0ex 2ex 0ex;
1.692.4.2  raeburn  5375:   padding: 3px;
1.423     albertel 5376: }
                   5377: .LC_topic_bar span {
                   5378:   vertical-align: middle;
                   5379: }
                   5380: .LC_topic_bar img {
                   5381:   vertical-align: bottom;
                   5382: }
                   5383: table.LC_course_group_status {
                   5384:   margin: 20px;
                   5385: }
                   5386: table.LC_status_selector td {
                   5387:   vertical-align: top;
                   5388:   text-align: center;
1.424     albertel 5389:   padding: 4px;
                   5390: }
                   5391: table.LC_descriptive_input td.LC_description {
                   5392:   vertical-align: top;
                   5393:   text-align: right;
                   5394:   font-weight: bold;
1.423     albertel 5395: }
1.599     albertel 5396: div.LC_feedback_link {
1.616     albertel 5397:   clear: both;
1.599     albertel 5398:   background: white;
                   5399:   width: 100%;  
1.489     raeburn  5400: }
                   5401: span.LC_feedback_link {
1.599     albertel 5402:   background: $feedback_link_bg;
                   5403:   font-size: larger;
                   5404: }
                   5405: span.LC_message_link {
                   5406:   background: $feedback_link_bg;
                   5407:   font-size: larger;
                   5408:   position: absolute;
                   5409:   right: 1em;
1.489     raeburn  5410: }
1.421     albertel 5411: 
1.515     albertel 5412: table.LC_prior_tries {
1.524     albertel 5413:   border: 1px solid #000000;
                   5414:   border-collapse: separate;
                   5415:   border-spacing: 1px;
1.515     albertel 5416: }
1.523     albertel 5417: 
1.515     albertel 5418: table.LC_prior_tries td {
1.524     albertel 5419:   padding: 2px;
1.515     albertel 5420: }
1.523     albertel 5421: 
                   5422: .LC_answer_correct {
                   5423:   background: #AAFFAA;
                   5424:   color: black;
                   5425: }
                   5426: .LC_answer_charged_try {
                   5427:   background: #FFAAAA ! important;
                   5428:   color: black;
                   5429: }
                   5430: .LC_answer_not_charged_try, 
                   5431: .LC_answer_no_grade,
                   5432: .LC_answer_late {
                   5433:   background: #FFFFAA;
                   5434:   color: black;
                   5435: }
                   5436: .LC_answer_previous {
                   5437:   background: #AAAAFF;
                   5438:   color: black;
                   5439: }
                   5440: .LC_answer_no_message {
                   5441:   background: #FFFFFF;
                   5442:   color: black;
                   5443: }
                   5444: .LC_answer_unknown {
                   5445:   background: orange;
                   5446:   color: black;
                   5447: }
                   5448: 
                   5449: 
1.529     albertel 5450: span.LC_prior_numerical,
                   5451: span.LC_prior_string,
                   5452: span.LC_prior_custom,
                   5453: span.LC_prior_reaction,
                   5454: span.LC_prior_math {
1.523     albertel 5455:   font-family: monospace;
                   5456:   white-space: pre;
                   5457: }
                   5458: 
1.525     albertel 5459: span.LC_prior_string {
                   5460:   font-family: monospace;
                   5461:   white-space: pre;
                   5462: }
                   5463: 
1.523     albertel 5464: table.LC_prior_option {
                   5465:   width: 100%;
                   5466:   border-collapse: collapse;
                   5467: }
1.528     albertel 5468: table.LC_prior_rank, table.LC_prior_match {
                   5469:   border-collapse: collapse;
                   5470: }
                   5471: table.LC_prior_option tr td,
                   5472: table.LC_prior_rank tr td,
                   5473: table.LC_prior_match tr td {
1.524     albertel 5474:   border: 1px solid #000000;
1.515     albertel 5475: }
                   5476: 
1.519     raeburn  5477: span.LC_nobreak {
1.544     albertel 5478:   white-space: nowrap;
1.519     raeburn  5479: }
                   5480: 
1.576     raeburn  5481: span.LC_cusr_emph {
                   5482:   font-style: italic;
                   5483: }
                   5484: 
1.633     raeburn  5485: span.LC_cusr_subheading {
                   5486:   font-weight: normal;
                   5487:   font-size: 85%;
                   5488: }
                   5489: 
1.545     albertel 5490: table.LC_docs_documents {
                   5491:   background: #BBBBBB;
1.692.4.2  raeburn  5492:   border-width: 0;
1.545     albertel 5493:   border-collapse: collapse;
                   5494: }
                   5495: 
                   5496: table.LC_docs_documents td.LC_docs_document {
                   5497:   border: 2px solid black;
                   5498:   padding: 4px;
                   5499: }
                   5500: 
                   5501: .LC_docs_course_commands div {
                   5502:   float: left;
                   5503:   border: 4px solid #AAAAAA;
                   5504:   padding: 4px;
                   5505:   background: #DDDDCC;
                   5506: }
                   5507: 
                   5508: .LC_docs_entry_move {
1.692.4.2  raeburn  5509:   border: none;
1.545     albertel 5510:   border-collapse: collapse;
1.544     albertel 5511: }
                   5512: 
1.545     albertel 5513: .LC_docs_entry_move td {
                   5514:   border: 2px solid #BBBBBB;
                   5515:   background: #DDDDDD;
                   5516: }
                   5517: 
                   5518: .LC_docs_editor td.LC_docs_entry_commands {
                   5519:   background: #DDDDDD;
                   5520:   font-size: x-small;
                   5521: }
1.544     albertel 5522: .LC_docs_copy {
1.545     albertel 5523:   color: #000099;
1.544     albertel 5524: }
                   5525: .LC_docs_cut {
1.545     albertel 5526:   color: #550044;
1.544     albertel 5527: }
                   5528: .LC_docs_rename {
1.545     albertel 5529:   color: #009900;
1.544     albertel 5530: }
                   5531: .LC_docs_remove {
1.545     albertel 5532:   color: #990000;
                   5533: }
                   5534: 
1.547     albertel 5535: .LC_docs_reinit_warn,
                   5536: .LC_docs_ext_edit {
                   5537:   font-size: x-small;
                   5538: }
                   5539: 
1.545     albertel 5540: .LC_docs_editor td.LC_docs_entry_title,
                   5541: .LC_docs_editor td.LC_docs_entry_icon {
                   5542:   background: #FFFFBB;
                   5543: }
                   5544: .LC_docs_editor td.LC_docs_entry_parameter {
                   5545:   background: #BBBBFF;
                   5546:   font-size: x-small;
                   5547:   white-space: nowrap;
                   5548: }
                   5549: 
                   5550: table.LC_docs_adddocs td,
                   5551: table.LC_docs_adddocs th {
                   5552:   border: 1px solid #BBBBBB;
                   5553:   padding: 4px;
                   5554:   background: #DDDDDD;
1.543     albertel 5555: }
                   5556: 
1.584     albertel 5557: table.LC_sty_begin {
                   5558:   background: #BBFFBB;
                   5559: }
                   5560: table.LC_sty_end {
                   5561:   background: #FFBBBB;
                   5562: }
                   5563: 
1.589     raeburn  5564: table.LC_double_column {
1.692.4.2  raeburn  5565:   border-width: 0;
1.589     raeburn  5566:   border-collapse: collapse;
                   5567:   width: 100%;
                   5568:   padding: 2px;
                   5569: }
                   5570: 
                   5571: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  5572:   top: 2px;
1.589     raeburn  5573:   left: 2px;
                   5574:   width: 47%;
                   5575:   vertical-align: top;
                   5576: }
                   5577: 
                   5578: table.LC_double_column tr td.LC_right_col {
                   5579:   top: 2px;
                   5580:   right: 2px; 
                   5581:   width: 47%;
                   5582:   vertical-align: top;
                   5583: }
                   5584: 
1.594     raeburn  5585: span.LC_role_level {
                   5586:   font-weight: bold;
                   5587: }
                   5588: 
1.591     raeburn  5589: div.LC_left_float {
                   5590:   float: left;
                   5591:   padding-right: 5%;
1.597     albertel 5592:   padding-bottom: 4px;
1.591     raeburn  5593: }
                   5594: 
                   5595: div.LC_clear_float_header {
1.597     albertel 5596:   padding-bottom: 2px;
1.591     raeburn  5597: }
                   5598: 
                   5599: div.LC_clear_float_footer {
1.597     albertel 5600:   padding-top: 10px;
1.591     raeburn  5601:   clear: both;
                   5602: }
                   5603: 
1.597     albertel 5604: 
1.601     albertel 5605: div.LC_grade_select_mode {
1.604     albertel 5606:   font-family: $sans;
1.601     albertel 5607: }
                   5608: div.LC_grade_select_mode div div {
                   5609:   margin: 5px;
                   5610: }
                   5611: div.LC_grade_select_mode_selector {
                   5612:   margin: 5px;
                   5613:   float: left;
                   5614: }
                   5615: div.LC_grade_select_mode_selector_header {
                   5616:   font: bold medium $sans;
                   5617: }
                   5618: div.LC_grade_select_mode_type {
                   5619:   clear: left;
                   5620: }
                   5621: 
1.597     albertel 5622: div.LC_grade_show_user {
                   5623:   margin-top: 20px;
                   5624:   border: 1px solid black;
                   5625: }
                   5626: div.LC_grade_user_name {
                   5627:   background: #DDDDEE;
                   5628:   border-bottom: 1px solid black;
                   5629:   font: bold large $sans;
                   5630: }
                   5631: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
                   5632:   background: #DDEEDD;
                   5633: }
                   5634: 
                   5635: div.LC_grade_show_problem,
                   5636: div.LC_grade_submissions,
                   5637: div.LC_grade_message_center,
                   5638: div.LC_grade_info_links,
                   5639: div.LC_grade_assign {
                   5640:   margin: 5px;
                   5641:   width: 99%;
                   5642:   background: #FFFFFF;
                   5643: }
                   5644: div.LC_grade_show_problem_header,
                   5645: div.LC_grade_submissions_header,
                   5646: div.LC_grade_message_center_header,
                   5647: div.LC_grade_assign_header {
                   5648:   font: bold large $sans;
                   5649: }
                   5650: div.LC_grade_show_problem_problem,
                   5651: div.LC_grade_submissions_body,
                   5652: div.LC_grade_message_center_body,
                   5653: div.LC_grade_assign_body {
                   5654:   border: 1px solid black;
                   5655:   width: 99%;
                   5656:   background: #FFFFFF;
                   5657: }
1.598     albertel 5658: span.LC_grade_check_note {
                   5659:   font: normal medium $sans;
                   5660:   display: inline;
                   5661:   position: absolute;
                   5662:   right: 1em;
                   5663: }
1.597     albertel 5664: 
1.613     albertel 5665: table.LC_scantron_action {
                   5666:   width: 100%;
                   5667: }
                   5668: table.LC_scantron_action tr th {
                   5669:   font: normal bold $sans;
                   5670: }
1.600     albertel 5671: 
1.614     albertel 5672: div.LC_edit_problem_header, 
                   5673: div.LC_edit_problem_footer {
1.600     albertel 5674:   font: normal medium $sans;
1.602     albertel 5675:   margin: 2px;
1.600     albertel 5676: }
                   5677: div.LC_edit_problem_header,
1.602     albertel 5678: div.LC_edit_problem_header div,
1.614     albertel 5679: div.LC_edit_problem_footer,
                   5680: div.LC_edit_problem_footer div,
1.602     albertel 5681: div.LC_edit_problem_editxml_header,
                   5682: div.LC_edit_problem_editxml_header div {
1.600     albertel 5683:   margin-top: 5px;
                   5684: }
1.602     albertel 5685: div.LC_edit_problem_header_edit_row {
                   5686:   background: $tabbg;
                   5687:   padding: 3px;
                   5688:   margin-bottom: 5px;
                   5689: }
1.600     albertel 5690: div.LC_edit_problem_header_title {
1.602     albertel 5691:   font: larger bold $sans;
                   5692:   background: $tabbg;
                   5693:   padding: 3px;
                   5694: }
                   5695: table.LC_edit_problem_header_title {
                   5696:   font: larger bold $sans;
                   5697:   width: 100%;
                   5698:   border-color: $pgbg;
                   5699:   border-style: solid;
                   5700:   border-width: $border;
                   5701: 
1.600     albertel 5702:   background: $tabbg;
1.602     albertel 5703:   border-collapse: collapse;
1.692.4.2  raeburn  5704:   padding: 0;
1.602     albertel 5705: }
                   5706: 
                   5707: div.LC_edit_problem_discards {
                   5708:   float: left;
                   5709:   padding-bottom: 5px;
                   5710: }
                   5711: div.LC_edit_problem_saves {
                   5712:   float: right;
                   5713:   padding-bottom: 5px;
1.600     albertel 5714: }
                   5715: hr.LC_edit_problem_divide {
1.602     albertel 5716:   clear: both;
1.600     albertel 5717:   color: $tabbg;
                   5718:   background-color: $tabbg;
                   5719:   height: 3px;
1.692.4.2  raeburn  5720:   border: none;
1.600     albertel 5721: }
1.679     riegler  5722: img.stift{
1.678     riegler  5723:   border-width:0;
1.679     riegler  5724:   vertical-align:middle;
1.677     riegler  5725: }
1.680     riegler  5726: 
1.681     riegler  5727: table#LC_mainmenu{
                   5728:  margin-top:10px;
                   5729:  width:80%;
                   5730: 
                   5731: }
                   5732: 
1.680     riegler  5733: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
                   5734:   vertical-align: top;
                   5735:   width: 45%;
                   5736: }
                   5737: .LC_mainmenu_fieldset_category {
                   5738:   color: $font;
                   5739:   background: $pgbg;
                   5740:   font-family: $sans;
                   5741:   font-size: small;
                   5742:   font-weight: bold;
                   5743: }
                   5744: fieldset#LC_mainmenu_fieldset {
1.692.4.2  raeburn  5745:   margin:0 10px 10px 0;
                   5746: 
                   5747: }
1.680     riegler  5748: 
1.692.4.2  raeburn  5749: div.LC_createcourse {
                   5750:     margin: 10px 10px 10px 10px;
1.680     riegler  5751: }
1.692.4.2  raeburn  5752: 
1.343     albertel 5753: END
                   5754: }
                   5755: 
1.306     albertel 5756: =pod
                   5757: 
                   5758: =item * &headtag()
                   5759: 
                   5760: Returns a uniform footer for LON-CAPA web pages.
                   5761: 
1.307     albertel 5762: Inputs: $title - optional title for the head
                   5763:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 5764:         $args - optional arguments
1.319     albertel 5765:             force_register - if is true call registerurl so the remote is 
                   5766:                              informed
1.415     albertel 5767:             redirect       -> array ref of
                   5768:                                    1- seconds before redirect occurs
                   5769:                                    2- url to redirect to
                   5770:                                    3- whether the side effect should occur
1.315     albertel 5771:                            (side effect of setting 
                   5772:                                $env{'internal.head.redirect'} to the url 
                   5773:                                redirected too)
1.352     albertel 5774:             domain         -> force to color decorate a page for a specific
                   5775:                                domain
                   5776:             function       -> force usage of a specific rolish color scheme
                   5777:             bgcolor        -> override the default page bgcolor
1.460     albertel 5778:             no_auto_mt_title
                   5779:                            -> prevent &mt()ing the title arg
1.464     albertel 5780: 
1.306     albertel 5781: =cut
                   5782: 
                   5783: sub headtag {
1.313     albertel 5784:     my ($title,$head_extra,$args) = @_;
1.306     albertel 5785:     
1.363     albertel 5786:     my $function = $args->{'function'} || &get_users_function();
                   5787:     my $domain   = $args->{'domain'}   || &determinedomain();
                   5788:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 5789:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 5790: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 5791: 		   #time(),
1.418     albertel 5792: 		   $env{'environment.color.timestamp'},
1.363     albertel 5793: 		   $function,$domain,$bgcolor);
                   5794: 
1.369     www      5795:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 5796: 
1.308     albertel 5797:     my $result =
                   5798: 	'<head>'.
1.461     albertel 5799: 	&font_settings();
1.319     albertel 5800: 
1.461     albertel 5801:     if (!$args->{'frameset'}) {
                   5802: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   5803:     }
1.319     albertel 5804:     if ($args->{'force_register'}) {
                   5805: 	$result .= &Apache::lonmenu::registerurl(1);
                   5806:     }
1.436     albertel 5807:     if (!$args->{'no_nav_bar'} 
                   5808: 	&& !$args->{'only_body'}
                   5809: 	&& !$args->{'frameset'}) {
                   5810: 	$result .= &help_menu_js();
                   5811:     }
1.319     albertel 5812: 
1.314     albertel 5813:     if (ref($args->{'redirect'})) {
1.414     albertel 5814: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 5815: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 5816: 	if (!$inhibit_continue) {
                   5817: 	    $env{'internal.head.redirect'} = $url;
                   5818: 	}
1.313     albertel 5819: 	$result.=<<ADDMETA
                   5820: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 5821: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 5822: ADDMETA
                   5823:     }
1.306     albertel 5824:     if (!defined($title)) {
                   5825: 	$title = 'The LearningOnline Network with CAPA';
                   5826:     }
1.460     albertel 5827:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   5828:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 5829: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
                   5830: 	.$head_extra;
1.306     albertel 5831:     return $result;
                   5832: }
                   5833: 
                   5834: =pod
                   5835: 
1.340     albertel 5836: =item * &font_settings()
                   5837: 
                   5838: Returns neccessary <meta> to set the proper encoding
                   5839: 
                   5840: Inputs: none
                   5841: 
                   5842: =cut
                   5843: 
                   5844: sub font_settings {
                   5845:     my $headerstring='';
1.647     www      5846:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 5847: 	$headerstring.=
                   5848: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   5849:     }
                   5850:     return $headerstring;
                   5851: }
                   5852: 
1.341     albertel 5853: =pod
                   5854: 
                   5855: =item * &xml_begin()
                   5856: 
                   5857: Returns the needed doctype and <html>
                   5858: 
                   5859: Inputs: none
                   5860: 
                   5861: =cut
                   5862: 
                   5863: sub xml_begin {
                   5864:     my $output='';
                   5865: 
1.592     albertel 5866:     if ($env{'internal.start_page'}==1) {
                   5867: 	&Apache::lonhtmlcommon::init_htmlareafields();
                   5868:     }
1.342     albertel 5869: 
1.341     albertel 5870:     if ($env{'browser.mathml'}) {
                   5871: 	$output='<?xml version="1.0"?>'
                   5872:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   5873: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   5874:             
                   5875: #	    .'<!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">] >'
                   5876: 	    .'<!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">'
                   5877:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   5878: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   5879:     } else {
1.692.4.6  raeburn  5880: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
                   5881:             '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 5882:     }
                   5883:     return $output;
                   5884: }
1.340     albertel 5885: 
                   5886: =pod
                   5887: 
1.306     albertel 5888: =item * &endheadtag()
                   5889: 
                   5890: Returns a uniform </head> for LON-CAPA web pages.
                   5891: 
                   5892: Inputs: none
                   5893: 
                   5894: =cut
                   5895: 
                   5896: sub endheadtag {
                   5897:     return '</head>';
                   5898: }
                   5899: 
                   5900: =pod
                   5901: 
                   5902: =item * &head()
                   5903: 
                   5904: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
                   5905: 
1.648     raeburn  5906: Inputs:
                   5907: 
                   5908: =over 4
                   5909: 
                   5910: $title - optional title for the page
                   5911: 
                   5912: $head_extra - optional extra HTML to put inside the <head>
                   5913: 
                   5914: =back
1.405     albertel 5915: 
1.306     albertel 5916: =cut
                   5917: 
                   5918: sub head {
1.325     albertel 5919:     my ($title,$head_extra,$args) = @_;
                   5920:     return &headtag($title,$head_extra,$args).&endheadtag();
1.306     albertel 5921: }
                   5922: 
                   5923: =pod
                   5924: 
                   5925: =item * &start_page()
                   5926: 
                   5927: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   5928: 
1.648     raeburn  5929: Inputs:
                   5930: 
                   5931: =over 4
                   5932: 
                   5933: $title - optional title for the page
                   5934: 
                   5935: $head_extra - optional extra HTML to incude inside the <head>
                   5936: 
                   5937: $args - additional optional args supported are:
                   5938: 
                   5939: =over 8
                   5940: 
                   5941:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 5942:                                     arg on
1.648     raeburn  5943:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
                   5944:              add_entries    -> additional attributes to add to the  <body>
                   5945:              domain         -> force to color decorate a page for a 
1.317     albertel 5946:                                     specific domain
1.648     raeburn  5947:              function       -> force usage of a specific rolish color
1.317     albertel 5948:                                     scheme
1.648     raeburn  5949:              redirect       -> see &headtag()
                   5950:              bgcolor        -> override the default page bg color
                   5951:              js_ready       -> return a string ready for being used in 
1.317     albertel 5952:                                     a javascript writeln
1.648     raeburn  5953:              html_encode    -> return a string ready for being used in 
1.320     albertel 5954:                                     a html attribute
1.648     raeburn  5955:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 5956:                                     $forcereg arg
1.648     raeburn  5957:              body_title     -> alternate text to use instead of $title
1.326     albertel 5958:                                     in the title box that appears, this text
                   5959:                                     is not auto translated like the $title is
1.648     raeburn  5960:              frameset       -> if true will start with a <frameset>
1.330     albertel 5961:                                     rather than <body>
1.648     raeburn  5962:              no_title       -> if true the title bar won't be shown
                   5963:              skip_phases    -> hash ref of 
1.338     albertel 5964:                                     head -> skip the <html><head> generation
                   5965:                                     body -> skip all <body> generation
1.648     raeburn  5966:              no_inline_link -> if true and in remote mode, don't show the 
1.361     albertel 5967:                                     'Switch To Inline Menu' link
1.648     raeburn  5968:              no_auto_mt_title -> prevent &mt()ing the title arg
                   5969:              inherit_jsmath -> when creating popup window in a page,
                   5970:                                     should it have jsmath forced on by the
                   5971:                                     current page
1.361     albertel 5972: 
1.648     raeburn  5973: =back
1.460     albertel 5974: 
1.648     raeburn  5975: =back
1.562     albertel 5976: 
1.306     albertel 5977: =cut
                   5978: 
                   5979: sub start_page {
1.309     albertel 5980:     my ($title,$head_extra,$args) = @_;
1.318     albertel 5981:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.313     albertel 5982:     my %head_args;
1.352     albertel 5983:     foreach my $arg ('redirect','force_register','domain','function',
1.460     albertel 5984: 		     'bgcolor','frameset','no_nav_bar','only_body',
                   5985: 		     'no_auto_mt_title') {
1.319     albertel 5986: 	if (defined($args->{$arg})) {
1.324     raeburn  5987: 	    $head_args{$arg} = $args->{$arg};
1.319     albertel 5988: 	}
1.313     albertel 5989:     }
1.319     albertel 5990: 
1.315     albertel 5991:     $env{'internal.start_page'}++;
1.338     albertel 5992:     my $result;
                   5993:     if (! exists($args->{'skip_phases'}{'head'}) ) {
                   5994: 	$result.=
1.341     albertel 5995: 	    &xml_begin().
1.338     albertel 5996: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
                   5997:     }
                   5998:     
                   5999:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   6000: 	if ($args->{'frameset'}) {
                   6001: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   6002: 						$args->{'add_entries'});
                   6003: 	    $result .= "\n<frameset $attr_string>\n";
                   6004: 	} else {
                   6005: 	    $result .=
                   6006: 		&bodytag($title, 
                   6007: 			 $args->{'function'},       $args->{'add_entries'},
                   6008: 			 $args->{'only_body'},      $args->{'domain'},
                   6009: 			 $args->{'force_register'}, $args->{'body_title'},
                   6010: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
1.460     albertel 6011: 			 $args->{'no_title'},       $args->{'no_inline_link'},
                   6012: 			 $args);
1.338     albertel 6013: 	}
1.330     albertel 6014:     }
1.338     albertel 6015: 
1.315     albertel 6016:     if ($args->{'js_ready'}) {
1.317     albertel 6017: 	$result = &js_ready($result);
1.315     albertel 6018:     }
1.320     albertel 6019:     if ($args->{'html_encode'}) {
                   6020: 	$result = &html_encode($result);
                   6021:     }
1.692.4.2  raeburn  6022:     #Breadcrumbs
                   6023:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   6024:         &Apache::lonhtmlcommon::clear_breadcrumbs();
                   6025:         #if any br links exists, add them to the breadcrumbs
                   6026:         if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6027:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   6028:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   6029:             }
                   6030:         }
1.306     albertel 6031: 
1.692.4.2  raeburn  6032:         #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   6033:         if (exists($args->{'bread_crumbs_component'})){
                   6034:             $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   6035:         } else {
                   6036:             $result .= &Apache::lonhtmlcommon::breadcrumbs();
                   6037:         }
                   6038:     }
                   6039:     return $result;
1.692.4.3  raeburn  6040: }
1.330     albertel 6041: 
1.306     albertel 6042: =pod
                   6043: 
                   6044: =item * &head()
                   6045: 
                   6046: Returns a complete </body></html> section for LON-CAPA web pages.
                   6047: 
1.315     albertel 6048: Inputs:         $args - additional optional args supported are:
                   6049:                  js_ready     -> return a string ready for being used in 
                   6050:                                  a javascript writeln
1.320     albertel 6051:                  html_encode  -> return a string ready for being used in 
                   6052:                                  a html attribute
1.330     albertel 6053:                  frameset     -> if true will start with a <frameset>
                   6054:                                  rather than <body>
1.493     albertel 6055:                  dicsussion   -> if true will get discussion from
                   6056:                                   lonxml::xmlend
                   6057:                                  (you can pass the target and parser arguments
                   6058:                                   through optional 'target' and 'parser' args
                   6059:                                   to this routine)
1.306     albertel 6060: 
                   6061: =cut
                   6062: 
                   6063: sub end_page {
1.315     albertel 6064:     my ($args) = @_;
                   6065:     $env{'internal.end_page'}++;
1.330     albertel 6066:     my $result;
1.335     albertel 6067:     if ($args->{'discussion'}) {
                   6068: 	my ($target,$parser);
                   6069: 	if (ref($args->{'discussion'})) {
                   6070: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   6071: 				$args->{'discussion'}{'parser'});
                   6072: 	}
                   6073: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   6074:     }
                   6075: 
1.330     albertel 6076:     if ($args->{'frameset'}) {
                   6077: 	$result .= '</frameset>';
                   6078:     } else {
1.635     raeburn  6079: 	$result .= &endbodytag($args);
1.330     albertel 6080:     }
                   6081:     $result .= "\n</html>";
                   6082: 
1.315     albertel 6083:     if ($args->{'js_ready'}) {
1.317     albertel 6084: 	$result = &js_ready($result);
1.315     albertel 6085:     }
1.335     albertel 6086: 
1.320     albertel 6087:     if ($args->{'html_encode'}) {
                   6088: 	$result = &html_encode($result);
                   6089:     }
1.335     albertel 6090: 
1.315     albertel 6091:     return $result;
                   6092: }
                   6093: 
1.320     albertel 6094: sub html_encode {
                   6095:     my ($result) = @_;
                   6096: 
1.322     albertel 6097:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 6098:     
                   6099:     return $result;
                   6100: }
1.317     albertel 6101: sub js_ready {
                   6102:     my ($result) = @_;
                   6103: 
1.323     albertel 6104:     $result =~ s/[\n\r]/ /xmsg;
                   6105:     $result =~ s/\\/\\\\/xmsg;
                   6106:     $result =~ s/'/\\'/xmsg;
1.372     albertel 6107:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 6108:     
                   6109:     return $result;
                   6110: }
                   6111: 
1.315     albertel 6112: sub validate_page {
                   6113:     if (  exists($env{'internal.start_page'})
1.316     albertel 6114: 	  &&     $env{'internal.start_page'} > 1) {
                   6115: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 6116: 				 $env{'internal.start_page'}.' '.
1.316     albertel 6117: 				 $ENV{'request.filename'});
1.315     albertel 6118:     }
                   6119:     if (  exists($env{'internal.end_page'})
1.316     albertel 6120: 	  &&     $env{'internal.end_page'} > 1) {
                   6121: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 6122: 				 $env{'internal.end_page'}.' '.
1.316     albertel 6123: 				 $env{'request.filename'});
1.315     albertel 6124:     }
                   6125:     if (     exists($env{'internal.start_page'})
                   6126: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 6127: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   6128: 				 $env{'request.filename'});
1.315     albertel 6129:     }
                   6130:     if (   ! exists($env{'internal.start_page'})
                   6131: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 6132: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   6133: 				 $env{'request.filename'});
1.315     albertel 6134:     }
1.306     albertel 6135: }
1.315     albertel 6136: 
1.318     albertel 6137: sub simple_error_page {
                   6138:     my ($r,$title,$msg) = @_;
                   6139:     my $page =
                   6140: 	&Apache::loncommon::start_page($title).
                   6141: 	&mt($msg).
                   6142: 	&Apache::loncommon::end_page();
                   6143:     if (ref($r)) {
                   6144: 	$r->print($page);
1.327     albertel 6145: 	return;
1.318     albertel 6146:     }
                   6147:     return $page;
                   6148: }
1.347     albertel 6149: 
                   6150: {
1.610     albertel 6151:     my @row_count;
1.347     albertel 6152:     sub start_data_table {
1.422     albertel 6153: 	my ($add_class) = @_;
                   6154: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.610     albertel 6155: 	unshift(@row_count,0);
1.422     albertel 6156: 	return '<table class="'.$css_class.'">'."\n";
1.347     albertel 6157:     }
                   6158: 
                   6159:     sub end_data_table {
1.610     albertel 6160: 	shift(@row_count);
1.389     albertel 6161: 	return '</table>'."\n";;
1.347     albertel 6162:     }
                   6163: 
                   6164:     sub start_data_table_row {
1.422     albertel 6165: 	my ($add_class) = @_;
1.610     albertel 6166: 	$row_count[0]++;
                   6167: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.428     albertel 6168: 	$css_class = (join(' ',$css_class,$add_class));
1.422     albertel 6169: 	return  '<tr class="'.$css_class.'">'."\n";;
1.347     albertel 6170:     }
1.471     banghart 6171:     
                   6172:     sub continue_data_table_row {
                   6173: 	my ($add_class) = @_;
1.610     albertel 6174: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.471     banghart 6175: 	$css_class = (join(' ',$css_class,$add_class));
                   6176: 	return  '<tr class="'.$css_class.'">'."\n";;
                   6177:     }
1.347     albertel 6178: 
                   6179:     sub end_data_table_row {
1.389     albertel 6180: 	return '</tr>'."\n";;
1.347     albertel 6181:     }
1.367     www      6182: 
1.421     albertel 6183:     sub start_data_table_empty_row {
1.610     albertel 6184: 	$row_count[0]++;
1.421     albertel 6185: 	return  '<tr class="LC_empty_row" >'."\n";;
                   6186:     }
                   6187: 
                   6188:     sub end_data_table_empty_row {
                   6189: 	return '</tr>'."\n";;
                   6190:     }
                   6191: 
1.367     www      6192:     sub start_data_table_header_row {
1.389     albertel 6193: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      6194:     }
                   6195: 
                   6196:     sub end_data_table_header_row {
1.389     albertel 6197: 	return '</tr>'."\n";;
1.367     www      6198:     }
1.347     albertel 6199: }
                   6200: 
1.548     albertel 6201: =pod
                   6202: 
                   6203: =item * &inhibit_menu_check($arg)
                   6204: 
                   6205: Checks for a inhibitmenu state and generates output to preserve it
                   6206: 
                   6207: Inputs:         $arg - can be any of
                   6208:                      - undef - in which case the return value is a string 
                   6209:                                to add  into arguments list of a uri
                   6210:                      - 'input' - in which case the return value is a HTML
                   6211:                                  <form> <input> field of type hidden to
                   6212:                                  preserve the value
                   6213:                      - a url - in which case the return value is the url with
                   6214:                                the neccesary cgi args added to preserve the
                   6215:                                inhibitmenu state
                   6216:                      - a ref to a url - no return value, but the string is
                   6217:                                         updated to include the neccessary cgi
                   6218:                                         args to preserve the inhibitmenu state
                   6219: 
                   6220: =cut
                   6221: 
                   6222: sub inhibit_menu_check {
                   6223:     my ($arg) = @_;
                   6224:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6225:     if ($arg eq 'input') {
                   6226: 	if ($env{'form.inhibitmenu'}) {
                   6227: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   6228: 	} else {
                   6229: 	    return
                   6230: 	}
                   6231:     }
                   6232:     if ($env{'form.inhibitmenu'}) {
                   6233: 	if (ref($arg)) {
                   6234: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   6235: 	} elsif ($arg eq '') {
                   6236: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   6237: 	} else {
                   6238: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   6239: 	}
                   6240:     }
                   6241:     if (!ref($arg)) {
                   6242: 	return $arg;
                   6243:     }
                   6244: }
                   6245: 
1.251     albertel 6246: ###############################################
1.182     matthew  6247: 
                   6248: =pod
                   6249: 
1.549     albertel 6250: =back
                   6251: 
                   6252: =head1 User Information Routines
                   6253: 
                   6254: =over 4
                   6255: 
1.405     albertel 6256: =item * &get_users_function()
1.182     matthew  6257: 
                   6258: Used by &bodytag to determine the current users primary role.
                   6259: Returns either 'student','coordinator','admin', or 'author'.
                   6260: 
                   6261: =cut
                   6262: 
                   6263: ###############################################
                   6264: sub get_users_function {
                   6265:     my $function = 'student';
1.258     albertel 6266:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
1.182     matthew  6267:         $function='coordinator';
                   6268:     }
1.258     albertel 6269:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  6270:         $function='admin';
                   6271:     }
1.692.4.5  raeburn  6272:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.182     matthew  6273:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   6274:         $function='author';
                   6275:     }
                   6276:     return $function;
1.54      www      6277: }
1.99      www      6278: 
                   6279: ###############################################
                   6280: 
1.233     raeburn  6281: =pod
                   6282: 
1.692.4.2  raeburn  6283: =item * &show_course()
                   6284: 
                   6285: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   6286: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   6287: Inputs:
                   6288: None
                   6289: 
                   6290: Outputs:
                   6291: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   6292: 
                   6293: =cut
                   6294: 
                   6295: ###############################################
                   6296: sub show_course {
                   6297:     my $course = !$env{'user.adv'};
                   6298:     if (!$env{'user.adv'}) {
                   6299:         foreach my $env (keys(%env)) {
                   6300:             next if ($env !~ m/^user\.priv\./);
                   6301:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   6302:                 $course = 0;
                   6303:                 last;
                   6304:             }
                   6305:         }
                   6306:     }
                   6307:     return $course;
                   6308: }
                   6309: 
                   6310: ###############################################
                   6311: 
                   6312: =pod
                   6313: 
1.542     raeburn  6314: =item * &check_user_status()
1.274     raeburn  6315: 
                   6316: Determines current status of supplied role for a
                   6317: specific user. Roles can be active, previous or future.
                   6318: 
                   6319: Inputs: 
                   6320: user's domain, user's username, course's domain,
1.375     raeburn  6321: course's number, optional section ID.
1.274     raeburn  6322: 
                   6323: Outputs:
                   6324: role status: active, previous or future. 
                   6325: 
                   6326: =cut
                   6327: 
                   6328: sub check_user_status {
1.412     raeburn  6329:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.274     raeburn  6330:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
                   6331:     my @uroles = keys %userinfo;
                   6332:     my $srchstr;
                   6333:     my $active_chk = 'none';
1.412     raeburn  6334:     my $now = time;
1.274     raeburn  6335:     if (@uroles > 0) {
1.412     raeburn  6336:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  6337:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   6338:         } else {
1.412     raeburn  6339:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   6340:         }
                   6341:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  6342:             my $role_end = 0;
                   6343:             my $role_start = 0;
                   6344:             $active_chk = 'active';
1.412     raeburn  6345:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   6346:                 $role_end = $1;
                   6347:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   6348:                     $role_start = $1;
1.274     raeburn  6349:                 }
                   6350:             }
                   6351:             if ($role_start > 0) {
1.412     raeburn  6352:                 if ($now < $role_start) {
1.274     raeburn  6353:                     $active_chk = 'future';
                   6354:                 }
                   6355:             }
                   6356:             if ($role_end > 0) {
1.412     raeburn  6357:                 if ($now > $role_end) {
1.274     raeburn  6358:                     $active_chk = 'previous';
                   6359:                 }
                   6360:             }
                   6361:         }
                   6362:     }
                   6363:     return $active_chk;
                   6364: }
                   6365: 
                   6366: ###############################################
                   6367: 
                   6368: =pod
                   6369: 
1.405     albertel 6370: =item * &get_sections()
1.233     raeburn  6371: 
                   6372: Determines all the sections for a course including
                   6373: sections with students and sections containing other roles.
1.419     raeburn  6374: Incoming parameters: 
                   6375: 
                   6376: 1. domain
                   6377: 2. course number 
                   6378: 3. reference to array containing roles for which sections should 
                   6379: be gathered (optional).
                   6380: 4. reference to array containing status types for which sections 
                   6381: should be gathered (optional).
                   6382: 
                   6383: If the third argument is undefined, sections are gathered for any role. 
                   6384: If the fourth argument is undefined, sections are gathered for any status.
                   6385: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  6386:  
1.374     raeburn  6387: Returns section hash (keys are section IDs, values are
                   6388: number of users in each section), subject to the
1.419     raeburn  6389: optional roles filter, optional status filter 
1.233     raeburn  6390: 
                   6391: =cut
                   6392: 
                   6393: ###############################################
                   6394: sub get_sections {
1.419     raeburn  6395:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 6396:     if (!defined($cdom) || !defined($cnum)) {
                   6397:         my $cid =  $env{'request.course.id'};
                   6398: 
                   6399: 	return if (!defined($cid));
                   6400: 
                   6401:         $cdom = $env{'course.'.$cid.'.domain'};
                   6402:         $cnum = $env{'course.'.$cid.'.num'};
                   6403:     }
                   6404: 
                   6405:     my %sectioncount;
1.419     raeburn  6406:     my $now = time;
1.240     albertel 6407: 
1.366     albertel 6408:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 6409: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 6410: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   6411: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  6412:         my $start_index = &Apache::loncoursedata::CL_START();
                   6413:         my $end_index = &Apache::loncoursedata::CL_END();
                   6414:         my $status;
1.366     albertel 6415: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  6416: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   6417: 				                     $data->[$status_index],
                   6418:                                                      $data->[$start_index],
                   6419:                                                      $data->[$end_index]);
                   6420:             if ($stu_status eq 'Active') {
                   6421:                 $status = 'active';
                   6422:             } elsif ($end < $now) {
                   6423:                 $status = 'previous';
                   6424:             } elsif ($start > $now) {
                   6425:                 $status = 'future';
                   6426:             } 
                   6427: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   6428:                 if ((!defined($possible_status)) || (($status ne '') && 
                   6429:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   6430: 		    $sectioncount{$section}++;
                   6431:                 }
1.240     albertel 6432: 	    }
                   6433: 	}
                   6434:     }
                   6435:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6436:     foreach my $user (sort(keys(%courseroles))) {
                   6437: 	if ($user !~ /^(\w{2})/) { next; }
                   6438: 	my ($role) = ($user =~ /^(\w{2})/);
                   6439: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  6440: 	my ($section,$status);
1.240     albertel 6441: 	if ($role eq 'cr' &&
                   6442: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   6443: 	    $section=$1;
                   6444: 	}
                   6445: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   6446: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  6447:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   6448:         if ($end == -1 && $start == -1) {
                   6449:             next; #deleted role
                   6450:         }
                   6451:         if (!defined($possible_status)) { 
                   6452:             $sectioncount{$section}++;
                   6453:         } else {
                   6454:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   6455:                 $status = 'active';
                   6456:             } elsif ($end < $now) {
                   6457:                 $status = 'future';
                   6458:             } elsif ($start > $now) {
                   6459:                 $status = 'previous';
                   6460:             }
                   6461:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   6462:                 $sectioncount{$section}++;
                   6463:             }
                   6464:         }
1.233     raeburn  6465:     }
1.366     albertel 6466:     return %sectioncount;
1.233     raeburn  6467: }
                   6468: 
1.274     raeburn  6469: ###############################################
1.294     raeburn  6470: 
                   6471: =pod
1.405     albertel 6472: 
                   6473: =item * &get_course_users()
                   6474: 
1.275     raeburn  6475: Retrieves usernames:domains for users in the specified course
                   6476: with specific role(s), and access status. 
                   6477: 
                   6478: Incoming parameters:
1.277     albertel 6479: 1. course domain
                   6480: 2. course number
                   6481: 3. access status: users must have - either active, 
1.275     raeburn  6482: previous, future, or all.
1.277     albertel 6483: 4. reference to array of permissible roles
1.288     raeburn  6484: 5. reference to array of section restrictions (optional)
                   6485: 6. reference to results object (hash of hashes).
                   6486: 7. reference to optional userdata hash
1.609     raeburn  6487: 8. reference to optional statushash
1.630     raeburn  6488: 9. flag if privileged users (except those set to unhide in
                   6489:    course settings) should be excluded    
1.609     raeburn  6490: Keys of top level results hash are roles.
1.275     raeburn  6491: Keys of inner hashes are username:domain, with 
                   6492: values set to access type.
1.288     raeburn  6493: Optional userdata hash returns an array with arguments in the 
                   6494: same order as loncoursedata::get_classlist() for student data.
                   6495: 
1.609     raeburn  6496: Optional statushash returns
                   6497: 
1.288     raeburn  6498: Entries for end, start, section and status are blank because
                   6499: of the possibility of multiple values for non-student roles.
                   6500: 
1.275     raeburn  6501: =cut
1.405     albertel 6502: 
1.275     raeburn  6503: ###############################################
1.405     albertel 6504: 
1.275     raeburn  6505: sub get_course_users {
1.630     raeburn  6506:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  6507:     my %idx = ();
1.419     raeburn  6508:     my %seclists;
1.288     raeburn  6509: 
                   6510:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   6511:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   6512:     $idx{end} = &Apache::loncoursedata::CL_END();
                   6513:     $idx{start} = &Apache::loncoursedata::CL_START();
                   6514:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   6515:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   6516:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   6517:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   6518: 
1.290     albertel 6519:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 6520:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  6521:         my $now = time;
1.277     albertel 6522:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  6523:             my $match = 0;
1.412     raeburn  6524:             my $secmatch = 0;
1.419     raeburn  6525:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  6526:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  6527:             if ($section eq '') {
                   6528:                 $section = 'none';
                   6529:             }
1.291     albertel 6530:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6531:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6532:                     $secmatch = 1;
                   6533:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 6534:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6535:                         $secmatch = 1;
                   6536:                     }
                   6537:                 } else {  
1.419     raeburn  6538: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  6539: 		        $secmatch = 1;
                   6540:                     }
1.290     albertel 6541: 		}
1.412     raeburn  6542:                 if (!$secmatch) {
                   6543:                     next;
                   6544:                 }
1.419     raeburn  6545:             }
1.275     raeburn  6546:             if (defined($$types{'active'})) {
1.288     raeburn  6547:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  6548:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  6549:                     $match = 1;
1.275     raeburn  6550:                 }
                   6551:             }
                   6552:             if (defined($$types{'previous'})) {
1.609     raeburn  6553:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  6554:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  6555:                     $match = 1;
1.275     raeburn  6556:                 }
                   6557:             }
                   6558:             if (defined($$types{'future'})) {
1.609     raeburn  6559:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  6560:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  6561:                     $match = 1;
1.275     raeburn  6562:                 }
                   6563:             }
1.609     raeburn  6564:             if ($match) {
                   6565:                 push(@{$seclists{$student}},$section);
                   6566:                 if (ref($userdata) eq 'HASH') {
                   6567:                     $$userdata{$student} = $$classlist{$student};
                   6568:                 }
                   6569:                 if (ref($statushash) eq 'HASH') {
                   6570:                     $statushash->{$student}{'st'}{$section} = $status;
                   6571:                 }
1.288     raeburn  6572:             }
1.275     raeburn  6573:         }
                   6574:     }
1.412     raeburn  6575:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  6576:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6577:         my $now = time;
1.609     raeburn  6578:         my %displaystatus = ( previous => 'Expired',
                   6579:                               active   => 'Active',
                   6580:                               future   => 'Future',
                   6581:                             );
1.630     raeburn  6582:         my %nothide;
                   6583:         if ($hidepriv) {
                   6584:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   6585:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   6586:                 if ($user !~ /:/) {
                   6587:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   6588:                 } else {
                   6589:                     $nothide{$user} = 1;
                   6590:                 }
                   6591:             }
                   6592:         }
1.439     raeburn  6593:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  6594:             my $match = 0;
1.412     raeburn  6595:             my $secmatch = 0;
1.439     raeburn  6596:             my $status;
1.412     raeburn  6597:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  6598:             $user =~ s/:$//;
1.439     raeburn  6599:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   6600:             if ($end == -1 || $start == -1) {
                   6601:                 next;
                   6602:             }
                   6603:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   6604:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  6605:                 my ($uname,$udom) = split(/:/,$user);
                   6606:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 6607:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  6608:                         $secmatch = 1;
                   6609:                     } elsif ($usec eq '') {
1.420     albertel 6610:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  6611:                             $secmatch = 1;
                   6612:                         }
                   6613:                     } else {
                   6614:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   6615:                             $secmatch = 1;
                   6616:                         }
                   6617:                     }
                   6618:                     if (!$secmatch) {
                   6619:                         next;
                   6620:                     }
1.288     raeburn  6621:                 }
1.419     raeburn  6622:                 if ($usec eq '') {
                   6623:                     $usec = 'none';
                   6624:                 }
1.275     raeburn  6625:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  6626:                     if ($hidepriv) {
                   6627:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   6628:                             (!$nothide{$uname.':'.$udom})) {
                   6629:                             next;
                   6630:                         }
                   6631:                     }
1.503     raeburn  6632:                     if ($end > 0 && $end < $now) {
1.439     raeburn  6633:                         $status = 'previous';
                   6634:                     } elsif ($start > $now) {
                   6635:                         $status = 'future';
                   6636:                     } else {
                   6637:                         $status = 'active';
                   6638:                     }
1.277     albertel 6639:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  6640:                         if ($status eq $type) {
1.420     albertel 6641:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  6642:                                 push(@{$$users{$role}{$user}},$type);
                   6643:                             }
1.288     raeburn  6644:                             $match = 1;
                   6645:                         }
                   6646:                     }
1.419     raeburn  6647:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   6648:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   6649: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   6650:                         }
1.420     albertel 6651:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  6652:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   6653:                         }
1.609     raeburn  6654:                         if (ref($statushash) eq 'HASH') {
                   6655:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   6656:                         }
1.275     raeburn  6657:                     }
                   6658:                 }
                   6659:             }
                   6660:         }
1.290     albertel 6661:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  6662:             if ((defined($cdom)) && (defined($cnum))) {
                   6663:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   6664:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   6665:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  6666:                     next if ($owner eq '');
                   6667:                     my ($ownername,$ownerdom);
                   6668:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   6669:                         $ownername = $1;
                   6670:                         $ownerdom = $2;
                   6671:                     } else {
                   6672:                         $ownername = $owner;
                   6673:                         $ownerdom = $cdom;
                   6674:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  6675:                     }
                   6676:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 6677:                     if (defined($userdata) && 
1.609     raeburn  6678: 			!exists($$userdata{$owner})) {
                   6679: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   6680:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   6681:                             push(@{$seclists{$owner}},'none');
                   6682:                         }
                   6683:                         if (ref($statushash) eq 'HASH') {
                   6684:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  6685:                         }
1.290     albertel 6686: 		    }
1.279     raeburn  6687:                 }
                   6688:             }
                   6689:         }
1.419     raeburn  6690:         foreach my $user (keys(%seclists)) {
                   6691:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   6692:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   6693:         }
1.275     raeburn  6694:     }
                   6695:     return;
                   6696: }
                   6697: 
1.288     raeburn  6698: sub get_user_info {
                   6699:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 6700:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   6701: 	&plainname($uname,$udom,'lastname');
1.291     albertel 6702:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  6703:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  6704:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   6705:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  6706:     return;
                   6707: }
1.275     raeburn  6708: 
1.472     raeburn  6709: ###############################################
                   6710: 
                   6711: =pod
                   6712: 
                   6713: =item * &get_user_quota()
                   6714: 
                   6715: Retrieves quota assigned for storage of portfolio files for a user  
                   6716: 
                   6717: Incoming parameters:
                   6718: 1. user's username
                   6719: 2. user's domain
                   6720: 
                   6721: Returns:
1.536     raeburn  6722: 1. Disk quota (in Mb) assigned to student.
                   6723: 2. (Optional) Type of setting: custom or default
                   6724:    (individually assigned or default for user's 
                   6725:    institutional status).
                   6726: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   6727:    or student - types as defined in localenroll::inst_usertypes 
                   6728:    for user's domain, which determines default quota for user.
                   6729: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  6730: 
                   6731: If a value has been stored in the user's environment, 
1.536     raeburn  6732: it will return that, otherwise it returns the maximal default
                   6733: defined for the user's instituional status(es) in the domain.
1.472     raeburn  6734: 
                   6735: =cut
                   6736: 
                   6737: ###############################################
                   6738: 
                   6739: 
                   6740: sub get_user_quota {
                   6741:     my ($uname,$udom) = @_;
1.536     raeburn  6742:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  6743:     if (!defined($udom)) {
                   6744:         $udom = $env{'user.domain'};
                   6745:     }
                   6746:     if (!defined($uname)) {
                   6747:         $uname = $env{'user.name'};
                   6748:     }
                   6749:     if (($udom eq '' || $uname eq '') ||
                   6750:         ($udom eq 'public') && ($uname eq 'public')) {
                   6751:         $quota = 0;
1.536     raeburn  6752:         $quotatype = 'default';
                   6753:         $defquota = 0; 
1.472     raeburn  6754:     } else {
1.536     raeburn  6755:         my $inststatus;
1.472     raeburn  6756:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   6757:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  6758:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  6759:         } else {
1.536     raeburn  6760:             my %userenv = 
                   6761:                 &Apache::lonnet::get('environment',['portfolioquota',
                   6762:                                      'inststatus'],$udom,$uname);
1.472     raeburn  6763:             my ($tmp) = keys(%userenv);
                   6764:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   6765:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  6766:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  6767:             } else {
                   6768:                 undef(%userenv);
                   6769:             }
                   6770:         }
1.536     raeburn  6771:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  6772:         if ($quota eq '') {
1.536     raeburn  6773:             $quota = $defquota;
                   6774:             $quotatype = 'default';
                   6775:         } else {
                   6776:             $quotatype = 'custom';
1.472     raeburn  6777:         }
                   6778:     }
1.536     raeburn  6779:     if (wantarray) {
                   6780:         return ($quota,$quotatype,$settingstatus,$defquota);
                   6781:     } else {
                   6782:         return $quota;
                   6783:     }
1.472     raeburn  6784: }
                   6785: 
                   6786: ###############################################
                   6787: 
                   6788: =pod
                   6789: 
                   6790: =item * &default_quota()
                   6791: 
1.536     raeburn  6792: Retrieves default quota assigned for storage of user portfolio files,
                   6793: given an (optional) user's institutional status.
1.472     raeburn  6794: 
                   6795: Incoming parameters:
                   6796: 1. domain
1.536     raeburn  6797: 2. (Optional) institutional status(es).  This is a : separated list of 
                   6798:    status types (e.g., faculty, staff, student etc.)
                   6799:    which apply to the user for whom the default is being retrieved.
                   6800:    If the institutional status string in undefined, the domain
                   6801:    default quota will be returned. 
1.472     raeburn  6802: 
                   6803: Returns:
                   6804: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  6805: 2. (Optional) institutional type which determined the value of the
                   6806:    default quota.
1.472     raeburn  6807: 
                   6808: If a value has been stored in the domain's configuration db,
                   6809: it will return that, otherwise it returns 20 (for backwards 
                   6810: compatibility with domains which have not set up a configuration
                   6811: db file; the original statically defined portfolio quota was 20 Mb). 
                   6812: 
1.536     raeburn  6813: If the user's status includes multiple types (e.g., staff and student),
                   6814: the largest default quota which applies to the user determines the
                   6815: default quota returned.
                   6816: 
1.472     raeburn  6817: =cut
                   6818: 
                   6819: ###############################################
                   6820: 
                   6821: 
                   6822: sub default_quota {
1.536     raeburn  6823:     my ($udom,$inststatus) = @_;
                   6824:     my ($defquota,$settingstatus);
                   6825:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  6826:                                             ['quotas'],$udom);
                   6827:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  6828:         if ($inststatus ne '') {
1.692.4.2  raeburn  6829:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  6830:             foreach my $item (@statuses) {
1.692.4.2  raeburn  6831:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   6832:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   6833:                         if ($defquota eq '') {
                   6834:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   6835:                             $settingstatus = $item;
                   6836:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   6837:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   6838:                             $settingstatus = $item;
                   6839:                         }
                   6840:                     }
                   6841:                 } else {
                   6842:                     if ($quotahash{'quotas'}{$item} ne '') {
                   6843:                         if ($defquota eq '') {
                   6844:                             $defquota = $quotahash{'quotas'}{$item};
                   6845:                             $settingstatus = $item;
                   6846:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   6847:                             $defquota = $quotahash{'quotas'}{$item};
                   6848:                             $settingstatus = $item;
                   6849:                         }
1.536     raeburn  6850:                     }
                   6851:                 }
                   6852:             }
                   6853:         }
                   6854:         if ($defquota eq '') {
1.692.4.2  raeburn  6855:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   6856:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   6857:             } else {
                   6858:                 $defquota = $quotahash{'quotas'}{'default'};
                   6859:             }
1.536     raeburn  6860:             $settingstatus = 'default';
                   6861:         }
                   6862:     } else {
                   6863:         $settingstatus = 'default';
                   6864:         $defquota = 20;
                   6865:     }
                   6866:     if (wantarray) {
                   6867:         return ($defquota,$settingstatus);
1.472     raeburn  6868:     } else {
1.536     raeburn  6869:         return $defquota;
1.472     raeburn  6870:     }
                   6871: }
                   6872: 
1.384     raeburn  6873: sub get_secgrprole_info {
                   6874:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   6875:     my %sections_count = &get_sections($cdom,$cnum);
                   6876:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   6877:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   6878:     my @groups = sort(keys(%curr_groups));
                   6879:     my $allroles = [];
                   6880:     my $rolehash;
                   6881:     my $accesshash = {
                   6882:                      active => 'Currently has access',
                   6883:                      future => 'Will have future access',
                   6884:                      previous => 'Previously had access',
                   6885:                   };
                   6886:     if ($needroles) {
                   6887:         $rolehash = {'all' => 'all'};
1.385     albertel 6888:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   6889: 	if (&Apache::lonnet::error(%user_roles)) {
                   6890: 	    undef(%user_roles);
                   6891: 	}
                   6892:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  6893:             my ($role)=split(/\:/,$item,2);
                   6894:             if ($role eq 'cr') { next; }
                   6895:             if ($role =~ /^cr/) {
                   6896:                 $$rolehash{$role} = (split('/',$role))[3];
                   6897:             } else {
                   6898:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   6899:             }
                   6900:         }
                   6901:         foreach my $key (sort(keys(%{$rolehash}))) {
                   6902:             push(@{$allroles},$key);
                   6903:         }
                   6904:         push (@{$allroles},'st');
                   6905:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   6906:     }
                   6907:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   6908: }
                   6909: 
1.555     raeburn  6910: sub user_picker {
1.627     raeburn  6911:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
1.555     raeburn  6912:     my $currdom = $dom;
                   6913:     my %curr_selected = (
                   6914:                         srchin => 'dom',
1.580     raeburn  6915:                         srchby => 'lastname',
1.555     raeburn  6916:                       );
                   6917:     my $srchterm;
1.625     raeburn  6918:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  6919:         if ($srch->{'srchby'} ne '') {
                   6920:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   6921:         }
                   6922:         if ($srch->{'srchin'} ne '') {
                   6923:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   6924:         }
                   6925:         if ($srch->{'srchtype'} ne '') {
                   6926:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   6927:         }
                   6928:         if ($srch->{'srchdomain'} ne '') {
                   6929:             $currdom = $srch->{'srchdomain'};
                   6930:         }
                   6931:         $srchterm = $srch->{'srchterm'};
                   6932:     }
                   6933:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  6934:                     'usr'       => 'Search criteria',
1.563     raeburn  6935:                     'doma'      => 'Domain/institution to search',
1.558     albertel 6936:                     'uname'     => 'username',
                   6937:                     'lastname'  => 'last name',
1.555     raeburn  6938:                     'lastfirst' => 'last name, first name',
1.558     albertel 6939:                     'crs'       => 'in this course',
1.576     raeburn  6940:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 6941:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  6942:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 6943:                     'exact'     => 'is',
                   6944:                     'contains'  => 'contains',
1.569     raeburn  6945:                     'begins'    => 'begins with',
1.571     raeburn  6946:                     'youm'      => "You must include some text to search for.",
                   6947:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   6948:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   6949:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   6950:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   6951:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   6952:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   6953:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  6954:                                        );
1.563     raeburn  6955:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   6956:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  6957: 
                   6958:     my @srchins = ('crs','dom','alc','instd');
                   6959: 
                   6960:     foreach my $option (@srchins) {
                   6961:         # FIXME 'alc' option unavailable until 
                   6962:         #       loncreateuser::print_user_query_page()
                   6963:         #       has been completed.
                   6964:         next if ($option eq 'alc');
1.692.4.11  raeburn  6965:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
1.555     raeburn  6966:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  6967:         if ($curr_selected{'srchin'} eq $option) {
                   6968:             $srchinsel .= ' 
                   6969:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6970:         } else {
                   6971:             $srchinsel .= '
                   6972:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6973:         }
1.555     raeburn  6974:     }
1.563     raeburn  6975:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  6976: 
                   6977:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  6978:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  6979:         if ($curr_selected{'srchby'} eq $option) {
                   6980:             $srchbysel .= '
                   6981:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6982:         } else {
                   6983:             $srchbysel .= '
                   6984:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6985:          }
                   6986:     }
                   6987:     $srchbysel .= "\n  </select>\n";
                   6988: 
                   6989:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  6990:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  6991:         if ($curr_selected{'srchtype'} eq $option) {
                   6992:             $srchtypesel .= '
                   6993:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   6994:         } else {
                   6995:             $srchtypesel .= '
                   6996:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   6997:         }
                   6998:     }
                   6999:     $srchtypesel .= "\n  </select>\n";
                   7000: 
1.558     albertel 7001:     my ($newuserscript,$new_user_create);
1.556     raeburn  7002: 
                   7003:     if ($forcenewuser) {
1.576     raeburn  7004:         if (ref($srch) eq 'HASH') {
                   7005:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
1.627     raeburn  7006:                 if ($cancreate) {
                   7007:                     $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>';
                   7008:                 } else {
1.692.4.2  raeburn  7009:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  7010:                     my %usertypetext = (
                   7011:                         official   => 'institutional',
                   7012:                         unofficial => 'non-institutional',
                   7013:                     );
1.692.4.2  raeburn  7014:                     $new_user_create = '<p class="LC_warning">'.
                   7015:                                        &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
                   7016:                                        &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
1.627     raeburn  7017:                 }
1.576     raeburn  7018:             }
                   7019:         }
                   7020: 
1.556     raeburn  7021:         $newuserscript = <<"ENDSCRIPT";
                   7022: 
1.570     raeburn  7023: function setSearch(createnew,callingForm) {
1.556     raeburn  7024:     if (createnew == 1) {
1.570     raeburn  7025:         for (var i=0; i<callingForm.srchby.length; i++) {
                   7026:             if (callingForm.srchby.options[i].value == 'uname') {
                   7027:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  7028:             }
                   7029:         }
1.570     raeburn  7030:         for (var i=0; i<callingForm.srchin.length; i++) {
                   7031:             if ( callingForm.srchin.options[i].value == 'dom') {
                   7032: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  7033:             }
                   7034:         }
1.570     raeburn  7035:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   7036:             if (callingForm.srchtype.options[i].value == 'exact') {
                   7037:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  7038:             }
                   7039:         }
1.570     raeburn  7040:         for (var i=0; i<callingForm.srchdomain.length; i++) {
                   7041:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
                   7042:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  7043:             }
                   7044:         }
                   7045:     }
                   7046: }
                   7047: ENDSCRIPT
1.558     albertel 7048: 
1.556     raeburn  7049:     }
                   7050: 
1.555     raeburn  7051:     my $output = <<"END_BLOCK";
1.556     raeburn  7052: <script type="text/javascript">
1.692.4.4  raeburn  7053: // <![CDATA[
1.570     raeburn  7054: function validateEntry(callingForm) {
1.558     albertel 7055: 
1.556     raeburn  7056:     var checkok = 1;
1.558     albertel 7057:     var srchin;
1.570     raeburn  7058:     for (var i=0; i<callingForm.srchin.length; i++) {
                   7059: 	if ( callingForm.srchin[i].checked ) {
                   7060: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 7061: 	}
                   7062:     }
                   7063: 
1.570     raeburn  7064:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   7065:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   7066:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   7067:     var srchterm =  callingForm.srchterm.value;
                   7068:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  7069:     var msg = "";
                   7070: 
                   7071:     if (srchterm == "") {
                   7072:         checkok = 0;
1.571     raeburn  7073:         msg += "$lt{'youm'}\\n";
1.556     raeburn  7074:     }
                   7075: 
1.569     raeburn  7076:     if (srchtype== 'begins') {
                   7077:         if (srchterm.length < 2) {
                   7078:             checkok = 0;
1.571     raeburn  7079:             msg += "$lt{'thte'}\\n";
1.569     raeburn  7080:         }
                   7081:     }
                   7082: 
1.556     raeburn  7083:     if (srchtype== 'contains') {
                   7084:         if (srchterm.length < 3) {
                   7085:             checkok = 0;
1.571     raeburn  7086:             msg += "$lt{'thet'}\\n";
1.556     raeburn  7087:         }
                   7088:     }
                   7089:     if (srchin == 'instd') {
                   7090:         if (srchdomain == '') {
                   7091:             checkok = 0;
1.571     raeburn  7092:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  7093:         }
                   7094:     }
                   7095:     if (srchin == 'dom') {
                   7096:         if (srchdomain == '') {
                   7097:             checkok = 0;
1.571     raeburn  7098:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  7099:         }
                   7100:     }
                   7101:     if (srchby == 'lastfirst') {
                   7102:         if (srchterm.indexOf(",") == -1) {
                   7103:             checkok = 0;
1.571     raeburn  7104:             msg += "$lt{'whus'}\\n";
1.556     raeburn  7105:         }
                   7106:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   7107:             checkok = 0;
1.571     raeburn  7108:             msg += "$lt{'whse'}\\n";
1.556     raeburn  7109:         }
                   7110:     }
                   7111:     if (checkok == 0) {
1.571     raeburn  7112:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  7113:         return;
                   7114:     }
                   7115:     if (checkok == 1) {
1.570     raeburn  7116:         callingForm.submit();
1.556     raeburn  7117:     }
                   7118: }
                   7119: 
                   7120: $newuserscript
                   7121: 
1.692.4.4  raeburn  7122: // ]]>
1.556     raeburn  7123: </script>
1.558     albertel 7124: 
                   7125: $new_user_create
                   7126: 
1.555     raeburn  7127: END_BLOCK
1.558     albertel 7128: 
1.692.4.9  raeburn  7129:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   7130:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   7131:                $domform.
                   7132:                &Apache::lonhtmlcommon::row_closure().
                   7133:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   7134:                $srchbysel.
                   7135:                $srchtypesel.
                   7136:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   7137:                $srchinsel.
                   7138:                &Apache::lonhtmlcommon::row_closure(1).
                   7139:                &Apache::lonhtmlcommon::end_pick_box().
                   7140:                '<br />';
1.555     raeburn  7141:     return $output;
                   7142: }
                   7143: 
1.612     raeburn  7144: sub user_rule_check {
1.615     raeburn  7145:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  7146:     my $response;
                   7147:     if (ref($usershash) eq 'HASH') {
                   7148:         foreach my $user (keys(%{$usershash})) {
                   7149:             my ($uname,$udom) = split(/:/,$user);
                   7150:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  7151:             my ($id,$newuser);
1.612     raeburn  7152:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  7153:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  7154:                 $id = $usershash->{$user}->{'id'};
                   7155:             }
                   7156:             my $inst_response;
                   7157:             if (ref($checks) eq 'HASH') {
                   7158:                 if (defined($checks->{'username'})) {
1.615     raeburn  7159:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  7160:                         &Apache::lonnet::get_instuser($udom,$uname);
                   7161:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  7162:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  7163:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   7164:                 }
1.615     raeburn  7165:             } else {
                   7166:                 ($inst_response,%{$inst_results->{$user}}) =
                   7167:                     &Apache::lonnet::get_instuser($udom,$uname);
                   7168:                 return;
1.612     raeburn  7169:             }
1.615     raeburn  7170:             if (!$got_rules->{$udom}) {
1.612     raeburn  7171:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   7172:                                                   ['usercreation'],$udom);
                   7173:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  7174:                     foreach my $item ('username','id') {
1.612     raeburn  7175:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   7176:                             $$curr_rules{$udom}{$item} = 
                   7177:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  7178:                         }
                   7179:                     }
                   7180:                 }
1.615     raeburn  7181:                 $got_rules->{$udom} = 1;  
1.585     raeburn  7182:             }
1.612     raeburn  7183:             foreach my $item (keys(%{$checks})) {
                   7184:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   7185:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   7186:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   7187:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   7188:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   7189:                                 if ($rule_check{$rule}) {
                   7190:                                     $$rulematch{$user}{$item} = $rule;
                   7191:                                     if ($inst_response eq 'ok') {
1.615     raeburn  7192:                                         if (ref($inst_results) eq 'HASH') {
                   7193:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   7194:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   7195:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   7196:                                                 }
1.612     raeburn  7197:                                             }
                   7198:                                         }
1.615     raeburn  7199:                                     }
                   7200:                                     last;
1.585     raeburn  7201:                                 }
                   7202:                             }
                   7203:                         }
                   7204:                     }
                   7205:                 }
                   7206:             }
                   7207:         }
                   7208:     }
1.612     raeburn  7209:     return;
                   7210: }
                   7211: 
                   7212: sub user_rule_formats {
                   7213:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   7214:     my %text = ( 
                   7215:                  'username' => 'Usernames',
                   7216:                  'id'       => 'IDs',
                   7217:                );
                   7218:     my $output;
                   7219:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   7220:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   7221:         if (@{$ruleorder} > 0) {
                   7222:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
                   7223:             foreach my $rule (@{$ruleorder}) {
                   7224:                 if (ref($curr_rules) eq 'ARRAY') {
                   7225:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   7226:                         if (ref($rules->{$rule}) eq 'HASH') {
                   7227:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   7228:                                         $rules->{$rule}{'desc'}.'</li>';
                   7229:                         }
                   7230:                     }
                   7231:                 }
                   7232:             }
                   7233:             $output .= '</ul>';
                   7234:         }
                   7235:     }
                   7236:     return $output;
                   7237: }
                   7238: 
                   7239: sub instrule_disallow_msg {
1.615     raeburn  7240:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  7241:     my $response;
                   7242:     my %text = (
                   7243:                   item   => 'username',
                   7244:                   items  => 'usernames',
                   7245:                   match  => 'matches',
                   7246:                   do     => 'does',
                   7247:                   action => 'a username',
                   7248:                   one    => 'one',
                   7249:                );
                   7250:     if ($count > 1) {
                   7251:         $text{'item'} = 'usernames';
                   7252:         $text{'match'} ='match';
                   7253:         $text{'do'} = 'do';
                   7254:         $text{'action'} = 'usernames',
                   7255:         $text{'one'} = 'ones';
                   7256:     }
                   7257:     if ($checkitem eq 'id') {
                   7258:         $text{'items'} = 'IDs';
                   7259:         $text{'item'} = 'ID';
                   7260:         $text{'action'} = 'an ID';
1.615     raeburn  7261:         if ($count > 1) {
                   7262:             $text{'item'} = 'IDs';
                   7263:             $text{'action'} = 'IDs';
                   7264:         }
1.612     raeburn  7265:     }
1.674     bisitz   7266:     $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  7267:     if ($mode eq 'upload') {
                   7268:         if ($checkitem eq 'username') {
                   7269:             $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'}.");
                   7270:         } elsif ($checkitem eq 'id') {
1.674     bisitz   7271:             $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  7272:         }
1.669     raeburn  7273:     } elsif ($mode eq 'selfcreate') {
                   7274:         if ($checkitem eq 'id') {
                   7275:             $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.");
                   7276:         }
1.615     raeburn  7277:     } else {
                   7278:         if ($checkitem eq 'username') {
                   7279:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   7280:         } elsif ($checkitem eq 'id') {
                   7281:             $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.");
                   7282:         }
1.612     raeburn  7283:     }
                   7284:     return $response;
1.585     raeburn  7285: }
                   7286: 
1.624     raeburn  7287: sub personal_data_fieldtitles {
                   7288:     my %fieldtitles = &Apache::lonlocal::texthash (
                   7289:                         id => 'Student/Employee ID',
                   7290:                         permanentemail => 'E-mail address',
                   7291:                         lastname => 'Last Name',
                   7292:                         firstname => 'First Name',
                   7293:                         middlename => 'Middle Name',
                   7294:                         generation => 'Generation',
                   7295:                         gen => 'Generation',
1.692.4.2  raeburn  7296:                         inststatus => 'Affiliation',
1.624     raeburn  7297:                    );
                   7298:     return %fieldtitles;
                   7299: }
                   7300: 
1.642     raeburn  7301: sub sorted_inst_types {
                   7302:     my ($dom) = @_;
                   7303:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   7304:     my $othertitle = &mt('All users');
                   7305:     if ($env{'request.course.id'}) {
1.668     raeburn  7306:         $othertitle  = &mt('Any users');
1.642     raeburn  7307:     }
                   7308:     my @types;
                   7309:     if (ref($order) eq 'ARRAY') {
                   7310:         @types = @{$order};
                   7311:     }
                   7312:     if (@types == 0) {
                   7313:         if (ref($usertypes) eq 'HASH') {
                   7314:             @types = sort(keys(%{$usertypes}));
                   7315:         }
                   7316:     }
                   7317:     if (keys(%{$usertypes}) > 0) {
                   7318:         $othertitle = &mt('Other users');
                   7319:     }
                   7320:     return ($othertitle,$usertypes,\@types);
                   7321: }
                   7322: 
1.645     raeburn  7323: sub get_institutional_codes {
                   7324:     my ($settings,$allcourses,$LC_code) = @_;
                   7325: # Get complete list of course sections to update
                   7326:     my @currsections = ();
                   7327:     my @currxlists = ();
                   7328:     my $coursecode = $$settings{'internal.coursecode'};
                   7329: 
                   7330:     if ($$settings{'internal.sectionnums'} ne '') {
                   7331:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   7332:     }
                   7333: 
                   7334:     if ($$settings{'internal.crosslistings'} ne '') {
                   7335:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   7336:     }
                   7337: 
                   7338:     if (@currxlists > 0) {
                   7339:         foreach (@currxlists) {
                   7340:             if (m/^([^:]+):(\w*)$/) {
                   7341:                 unless (grep/^$1$/,@{$allcourses}) {
                   7342:                     push @{$allcourses},$1;
                   7343:                     $$LC_code{$1} = $2;
                   7344:                 }
                   7345:             }
                   7346:         }
                   7347:     }
                   7348:  
                   7349:     if (@currsections > 0) {
                   7350:         foreach (@currsections) {
                   7351:             if (m/^(\w+):(\w*)$/) {
                   7352:                 my $sec = $coursecode.$1;
                   7353:                 my $lc_sec = $2;
                   7354:                 unless (grep/^$sec$/,@{$allcourses}) {
                   7355:                     push @{$allcourses},$sec;
                   7356:                     $$LC_code{$sec} = $lc_sec;
                   7357:                 }
                   7358:             }
                   7359:         }
                   7360:     }
                   7361:     return;
                   7362: }
                   7363: 
1.112     bowersj2 7364: =pod
                   7365: 
1.692.4.2  raeburn  7366: =head1 Slot Helpers
                   7367: 
                   7368: =over 4
                   7369: 
                   7370: =item * sorted_slots()
                   7371: 
                   7372: Sorts an array of slot names in order of slot start time (earliest first).
                   7373: 
                   7374: Inputs:
                   7375: 
                   7376: =over 4
                   7377: 
                   7378: slotsarr  - Reference to array of unsorted slot names.
                   7379: 
                   7380: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   7381: 
                   7382: =back
                   7383: 
                   7384: Returns:
                   7385: 
                   7386: =over 4
                   7387: 
                   7388: sorted   - An array of slot names sorted by the start time of the slot.
                   7389: 
                   7390: =back
                   7391: 
                   7392: =back
                   7393: 
                   7394: =cut
                   7395: 
                   7396: 
                   7397: sub sorted_slots {
                   7398:     my ($slotsarr,$slots) = @_;
                   7399:     my @sorted;
                   7400:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   7401:         @sorted =
                   7402:             sort {
                   7403:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
                   7404:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
                   7405:                      }
                   7406:                      if (ref($slots->{$a})) { return -1;}
                   7407:                      if (ref($slots->{$b})) { return 1;}
                   7408:                      return 0;
                   7409:                  } @{$slotsarr};
                   7410:     }
                   7411:     return @sorted;
                   7412: }
                   7413: 
                   7414: =pod
                   7415: 
1.549     albertel 7416: =back
                   7417: 
                   7418: =head1 HTTP Helpers
                   7419: 
                   7420: =over 4
                   7421: 
1.648     raeburn  7422: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 7423: 
1.258     albertel 7424: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 7425: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 7426: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 7427: 
                   7428: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   7429: $possible_names is an ref to an array of form element names.  As an example:
                   7430: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 7431: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 7432: 
                   7433: =cut
1.1       albertel 7434: 
1.6       albertel 7435: sub get_unprocessed_cgi {
1.25      albertel 7436:   my ($query,$possible_names)= @_;
1.26      matthew  7437:   # $Apache::lonxml::debug=1;
1.356     albertel 7438:   foreach my $pair (split(/&/,$query)) {
                   7439:     my ($name, $value) = split(/=/,$pair);
1.369     www      7440:     $name = &unescape($name);
1.25      albertel 7441:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   7442:       $value =~ tr/+/ /;
                   7443:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 7444:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 7445:     }
1.16      harris41 7446:   }
1.6       albertel 7447: }
                   7448: 
1.112     bowersj2 7449: =pod
                   7450: 
1.648     raeburn  7451: =item * &cacheheader() 
1.112     bowersj2 7452: 
                   7453: returns cache-controlling header code
                   7454: 
                   7455: =cut
                   7456: 
1.7       albertel 7457: sub cacheheader {
1.258     albertel 7458:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 7459:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   7460:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 7461:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   7462:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 7463:     return $output;
1.7       albertel 7464: }
                   7465: 
1.112     bowersj2 7466: =pod
                   7467: 
1.648     raeburn  7468: =item * &no_cache($r) 
1.112     bowersj2 7469: 
                   7470: specifies header code to not have cache
                   7471: 
                   7472: =cut
                   7473: 
1.9       albertel 7474: sub no_cache {
1.216     albertel 7475:     my ($r) = @_;
                   7476:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 7477: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 7478:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   7479:     $r->no_cache(1);
                   7480:     $r->header_out("Expires" => $date);
                   7481:     $r->header_out("Pragma" => "no-cache");
1.123     www      7482: }
                   7483: 
                   7484: sub content_type {
1.181     albertel 7485:     my ($r,$type,$charset) = @_;
1.299     foxr     7486:     if ($r) {
                   7487: 	#  Note that printout.pl calls this with undef for $r.
                   7488: 	&no_cache($r);
                   7489:     }
1.258     albertel 7490:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 7491:     unless ($charset) {
                   7492: 	$charset=&Apache::lonlocal::current_encoding;
                   7493:     }
                   7494:     if ($charset) { $type.='; charset='.$charset; }
                   7495:     if ($r) {
                   7496: 	$r->content_type($type);
                   7497:     } else {
                   7498: 	print("Content-type: $type\n\n");
                   7499:     }
1.9       albertel 7500: }
1.25      albertel 7501: 
1.112     bowersj2 7502: =pod
                   7503: 
1.648     raeburn  7504: =item * &add_to_env($name,$value) 
1.112     bowersj2 7505: 
1.258     albertel 7506: adds $name to the %env hash with value
1.112     bowersj2 7507: $value, if $name already exists, the entry is converted to an array
                   7508: reference and $value is added to the array.
                   7509: 
                   7510: =cut
                   7511: 
1.25      albertel 7512: sub add_to_env {
                   7513:   my ($name,$value)=@_;
1.258     albertel 7514:   if (defined($env{$name})) {
                   7515:     if (ref($env{$name})) {
1.25      albertel 7516:       #already have multiple values
1.258     albertel 7517:       push(@{ $env{$name} },$value);
1.25      albertel 7518:     } else {
                   7519:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 7520:       my $first=$env{$name};
                   7521:       undef($env{$name});
                   7522:       push(@{ $env{$name} },$first,$value);
1.25      albertel 7523:     }
                   7524:   } else {
1.258     albertel 7525:     $env{$name}=$value;
1.25      albertel 7526:   }
1.31      albertel 7527: }
1.149     albertel 7528: 
                   7529: =pod
                   7530: 
1.648     raeburn  7531: =item * &get_env_multiple($name) 
1.149     albertel 7532: 
1.258     albertel 7533: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 7534: values may be defined and end up as an array ref.
                   7535: 
                   7536: returns an array of values
                   7537: 
                   7538: =cut
                   7539: 
                   7540: sub get_env_multiple {
                   7541:     my ($name) = @_;
                   7542:     my @values;
1.258     albertel 7543:     if (defined($env{$name})) {
1.149     albertel 7544:         # exists is it an array
1.258     albertel 7545:         if (ref($env{$name})) {
                   7546:             @values=@{ $env{$name} };
1.149     albertel 7547:         } else {
1.258     albertel 7548:             $values[0]=$env{$name};
1.149     albertel 7549:         }
                   7550:     }
                   7551:     return(@values);
                   7552: }
                   7553: 
1.660     raeburn  7554: sub ask_for_embedded_content {
                   7555:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
                   7556:     my $upload_output = '
                   7557:    <form name="upload_embedded" action="'.$actionurl.'"
                   7558:                   method="post" enctype="multipart/form-data">';
                   7559:     $upload_output .= $state;
1.661     raeburn  7560:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
1.660     raeburn  7561: 
                   7562:     my $num = 0;
                   7563:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
                   7564:         $upload_output .= &start_data_table_row().
                   7565:             '<td>'.$embed_file.'</td><td>';
                   7566:         if ($args->{'ignore_remote_references'}
                   7567:             && $embed_file =~ m{^\w+://}) {
                   7568:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
                   7569:         } elsif ($args->{'error_on_invalid_names'}
                   7570:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
                   7571: 
                   7572:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
                   7573: 
                   7574:         } else {
                   7575:             $upload_output .='
1.661     raeburn  7576:            <input name="embedded_item_'.$num.'" type="file" value="" />
1.660     raeburn  7577:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
                   7578:             my $attrib = join(':',@{$$allfiles{$embed_file}});
                   7579:             $upload_output .=
                   7580:                 "\n\t\t".
                   7581:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   7582:                 $attrib.'" />';
                   7583:             if (exists($$codebase{$embed_file})) {
                   7584:                 $upload_output .=
                   7585:                     "\n\t\t".
                   7586:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
                   7587:                     &escape($$codebase{$embed_file}).'" />';
                   7588:             }
                   7589:         }
                   7590:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
                   7591:         $num++;
                   7592:     }
                   7593:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
                   7594:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
                   7595:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
                   7596:    '.&mt('(only files for which a location has been provided will be uploaded)').'
                   7597:    </form>';
                   7598:     return $upload_output;
                   7599: }
                   7600: 
1.661     raeburn  7601: sub upload_embedded {
                   7602:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
                   7603:         $current_disk_usage) = @_;
                   7604:     my $output;
                   7605:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   7606:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   7607:         my $orig_uploaded_filename =
                   7608:             $env{'form.embedded_item_'.$i.'.filename'};
                   7609: 
                   7610:         $env{'form.embedded_orig_'.$i} =
                   7611:             &unescape($env{'form.embedded_orig_'.$i});
                   7612:         my ($path,$fname) =
                   7613:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   7614:         # no path, whole string is fname
                   7615:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   7616: 
                   7617:         $path = $env{'form.currentpath'}.$path;
                   7618:         $fname = &Apache::lonnet::clean_filename($fname);
                   7619:         # See if there is anything left
                   7620:         next if ($fname eq '');
                   7621: 
                   7622:         # Check if file already exists as a file or directory.
                   7623:         my ($state,$msg);
                   7624:         if ($context eq 'portfolio') {
                   7625:             my $port_path = $dirpath;
                   7626:             if ($group ne '') {
                   7627:                 $port_path = "groups/$group/$port_path";
                   7628:             }
                   7629:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
                   7630:                                               $dir_root,$port_path,$disk_quota,
                   7631:                                               $current_disk_usage,$uname,$udom);
                   7632:             if ($state eq 'will_exceed_quota'
                   7633:                 || $state eq 'file_locked'
                   7634:                 || $state eq 'file_exists' ) {
                   7635:                 $output .= $msg;
                   7636:                 next;
                   7637:             }
                   7638:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   7639:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   7640:             if ($state eq 'exists') {
                   7641:                 $output .= $msg;
                   7642:                 next;
                   7643:             }
                   7644:         }
                   7645:         # Check if extension is valid
                   7646:         if (($fname =~ /\.(\w+)$/) &&
                   7647:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
                   7648:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
                   7649:             next;
                   7650:         } elsif (($fname =~ /\.(\w+)$/) &&
                   7651:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
                   7652:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
                   7653:             next;
                   7654:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
                   7655:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
                   7656:             next;
                   7657:         }
                   7658: 
                   7659:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   7660:         if ($context eq 'portfolio') {
                   7661:             my $result=
                   7662:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
                   7663:                                                 $dirpath.$path);
                   7664:             if ($result !~ m|^/uploaded/|) {
                   7665:                 $output .= '<span class="LC_error">'
                   7666:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   7667:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   7668:                       .'</span><br />';
                   7669:                 next;
                   7670:             } else {
                   7671:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
                   7672:                            $path.$fname.'</span>').'</p>';     
                   7673:             }
                   7674:         } else {
                   7675: # Save the file
                   7676:             my $target = $env{'form.embedded_item_'.$i};
                   7677:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   7678:             my $dest = $fullpath.$fname;
                   7679:             my $url = $url_root.$dirpath.'/'.$path.$fname;
                   7680:             my @parts=split(/\//,$fullpath);
                   7681:             my $count;
                   7682:             my $filepath = $dir_root;
                   7683:             for ($count=4;$count<=$#parts;$count++) {
                   7684:                 $filepath .= "/$parts[$count]";
                   7685:                 if ((-e $filepath)!=1) {
                   7686:                     mkdir($filepath,0770);
                   7687:                 }
                   7688:             }
                   7689:             my $fh;
                   7690:             if (!open($fh,'>'.$dest)) {
                   7691:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   7692:                 $output .= '<span class="LC_error">'.
                   7693:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7694:                            '</span><br />';
                   7695:             } else {
                   7696:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   7697:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   7698:                     $output .= '<span class="LC_error">'.
                   7699:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
                   7700:                               '</span><br />';
                   7701:                 } else {
                   7702:                     if ($context eq 'testbank') {
                   7703:                         $output .= &mt('Embedded file uploaded successfully:').
                   7704:                                    '&nbsp;<a href="'.$url.'">'.
                   7705:                                    $orig_uploaded_filename.'</a><br />';
                   7706:                     } else {
                   7707:                         $output .= '<font size="+2">'.
                   7708:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
                   7709:                                    $orig_uploaded_filename.'</a>').'</font><br />';
                   7710:                     }
                   7711:                 }
                   7712:                 close($fh);
                   7713:             }
                   7714:         }
                   7715:     }
                   7716:     return $output;
                   7717: }
                   7718: 
                   7719: sub check_for_existing {
                   7720:     my ($path,$fname,$element) = @_;
                   7721:     my ($state,$msg);
                   7722:     if (-d $path.'/'.$fname) {
                   7723:         $state = 'exists';
                   7724:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7725:     } elsif (-e $path.'/'.$fname) {
                   7726:         $state = 'exists';
                   7727:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   7728:     }
                   7729:     if ($state eq 'exists') {
                   7730:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   7731:     }
                   7732:     return ($state,$msg);
                   7733: }
                   7734: 
                   7735: sub check_for_upload {
                   7736:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   7737:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
                   7738:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
                   7739:     my $getpropath = 1;
                   7740:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
                   7741:                                             $getpropath);
                   7742:     my $found_file = 0;
                   7743:     my $locked_file = 0;
                   7744:     foreach my $line (@dir_list) {
                   7745:         my ($file_name)=split(/\&/,$line,2);
                   7746:         if ($file_name eq $fname){
                   7747:             $file_name = $path.$file_name;
                   7748:             if ($group ne '') {
                   7749:                 $file_name = $group.$file_name;
                   7750:             }
                   7751:             $found_file = 1;
                   7752:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
                   7753:                 $locked_file = 1;
                   7754:             }
                   7755:         }
                   7756:     }
                   7757:     if (($current_disk_usage + $filesize) > $disk_quota){
                   7758:         my $msg = '<span class="LC_error">'.
                   7759:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   7760:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   7761:         return ('will_exceed_quota',$msg);
                   7762:     } elsif ($found_file) {
                   7763:         if ($locked_file) {
                   7764:             my $msg = '<span class="LC_error">';
                   7765:             $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>');
                   7766:             $msg .= '</span><br />';
                   7767:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   7768:             return ('file_locked',$msg);
                   7769:         } else {
                   7770:             my $msg = '<span class="LC_error">';
                   7771:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
                   7772:             $msg .= '</span>';
                   7773:             $msg .= '<br />';
                   7774:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
                   7775:             return ('file_exists',$msg);
                   7776:         }
                   7777:     }
                   7778: }
                   7779: 
1.31      albertel 7780: 
1.41      ng       7781: =pod
1.45      matthew  7782: 
1.464     albertel 7783: =back
1.41      ng       7784: 
1.112     bowersj2 7785: =head1 CSV Upload/Handling functions
1.38      albertel 7786: 
1.41      ng       7787: =over 4
                   7788: 
1.648     raeburn  7789: =item * &upfile_store($r)
1.41      ng       7790: 
                   7791: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 7792: needs $env{'form.upfile'}
1.41      ng       7793: returns $datatoken to be put into hidden field
                   7794: 
                   7795: =cut
1.31      albertel 7796: 
                   7797: sub upfile_store {
                   7798:     my $r=shift;
1.258     albertel 7799:     $env{'form.upfile'}=~s/\r/\n/gs;
                   7800:     $env{'form.upfile'}=~s/\f/\n/gs;
                   7801:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   7802:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 7803: 
1.258     albertel 7804:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   7805: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 7806:     {
1.158     raeburn  7807:         my $datafile = $r->dir_config('lonDaemons').
                   7808:                            '/tmp/'.$datatoken.'.tmp';
                   7809:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 7810:             print $fh $env{'form.upfile'};
1.158     raeburn  7811:             close($fh);
                   7812:         }
1.31      albertel 7813:     }
                   7814:     return $datatoken;
                   7815: }
                   7816: 
1.56      matthew  7817: =pod
                   7818: 
1.648     raeburn  7819: =item * &load_tmp_file($r)
1.41      ng       7820: 
                   7821: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 7822: needs $env{'form.datatoken'},
                   7823: sets $env{'form.upfile'} to the contents of the file
1.41      ng       7824: 
                   7825: =cut
1.31      albertel 7826: 
                   7827: sub load_tmp_file {
                   7828:     my $r=shift;
                   7829:     my @studentdata=();
                   7830:     {
1.158     raeburn  7831:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 7832:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  7833:         if ( open(my $fh,"<$studentfile") ) {
                   7834:             @studentdata=<$fh>;
                   7835:             close($fh);
                   7836:         }
1.31      albertel 7837:     }
1.258     albertel 7838:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 7839: }
                   7840: 
1.56      matthew  7841: =pod
                   7842: 
1.648     raeburn  7843: =item * &upfile_record_sep()
1.41      ng       7844: 
                   7845: Separate uploaded file into records
                   7846: returns array of records,
1.258     albertel 7847: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       7848: 
                   7849: =cut
1.31      albertel 7850: 
                   7851: sub upfile_record_sep {
1.258     albertel 7852:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 7853:     } else {
1.248     albertel 7854: 	my @records;
1.258     albertel 7855: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 7856: 	    if ($line=~/^\s*$/) { next; }
                   7857: 	    push(@records,$line);
                   7858: 	}
                   7859: 	return @records;
1.31      albertel 7860:     }
                   7861: }
                   7862: 
1.56      matthew  7863: =pod
                   7864: 
1.648     raeburn  7865: =item * &record_sep($record)
1.41      ng       7866: 
1.258     albertel 7867: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       7868: 
                   7869: =cut
                   7870: 
1.263     www      7871: sub takeleft {
                   7872:     my $index=shift;
                   7873:     return substr('0000'.$index,-4,4);
                   7874: }
                   7875: 
1.31      albertel 7876: sub record_sep {
                   7877:     my $record=shift;
                   7878:     my %components=();
1.258     albertel 7879:     if ($env{'form.upfiletype'} eq 'xml') {
                   7880:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 7881:         my $i=0;
1.356     albertel 7882:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 7883:             $field=~s/^(\"|\')//;
                   7884:             $field=~s/(\"|\')$//;
1.263     www      7885:             $components{&takeleft($i)}=$field;
1.31      albertel 7886:             $i++;
                   7887:         }
1.258     albertel 7888:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 7889:         my $i=0;
1.356     albertel 7890:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 7891:             $field=~s/^(\"|\')//;
                   7892:             $field=~s/(\"|\')$//;
1.263     www      7893:             $components{&takeleft($i)}=$field;
1.31      albertel 7894:             $i++;
                   7895:         }
                   7896:     } else {
1.561     www      7897:         my $separator=',';
1.480     banghart 7898:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      7899:             $separator=';';
1.480     banghart 7900:         }
1.31      albertel 7901:         my $i=0;
1.561     www      7902: # the character we are looking for to indicate the end of a quote or a record 
                   7903:         my $looking_for=$separator;
                   7904: # do not add the characters to the fields
                   7905:         my $ignore=0;
                   7906: # we just encountered a separator (or the beginning of the record)
                   7907:         my $just_found_separator=1;
                   7908: # store the field we are working on here
                   7909:         my $field='';
                   7910: # work our way through all characters in record
                   7911:         foreach my $character ($record=~/(.)/g) {
                   7912:             if ($character eq $looking_for) {
                   7913:                if ($character ne $separator) {
                   7914: # Found the end of a quote, again looking for separator
                   7915:                   $looking_for=$separator;
                   7916:                   $ignore=1;
                   7917:                } else {
                   7918: # Found a separator, store away what we got
                   7919:                   $components{&takeleft($i)}=$field;
                   7920: 	          $i++;
                   7921:                   $just_found_separator=1;
                   7922:                   $ignore=0;
                   7923:                   $field='';
                   7924:                }
                   7925:                next;
                   7926:             }
                   7927: # single or double quotation marks after a separator indicate beginning of a quote
                   7928: # we are now looking for the end of the quote and need to ignore separators
                   7929:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   7930:                $looking_for=$character;
                   7931:                next;
                   7932:             }
                   7933: # ignore would be true after we reached the end of a quote
                   7934:             if ($ignore) { next; }
                   7935:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   7936:             $field.=$character;
                   7937:             $just_found_separator=0; 
1.31      albertel 7938:         }
1.561     www      7939: # catch the very last entry, since we never encountered the separator
                   7940:         $components{&takeleft($i)}=$field;
1.31      albertel 7941:     }
                   7942:     return %components;
                   7943: }
                   7944: 
1.144     matthew  7945: ######################################################
                   7946: ######################################################
                   7947: 
1.56      matthew  7948: =pod
                   7949: 
1.648     raeburn  7950: =item * &upfile_select_html()
1.41      ng       7951: 
1.144     matthew  7952: Return HTML code to select a file from the users machine and specify 
                   7953: the file type.
1.41      ng       7954: 
                   7955: =cut
                   7956: 
1.144     matthew  7957: ######################################################
                   7958: ######################################################
1.31      albertel 7959: sub upfile_select_html {
1.144     matthew  7960:     my %Types = (
                   7961:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 7962:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  7963:                  space => &mt('Space separated'),
                   7964:                  tab   => &mt('Tabulator separated'),
                   7965: #                 xml   => &mt('HTML/XML'),
                   7966:                  );
                   7967:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.692.4.2  raeburn  7968:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  7969:     foreach my $type (sort(keys(%Types))) {
                   7970:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   7971:     }
                   7972:     $Str .= "</select>\n";
                   7973:     return $Str;
1.31      albertel 7974: }
                   7975: 
1.301     albertel 7976: sub get_samples {
                   7977:     my ($records,$toget) = @_;
                   7978:     my @samples=({});
                   7979:     my $got=0;
                   7980:     foreach my $rec (@$records) {
                   7981: 	my %temp = &record_sep($rec);
                   7982: 	if (! grep(/\S/, values(%temp))) { next; }
                   7983: 	if (%temp) {
                   7984: 	    $samples[$got]=\%temp;
                   7985: 	    $got++;
                   7986: 	    if ($got == $toget) { last; }
                   7987: 	}
                   7988:     }
                   7989:     return \@samples;
                   7990: }
                   7991: 
1.144     matthew  7992: ######################################################
                   7993: ######################################################
                   7994: 
1.56      matthew  7995: =pod
                   7996: 
1.648     raeburn  7997: =item * &csv_print_samples($r,$records)
1.41      ng       7998: 
                   7999: Prints a table of sample values from each column uploaded $r is an
                   8000: Apache Request ref, $records is an arrayref from
                   8001: &Apache::loncommon::upfile_record_sep
                   8002: 
                   8003: =cut
                   8004: 
1.144     matthew  8005: ######################################################
                   8006: ######################################################
1.31      albertel 8007: sub csv_print_samples {
                   8008:     my ($r,$records) = @_;
1.662     bisitz   8009:     my $samples = &get_samples($records,5);
1.301     albertel 8010: 
1.594     raeburn  8011:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   8012:               &start_data_table_header_row());
1.356     albertel 8013:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.692.4.6  raeburn  8014:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
                   8015:     }
1.594     raeburn  8016:     $r->print(&end_data_table_header_row());
1.301     albertel 8017:     foreach my $hash (@$samples) {
1.594     raeburn  8018: 	$r->print(&start_data_table_row());
1.356     albertel 8019: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 8020: 	    $r->print('<td>');
1.356     albertel 8021: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 8022: 	    $r->print('</td>');
                   8023: 	}
1.594     raeburn  8024: 	$r->print(&end_data_table_row());
1.31      albertel 8025:     }
1.594     raeburn  8026:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 8027: }
                   8028: 
1.144     matthew  8029: ######################################################
                   8030: ######################################################
                   8031: 
1.56      matthew  8032: =pod
                   8033: 
1.648     raeburn  8034: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       8035: 
                   8036: Prints a table to create associations between values and table columns.
1.144     matthew  8037: 
1.41      ng       8038: $r is an Apache Request ref,
                   8039: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  8040: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       8041: 
                   8042: =cut
                   8043: 
1.144     matthew  8044: ######################################################
                   8045: ######################################################
1.31      albertel 8046: sub csv_print_select_table {
                   8047:     my ($r,$records,$d) = @_;
1.301     albertel 8048:     my $i=0;
                   8049:     my $samples = &get_samples($records,1);
1.144     matthew  8050:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  8051: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  8052:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  8053:               '<th>'.&mt('Column').'</th>'.
                   8054:               &end_data_table_header_row()."\n");
1.356     albertel 8055:     foreach my $array_ref (@$d) {
                   8056: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.689     bisitz   8057: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 8058: 
1.692.4.8  raeburn  8059: 	$r->print('<td><select name"f'.$i.'"'.
1.32      matthew  8060: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 8061: 	$r->print('<option value="none"></option>');
1.356     albertel 8062: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   8063: 	    $r->print('<option value="'.$sample.'"'.
                   8064:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   8065:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 8066: 	}
1.594     raeburn  8067: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 8068: 	$i++;
                   8069:     }
1.594     raeburn  8070:     $r->print(&end_data_table());
1.31      albertel 8071:     $i--;
                   8072:     return $i;
                   8073: }
1.56      matthew  8074: 
1.144     matthew  8075: ######################################################
                   8076: ######################################################
                   8077: 
1.56      matthew  8078: =pod
1.31      albertel 8079: 
1.648     raeburn  8080: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       8081: 
                   8082: Prints a table of sample values from the upload and can make associate samples to internal names.
                   8083: 
                   8084: $r is an Apache Request ref,
                   8085: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   8086: $d is an array of 2 element arrays (internal name, displayed name)
                   8087: 
                   8088: =cut
                   8089: 
1.144     matthew  8090: ######################################################
                   8091: ######################################################
1.31      albertel 8092: sub csv_samples_select_table {
                   8093:     my ($r,$records,$d) = @_;
                   8094:     my $i=0;
1.144     matthew  8095:     #
1.662     bisitz   8096:     my $max_samples = 5;
                   8097:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  8098:     $r->print(&start_data_table().
                   8099:               &start_data_table_header_row().'<th>'.
                   8100:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   8101:               &end_data_table_header_row());
1.301     albertel 8102: 
                   8103:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  8104: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  8105: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 8106: 	foreach my $option (@$d) {
                   8107: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  8108: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 8109:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  8110:                       $display.'</option>');
1.31      albertel 8111: 	}
                   8112: 	$r->print('</select></td><td>');
1.662     bisitz   8113: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 8114: 	    if (defined($samples->[$line]{$key})) { 
                   8115: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   8116: 	    }
                   8117: 	}
1.594     raeburn  8118: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 8119: 	$i++;
                   8120:     }
1.594     raeburn  8121:     $r->print(&end_data_table());
1.31      albertel 8122:     $i--;
                   8123:     return($i);
1.115     matthew  8124: }
                   8125: 
1.144     matthew  8126: ######################################################
                   8127: ######################################################
                   8128: 
1.115     matthew  8129: =pod
                   8130: 
1.648     raeburn  8131: =item * &clean_excel_name($name)
1.115     matthew  8132: 
                   8133: Returns a replacement for $name which does not contain any illegal characters.
                   8134: 
                   8135: =cut
                   8136: 
1.144     matthew  8137: ######################################################
                   8138: ######################################################
1.115     matthew  8139: sub clean_excel_name {
                   8140:     my ($name) = @_;
                   8141:     $name =~ s/[:\*\?\/\\]//g;
                   8142:     if (length($name) > 31) {
                   8143:         $name = substr($name,0,31);
                   8144:     }
                   8145:     return $name;
1.25      albertel 8146: }
1.84      albertel 8147: 
1.85      albertel 8148: =pod
                   8149: 
1.648     raeburn  8150: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 8151: 
                   8152: Returns either 1 or undef
                   8153: 
                   8154: 1 if the part is to be hidden, undef if it is to be shown
                   8155: 
                   8156: Arguments are:
                   8157: 
                   8158: $id the id of the part to be checked
                   8159: $symb, optional the symb of the resource to check
                   8160: $udom, optional the domain of the user to check for
                   8161: $uname, optional the username of the user to check for
                   8162: 
                   8163: =cut
1.84      albertel 8164: 
                   8165: sub check_if_partid_hidden {
                   8166:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 8167:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 8168: 					 $symb,$udom,$uname);
1.141     albertel 8169:     my $truth=1;
                   8170:     #if the string starts with !, then the list is the list to show not hide
                   8171:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 8172:     my @hiddenlist=split(/,/,$hiddenparts);
                   8173:     foreach my $checkid (@hiddenlist) {
1.141     albertel 8174: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 8175:     }
1.141     albertel 8176:     return !$truth;
1.84      albertel 8177: }
1.127     matthew  8178: 
1.138     matthew  8179: 
                   8180: ############################################################
                   8181: ############################################################
                   8182: 
                   8183: =pod
                   8184: 
1.157     matthew  8185: =back 
                   8186: 
1.138     matthew  8187: =head1 cgi-bin script and graphing routines
                   8188: 
1.157     matthew  8189: =over 4
                   8190: 
1.648     raeburn  8191: =item * &get_cgi_id()
1.138     matthew  8192: 
                   8193: Inputs: none
                   8194: 
                   8195: Returns an id which can be used to pass environment variables
                   8196: to various cgi-bin scripts.  These environment variables will
                   8197: be removed from the users environment after a given time by
                   8198: the routine &Apache::lonnet::transfer_profile_to_env.
                   8199: 
                   8200: =cut
                   8201: 
                   8202: ############################################################
                   8203: ############################################################
1.152     albertel 8204: my $uniq=0;
1.136     matthew  8205: sub get_cgi_id {
1.154     albertel 8206:     $uniq=($uniq+1)%100000;
1.280     albertel 8207:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  8208: }
                   8209: 
1.127     matthew  8210: ############################################################
                   8211: ############################################################
                   8212: 
                   8213: =pod
                   8214: 
1.648     raeburn  8215: =item * &DrawBarGraph()
1.127     matthew  8216: 
1.138     matthew  8217: Facilitates the plotting of data in a (stacked) bar graph.
                   8218: Puts plot definition data into the users environment in order for 
                   8219: graph.png to plot it.  Returns an <img> tag for the plot.
                   8220: The bars on the plot are labeled '1','2',...,'n'.
                   8221: 
                   8222: Inputs:
                   8223: 
                   8224: =over 4
                   8225: 
                   8226: =item $Title: string, the title of the plot
                   8227: 
                   8228: =item $xlabel: string, text describing the X-axis of the plot
                   8229: 
                   8230: =item $ylabel: string, text describing the Y-axis of the plot
                   8231: 
                   8232: =item $Max: scalar, the maximum Y value to use in the plot
                   8233: If $Max is < any data point, the graph will not be rendered.
                   8234: 
1.140     matthew  8235: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  8236: they are plotted.  If undefined, default values will be used.
                   8237: 
1.178     matthew  8238: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   8239: 
1.138     matthew  8240: =item @Values: An array of array references.  Each array reference holds data
                   8241: to be plotted in a stacked bar chart.
                   8242: 
1.239     matthew  8243: =item If the final element of @Values is a hash reference the key/value
                   8244: pairs will be added to the graph definition.
                   8245: 
1.138     matthew  8246: =back
                   8247: 
                   8248: Returns:
                   8249: 
                   8250: An <img> tag which references graph.png and the appropriate identifying
                   8251: information for the plot.
                   8252: 
1.127     matthew  8253: =cut
                   8254: 
                   8255: ############################################################
                   8256: ############################################################
1.134     matthew  8257: sub DrawBarGraph {
1.178     matthew  8258:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  8259:     #
                   8260:     if (! defined($colors)) {
                   8261:         $colors = ['#33ff00', 
                   8262:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   8263:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   8264:                   ]; 
                   8265:     }
1.228     matthew  8266:     my $extra_settings = {};
                   8267:     if (ref($Values[-1]) eq 'HASH') {
                   8268:         $extra_settings = pop(@Values);
                   8269:     }
1.127     matthew  8270:     #
1.136     matthew  8271:     my $identifier = &get_cgi_id();
                   8272:     my $id = 'cgi.'.$identifier;        
1.129     matthew  8273:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  8274:         return '';
                   8275:     }
1.225     matthew  8276:     #
                   8277:     my @Labels;
                   8278:     if (defined($labels)) {
                   8279:         @Labels = @$labels;
                   8280:     } else {
                   8281:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   8282:             push (@Labels,$i+1);
                   8283:         }
                   8284:     }
                   8285:     #
1.129     matthew  8286:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  8287:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  8288:     my %ValuesHash;
                   8289:     my $NumSets=1;
                   8290:     foreach my $array (@Values) {
                   8291:         next if (! ref($array));
1.136     matthew  8292:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  8293:             join(',',@$array);
1.129     matthew  8294:     }
1.127     matthew  8295:     #
1.136     matthew  8296:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  8297:     if ($NumBars < 3) {
                   8298:         $width = 120+$NumBars*32;
1.220     matthew  8299:         $xskip = 1;
1.225     matthew  8300:         $bar_width = 30;
                   8301:     } elsif ($NumBars < 5) {
                   8302:         $width = 120+$NumBars*20;
                   8303:         $xskip = 1;
                   8304:         $bar_width = 20;
1.220     matthew  8305:     } elsif ($NumBars < 10) {
1.136     matthew  8306:         $width = 120+$NumBars*15;
                   8307:         $xskip = 1;
                   8308:         $bar_width = 15;
                   8309:     } elsif ($NumBars <= 25) {
                   8310:         $width = 120+$NumBars*11;
                   8311:         $xskip = 5;
                   8312:         $bar_width = 8;
                   8313:     } elsif ($NumBars <= 50) {
                   8314:         $width = 120+$NumBars*8;
                   8315:         $xskip = 5;
                   8316:         $bar_width = 4;
                   8317:     } else {
                   8318:         $width = 120+$NumBars*8;
                   8319:         $xskip = 5;
                   8320:         $bar_width = 4;
                   8321:     }
                   8322:     #
1.137     matthew  8323:     $Max = 1 if ($Max < 1);
                   8324:     if ( int($Max) < $Max ) {
                   8325:         $Max++;
                   8326:         $Max = int($Max);
                   8327:     }
1.127     matthew  8328:     $Title  = '' if (! defined($Title));
                   8329:     $xlabel = '' if (! defined($xlabel));
                   8330:     $ylabel = '' if (! defined($ylabel));
1.369     www      8331:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   8332:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   8333:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  8334:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  8335:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   8336:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   8337:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   8338:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8339:     $ValuesHash{$id.'.height'}   = $height;
                   8340:     $ValuesHash{$id.'.width'}    = $width;
                   8341:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   8342:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   8343:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  8344:     #
1.228     matthew  8345:     # Deal with other parameters
                   8346:     while (my ($key,$value) = each(%$extra_settings)) {
                   8347:         $ValuesHash{$id.'.'.$key} = $value;
                   8348:     }
                   8349:     #
1.646     raeburn  8350:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  8351:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   8352: }
                   8353: 
                   8354: ############################################################
                   8355: ############################################################
                   8356: 
                   8357: =pod
                   8358: 
1.648     raeburn  8359: =item * &DrawXYGraph()
1.137     matthew  8360: 
1.138     matthew  8361: Facilitates the plotting of data in an XY graph.
                   8362: Puts plot definition data into the users environment in order for 
                   8363: graph.png to plot it.  Returns an <img> tag for the plot.
                   8364: 
                   8365: Inputs:
                   8366: 
                   8367: =over 4
                   8368: 
                   8369: =item $Title: string, the title of the plot
                   8370: 
                   8371: =item $xlabel: string, text describing the X-axis of the plot
                   8372: 
                   8373: =item $ylabel: string, text describing the Y-axis of the plot
                   8374: 
                   8375: =item $Max: scalar, the maximum Y value to use in the plot
                   8376: If $Max is < any data point, the graph will not be rendered.
                   8377: 
                   8378: =item $colors: Array ref containing the hex color codes for the data to be 
                   8379: plotted in.  If undefined, default values will be used.
                   8380: 
                   8381: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   8382: 
                   8383: =item $Ydata: Array ref containing Array refs.  
1.185     www      8384: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  8385: 
                   8386: =item %Values: hash indicating or overriding any default values which are 
                   8387: passed to graph.png.  
                   8388: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   8389: 
                   8390: =back
                   8391: 
                   8392: Returns:
                   8393: 
                   8394: An <img> tag which references graph.png and the appropriate identifying
                   8395: information for the plot.
                   8396: 
1.137     matthew  8397: =cut
                   8398: 
                   8399: ############################################################
                   8400: ############################################################
                   8401: sub DrawXYGraph {
                   8402:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   8403:     #
                   8404:     # Create the identifier for the graph
                   8405:     my $identifier = &get_cgi_id();
                   8406:     my $id = 'cgi.'.$identifier;
                   8407:     #
                   8408:     $Title  = '' if (! defined($Title));
                   8409:     $xlabel = '' if (! defined($xlabel));
                   8410:     $ylabel = '' if (! defined($ylabel));
                   8411:     my %ValuesHash = 
                   8412:         (
1.369     www      8413:          $id.'.title'  => &escape($Title),
                   8414:          $id.'.xlabel' => &escape($xlabel),
                   8415:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  8416:          $id.'.y_max_value'=> $Max,
                   8417:          $id.'.labels'     => join(',',@$Xlabels),
                   8418:          $id.'.PlotType'   => 'XY',
                   8419:          );
                   8420:     #
                   8421:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   8422:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8423:     }
                   8424:     #
                   8425:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   8426:         return '';
                   8427:     }
                   8428:     my $NumSets=1;
1.138     matthew  8429:     foreach my $array (@{$Ydata}){
1.137     matthew  8430:         next if (! ref($array));
                   8431:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   8432:     }
1.138     matthew  8433:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  8434:     #
                   8435:     # Deal with other parameters
                   8436:     while (my ($key,$value) = each(%Values)) {
                   8437:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  8438:     }
                   8439:     #
1.646     raeburn  8440:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  8441:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   8442: }
                   8443: 
                   8444: ############################################################
                   8445: ############################################################
                   8446: 
                   8447: =pod
                   8448: 
1.648     raeburn  8449: =item * &DrawXYYGraph()
1.138     matthew  8450: 
                   8451: Facilitates the plotting of data in an XY graph with two Y axes.
                   8452: Puts plot definition data into the users environment in order for 
                   8453: graph.png to plot it.  Returns an <img> tag for the plot.
                   8454: 
                   8455: Inputs:
                   8456: 
                   8457: =over 4
                   8458: 
                   8459: =item $Title: string, the title of the plot
                   8460: 
                   8461: =item $xlabel: string, text describing the X-axis of the plot
                   8462: 
                   8463: =item $ylabel: string, text describing the Y-axis of the plot
                   8464: 
                   8465: =item $colors: Array ref containing the hex color codes for the data to be 
                   8466: plotted in.  If undefined, default values will be used.
                   8467: 
                   8468: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   8469: 
                   8470: =item $Ydata1: The first data set
                   8471: 
                   8472: =item $Min1: The minimum value of the left Y-axis
                   8473: 
                   8474: =item $Max1: The maximum value of the left Y-axis
                   8475: 
                   8476: =item $Ydata2: The second data set
                   8477: 
                   8478: =item $Min2: The minimum value of the right Y-axis
                   8479: 
                   8480: =item $Max2: The maximum value of the left Y-axis
                   8481: 
                   8482: =item %Values: hash indicating or overriding any default values which are 
                   8483: passed to graph.png.  
                   8484: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   8485: 
                   8486: =back
                   8487: 
                   8488: Returns:
                   8489: 
                   8490: An <img> tag which references graph.png and the appropriate identifying
                   8491: information for the plot.
1.136     matthew  8492: 
                   8493: =cut
                   8494: 
                   8495: ############################################################
                   8496: ############################################################
1.137     matthew  8497: sub DrawXYYGraph {
                   8498:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   8499:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  8500:     #
                   8501:     # Create the identifier for the graph
                   8502:     my $identifier = &get_cgi_id();
                   8503:     my $id = 'cgi.'.$identifier;
                   8504:     #
                   8505:     $Title  = '' if (! defined($Title));
                   8506:     $xlabel = '' if (! defined($xlabel));
                   8507:     $ylabel = '' if (! defined($ylabel));
                   8508:     my %ValuesHash = 
                   8509:         (
1.369     www      8510:          $id.'.title'  => &escape($Title),
                   8511:          $id.'.xlabel' => &escape($xlabel),
                   8512:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  8513:          $id.'.labels' => join(',',@$Xlabels),
                   8514:          $id.'.PlotType' => 'XY',
                   8515:          $id.'.NumSets' => 2,
1.137     matthew  8516:          $id.'.two_axes' => 1,
                   8517:          $id.'.y1_max_value' => $Max1,
                   8518:          $id.'.y1_min_value' => $Min1,
                   8519:          $id.'.y2_max_value' => $Max2,
                   8520:          $id.'.y2_min_value' => $Min2,
1.136     matthew  8521:          );
                   8522:     #
1.137     matthew  8523:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   8524:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   8525:     }
                   8526:     #
                   8527:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   8528:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  8529:         return '';
                   8530:     }
                   8531:     my $NumSets=1;
1.137     matthew  8532:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  8533:         next if (! ref($array));
                   8534:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  8535:     }
                   8536:     #
                   8537:     # Deal with other parameters
                   8538:     while (my ($key,$value) = each(%Values)) {
                   8539:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  8540:     }
                   8541:     #
1.646     raeburn  8542:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 8543:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  8544: }
                   8545: 
                   8546: ############################################################
                   8547: ############################################################
                   8548: 
                   8549: =pod
                   8550: 
1.157     matthew  8551: =back 
                   8552: 
1.139     matthew  8553: =head1 Statistics helper routines?  
                   8554: 
                   8555: Bad place for them but what the hell.
                   8556: 
1.157     matthew  8557: =over 4
                   8558: 
1.648     raeburn  8559: =item * &chartlink()
1.139     matthew  8560: 
                   8561: Returns a link to the chart for a specific student.  
                   8562: 
                   8563: Inputs:
                   8564: 
                   8565: =over 4
                   8566: 
                   8567: =item $linktext: The text of the link
                   8568: 
                   8569: =item $sname: The students username
                   8570: 
                   8571: =item $sdomain: The students domain
                   8572: 
                   8573: =back
                   8574: 
1.157     matthew  8575: =back
                   8576: 
1.139     matthew  8577: =cut
                   8578: 
                   8579: ############################################################
                   8580: ############################################################
                   8581: sub chartlink {
                   8582:     my ($linktext, $sname, $sdomain) = @_;
                   8583:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      8584:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 8585:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  8586:        '">'.$linktext.'</a>';
1.153     matthew  8587: }
                   8588: 
                   8589: #######################################################
                   8590: #######################################################
                   8591: 
                   8592: =pod
                   8593: 
                   8594: =head1 Course Environment Routines
1.157     matthew  8595: 
                   8596: =over 4
1.153     matthew  8597: 
1.648     raeburn  8598: =item * &restore_course_settings()
1.153     matthew  8599: 
1.648     raeburn  8600: =item * &store_course_settings()
1.153     matthew  8601: 
                   8602: Restores/Store indicated form parameters from the course environment.
                   8603: Will not overwrite existing values of the form parameters.
                   8604: 
                   8605: Inputs: 
                   8606: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   8607: 
                   8608: a hash ref describing the data to be stored.  For example:
                   8609:    
                   8610: %Save_Parameters = ('Status' => 'scalar',
                   8611:     'chartoutputmode' => 'scalar',
                   8612:     'chartoutputdata' => 'scalar',
                   8613:     'Section' => 'array',
1.373     raeburn  8614:     'Group' => 'array',
1.153     matthew  8615:     'StudentData' => 'array',
                   8616:     'Maps' => 'array');
                   8617: 
                   8618: Returns: both routines return nothing
                   8619: 
1.631     raeburn  8620: =back
                   8621: 
1.153     matthew  8622: =cut
                   8623: 
                   8624: #######################################################
                   8625: #######################################################
                   8626: sub store_course_settings {
1.496     albertel 8627:     return &store_settings($env{'request.course.id'},@_);
                   8628: }
                   8629: 
                   8630: sub store_settings {
1.153     matthew  8631:     # save to the environment
                   8632:     # appenv the same items, just to be safe
1.300     albertel 8633:     my $udom  = $env{'user.domain'};
                   8634:     my $uname = $env{'user.name'};
1.496     albertel 8635:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8636:     my %SaveHash;
                   8637:     my %AppHash;
                   8638:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 8639:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 8640:         my $envname = 'environment.'.$basename;
1.258     albertel 8641:         if (exists($env{'form.'.$setting})) {
1.153     matthew  8642:             # Save this value away
                   8643:             if ($type eq 'scalar' &&
1.258     albertel 8644:                 (! exists($env{$envname}) || 
                   8645:                  $env{$envname} ne $env{'form.'.$setting})) {
                   8646:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   8647:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  8648:             } elsif ($type eq 'array') {
                   8649:                 my $stored_form;
1.258     albertel 8650:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  8651:                     $stored_form = join(',',
                   8652:                                         map {
1.369     www      8653:                                             &escape($_);
1.258     albertel 8654:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  8655:                 } else {
                   8656:                     $stored_form = 
1.369     www      8657:                         &escape($env{'form.'.$setting});
1.153     matthew  8658:                 }
                   8659:                 # Determine if the array contents are the same.
1.258     albertel 8660:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  8661:                     $SaveHash{$basename} = $stored_form;
                   8662:                     $AppHash{$envname}   = $stored_form;
                   8663:                 }
                   8664:             }
                   8665:         }
                   8666:     }
                   8667:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 8668:                                           $udom,$uname);
1.153     matthew  8669:     if ($put_result !~ /^(ok|delayed)/) {
                   8670:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   8671:                                  'got error:'.$put_result);
                   8672:     }
                   8673:     # Make sure these settings stick around in this session, too
1.646     raeburn  8674:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  8675:     return;
                   8676: }
                   8677: 
                   8678: sub restore_course_settings {
1.499     albertel 8679:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 8680: }
                   8681: 
                   8682: sub restore_settings {
                   8683:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  8684:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 8685:         next if (exists($env{'form.'.$setting}));
1.496     albertel 8686:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  8687:             '.'.$setting;
1.258     albertel 8688:         if (exists($env{$envname})) {
1.153     matthew  8689:             if ($type eq 'scalar') {
1.258     albertel 8690:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  8691:             } elsif ($type eq 'array') {
1.258     albertel 8692:                 $env{'form.'.$setting} = [ 
1.153     matthew  8693:                                            map { 
1.369     www      8694:                                                &unescape($_); 
1.258     albertel 8695:                                            } split(',',$env{$envname})
1.153     matthew  8696:                                            ];
                   8697:             }
                   8698:         }
                   8699:     }
1.127     matthew  8700: }
                   8701: 
1.618     raeburn  8702: #######################################################
                   8703: #######################################################
                   8704: 
                   8705: =pod
                   8706: 
                   8707: =head1 Domain E-mail Routines  
                   8708: 
                   8709: =over 4
                   8710: 
1.648     raeburn  8711: =item * &build_recipient_list()
1.618     raeburn  8712: 
1.692.4.14! raeburn  8713: Build recipient lists for five types of e-mail:
1.692.4.2  raeburn  8714: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.692.4.14! raeburn  8715: (d) Help requests, (e) Course requests needing approval,  generated by
        !          8716: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
        !          8717: loncoursequeueadmin.pm respectively.
1.618     raeburn  8718: 
                   8719: Inputs:
1.619     raeburn  8720: defmail (scalar - email address of default recipient), 
1.618     raeburn  8721: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  8722: defdom (domain for which to retrieve configuration settings),
                   8723: origmail (scalar - email address of recipient from loncapa.conf, 
                   8724: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  8725: 
1.655     raeburn  8726: Returns: comma separated list of addresses to which to send e-mail.
                   8727: 
                   8728: =back
1.618     raeburn  8729: 
                   8730: =cut
                   8731: 
                   8732: ############################################################
                   8733: ############################################################
                   8734: sub build_recipient_list {
1.619     raeburn  8735:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  8736:     my @recipients;
                   8737:     my $otheremails;
                   8738:     my %domconfig =
                   8739:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   8740:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.692.4.2  raeburn  8741:         if (exists($domconfig{'contacts'}{$mailing})) {
                   8742:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   8743:                 my @contacts = ('adminemail','supportemail');
                   8744:                 foreach my $item (@contacts) {
                   8745:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   8746:                         my $addr = $domconfig{'contacts'}{$item};
                   8747:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8748:                             push(@recipients,$addr);
                   8749:                         }
1.619     raeburn  8750:                     }
1.692.4.2  raeburn  8751:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  8752:                 }
                   8753:             }
1.692.4.2  raeburn  8754:         } elsif ($origmail ne '') {
                   8755:             push(@recipients,$origmail);
1.618     raeburn  8756:         }
1.619     raeburn  8757:     } elsif ($origmail ne '') {
                   8758:         push(@recipients,$origmail);
1.618     raeburn  8759:     }
1.688     raeburn  8760:     if (defined($defmail)) {
                   8761:         if ($defmail ne '') {
                   8762:             push(@recipients,$defmail);
                   8763:         }
1.618     raeburn  8764:     }
                   8765:     if ($otheremails) {
1.619     raeburn  8766:         my @others;
                   8767:         if ($otheremails =~ /,/) {
                   8768:             @others = split(/,/,$otheremails);
1.618     raeburn  8769:         } else {
1.619     raeburn  8770:             push(@others,$otheremails);
                   8771:         }
                   8772:         foreach my $addr (@others) {
                   8773:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   8774:                 push(@recipients,$addr);
                   8775:             }
1.618     raeburn  8776:         }
                   8777:     }
1.619     raeburn  8778:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  8779:     return $recipientlist;
                   8780: }
                   8781: 
1.127     matthew  8782: ############################################################
                   8783: ############################################################
1.154     albertel 8784: 
1.655     raeburn  8785: =pod
                   8786: 
                   8787: =head1 Course Catalog Routines
                   8788: 
                   8789: =over 4
                   8790: 
                   8791: =item * &gather_categories()
                   8792: 
                   8793: Converts category definitions - keys of categories hash stored in  
                   8794: coursecategories in configuration.db on the primary library server in a 
                   8795: domain - to an array.  Also generates javascript and idx hash used to 
                   8796: generate Domain Coordinator interface for editing Course Categories.
                   8797: 
                   8798: Inputs:
1.663     raeburn  8799: 
1.655     raeburn  8800: categories (reference to hash of category definitions).
1.663     raeburn  8801: 
1.655     raeburn  8802: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8803:       categories and subcategories).
1.663     raeburn  8804: 
1.655     raeburn  8805: idx (reference to hash of counters used in Domain Coordinator interface for 
                   8806:       editing Course Categories).
1.663     raeburn  8807: 
1.655     raeburn  8808: jsarray (reference to array of categories used to create Javascript arrays for
                   8809:          Domain Coordinator interface for editing Course Categories).
                   8810: 
                   8811: Returns: nothing
                   8812: 
                   8813: Side effects: populates cats, idx and jsarray. 
                   8814: 
                   8815: =cut
                   8816: 
                   8817: sub gather_categories {
                   8818:     my ($categories,$cats,$idx,$jsarray) = @_;
                   8819:     my %counters;
                   8820:     my $num = 0;
                   8821:     foreach my $item (keys(%{$categories})) {
                   8822:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   8823:         if ($container eq '' && $depth == 0) {
                   8824:             $cats->[$depth][$categories->{$item}] = $cat;
                   8825:         } else {
                   8826:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   8827:         }
                   8828:         my ($escitem,$tail) = split(/:/,$item,2);
                   8829:         if ($counters{$tail} eq '') {
                   8830:             $counters{$tail} = $num;
                   8831:             $num ++;
                   8832:         }
                   8833:         if (ref($idx) eq 'HASH') {
                   8834:             $idx->{$item} = $counters{$tail};
                   8835:         }
                   8836:         if (ref($jsarray) eq 'ARRAY') {
                   8837:             push(@{$jsarray->[$counters{$tail}]},$item);
                   8838:         }
                   8839:     }
                   8840:     return;
                   8841: }
                   8842: 
                   8843: =pod
                   8844: 
                   8845: =item * &extract_categories()
                   8846: 
                   8847: Used to generate breadcrumb trails for course categories.
                   8848: 
                   8849: Inputs:
1.663     raeburn  8850: 
1.655     raeburn  8851: categories (reference to hash of category definitions).
1.663     raeburn  8852: 
1.655     raeburn  8853: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8854:       categories and subcategories).
1.663     raeburn  8855: 
1.655     raeburn  8856: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  8857: 
1.655     raeburn  8858: allitems (reference to hash - key is category key 
                   8859:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8860: 
1.655     raeburn  8861: idx (reference to hash of counters used in Domain Coordinator interface for
                   8862:       editing Course Categories).
1.663     raeburn  8863: 
1.655     raeburn  8864: jsarray (reference to array of categories used to create Javascript arrays for
                   8865:          Domain Coordinator interface for editing Course Categories).
                   8866: 
1.665     raeburn  8867: subcats (reference to hash of arrays containing all subcategories within each 
                   8868:          category, -recursive)
                   8869: 
1.655     raeburn  8870: Returns: nothing
                   8871: 
                   8872: Side effects: populates trails and allitems hash references.
                   8873: 
                   8874: =cut
                   8875: 
                   8876: sub extract_categories {
1.665     raeburn  8877:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  8878:     if (ref($categories) eq 'HASH') {
                   8879:         &gather_categories($categories,$cats,$idx,$jsarray);
                   8880:         if (ref($cats->[0]) eq 'ARRAY') {
                   8881:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   8882:                 my $name = $cats->[0][$i];
                   8883:                 my $item = &escape($name).'::0';
                   8884:                 my $trailstr;
                   8885:                 if ($name eq 'instcode') {
                   8886:                     $trailstr = &mt('Official courses (with institutional codes)');
                   8887:                 } else {
                   8888:                     $trailstr = $name;
                   8889:                 }
                   8890:                 if ($allitems->{$item} eq '') {
                   8891:                     push(@{$trails},$trailstr);
                   8892:                     $allitems->{$item} = scalar(@{$trails})-1;
                   8893:                 }
                   8894:                 my @parents = ($name);
                   8895:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   8896:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   8897:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  8898:                         if (ref($subcats) eq 'HASH') {
                   8899:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   8900:                         }
                   8901:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   8902:                     }
                   8903:                 } else {
                   8904:                     if (ref($subcats) eq 'HASH') {
                   8905:                         $subcats->{$item} = [];
1.655     raeburn  8906:                     }
                   8907:                 }
                   8908:             }
                   8909:         }
                   8910:     }
                   8911:     return;
                   8912: }
                   8913: 
                   8914: =pod
                   8915: 
                   8916: =item *&recurse_categories()
                   8917: 
                   8918: Recursively used to generate breadcrumb trails for course categories.
                   8919: 
                   8920: Inputs:
1.663     raeburn  8921: 
1.655     raeburn  8922: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   8923:       categories and subcategories).
1.663     raeburn  8924: 
1.655     raeburn  8925: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  8926: 
                   8927: category (current course category, for which breadcrumb trail is being generated).
                   8928: 
                   8929: trails (reference to array of breadcrumb trails for each category).
                   8930: 
1.655     raeburn  8931: allitems (reference to hash - key is category key
                   8932:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  8933: 
1.655     raeburn  8934: parents (array containing containers directories for current category, 
                   8935:          back to top level). 
                   8936: 
                   8937: Returns: nothing
                   8938: 
                   8939: Side effects: populates trails and allitems hash references
                   8940: 
                   8941: =cut
                   8942: 
                   8943: sub recurse_categories {
1.665     raeburn  8944:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  8945:     my $shallower = $depth - 1;
                   8946:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   8947:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   8948:             my $name = $cats->[$depth]{$category}[$k];
                   8949:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8950:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8951:             if ($allitems->{$item} eq '') {
                   8952:                 push(@{$trails},$trailstr);
                   8953:                 $allitems->{$item} = scalar(@{$trails})-1;
                   8954:             }
                   8955:             my $deeper = $depth+1;
                   8956:             push(@{$parents},$category);
1.665     raeburn  8957:             if (ref($subcats) eq 'HASH') {
                   8958:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   8959:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   8960:                     my $higher;
                   8961:                     if ($j > 0) {
                   8962:                         $higher = &escape($parents->[$j]).':'.
                   8963:                                   &escape($parents->[$j-1]).':'.$j;
                   8964:                     } else {
                   8965:                         $higher = &escape($parents->[$j]).'::'.$j;
                   8966:                     }
                   8967:                     push(@{$subcats->{$higher}},$subcat);
                   8968:                 }
                   8969:             }
                   8970:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   8971:                                 $subcats);
1.655     raeburn  8972:             pop(@{$parents});
                   8973:         }
                   8974:     } else {
                   8975:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   8976:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   8977:         if ($allitems->{$item} eq '') {
                   8978:             push(@{$trails},$trailstr);
                   8979:             $allitems->{$item} = scalar(@{$trails})-1;
                   8980:         }
                   8981:     }
                   8982:     return;
                   8983: }
                   8984: 
1.663     raeburn  8985: =pod
                   8986: 
                   8987: =item *&assign_categories_table()
                   8988: 
                   8989: Create a datatable for display of hierarchical categories in a domain,
                   8990: with checkboxes to allow a course to be categorized. 
                   8991: 
                   8992: Inputs:
                   8993: 
                   8994: cathash - reference to hash of categories defined for the domain (from
                   8995:           configuration.db)
                   8996: 
                   8997: currcat - scalar with an & separated list of categories assigned to a course. 
                   8998: 
                   8999: Returns: $output (markup to be displayed) 
                   9000: 
                   9001: =cut
                   9002: 
                   9003: sub assign_categories_table {
                   9004:     my ($cathash,$currcat) = @_;
                   9005:     my $output;
                   9006:     if (ref($cathash) eq 'HASH') {
                   9007:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   9008:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   9009:         $maxdepth = scalar(@cats);
                   9010:         if (@cats > 0) {
                   9011:             my $itemcount = 0;
                   9012:             if (ref($cats[0]) eq 'ARRAY') {
                   9013:                 $output = &Apache::loncommon::start_data_table();
                   9014:                 my @currcategories;
                   9015:                 if ($currcat ne '') {
                   9016:                     @currcategories = split('&',$currcat);
                   9017:                 }
                   9018:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   9019:                     my $parent = $cats[0][$i];
                   9020:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   9021:                     next if ($parent eq 'instcode');
                   9022:                     my $item = &escape($parent).'::0';
                   9023:                     my $checked = '';
                   9024:                     if (@currcategories > 0) {
                   9025:                         if (grep(/^\Q$item\E$/,@currcategories)) {
                   9026:                             $checked = ' checked="checked" ';
                   9027:                         }
                   9028:                     }
1.675     raeburn  9029:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   9030:                                '<input type="checkbox" name="usecategory" value="'.
                   9031:                                $item.'"'.$checked.' />'.$parent.'</span>'.
                   9032:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  9033:                     my $depth = 1;
                   9034:                     push(@path,$parent);
                   9035:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
                   9036:                     pop(@path);
                   9037:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
                   9038:                     $itemcount ++;
                   9039:                 }
                   9040:                 $output .= &Apache::loncommon::end_data_table();
                   9041:             }
                   9042:         }
                   9043:     }
                   9044:     return $output;
                   9045: }
                   9046: 
                   9047: =pod
                   9048: 
                   9049: =item *&assign_category_rows()
                   9050: 
                   9051: Create a datatable row for display of nested categories in a domain,
                   9052: with checkboxes to allow a course to be categorized,called recursively.
                   9053: 
                   9054: Inputs:
                   9055: 
                   9056: itemcount - track row number for alternating colors
                   9057: 
                   9058: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   9059:       categories and subcategories.
                   9060: 
                   9061: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   9062: 
                   9063: parent - parent of current category item
                   9064: 
                   9065: path - Array containing all categories back up through the hierarchy from the
                   9066:        current category to the top level.
                   9067: 
                   9068: currcategories - reference to array of current categories assigned to the course
                   9069: 
                   9070: Returns: $output (markup to be displayed).
                   9071: 
                   9072: =cut
                   9073: 
                   9074: sub assign_category_rows {
                   9075:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   9076:     my ($text,$name,$item,$chgstr);
                   9077:     if (ref($cats) eq 'ARRAY') {
                   9078:         my $maxdepth = scalar(@{$cats});
                   9079:         if (ref($cats->[$depth]) eq 'HASH') {
                   9080:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   9081:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   9082:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   9083:                 $text .= '<td><table class="LC_datatable">';
                   9084:                 for (my $j=0; $j<$numchildren; $j++) {
                   9085:                     $name = $cats->[$depth]{$parent}[$j];
                   9086:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   9087:                     my $deeper = $depth+1;
                   9088:                     my $checked = '';
                   9089:                     if (ref($currcategories) eq 'ARRAY') {
                   9090:                         if (@{$currcategories} > 0) {
                   9091:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
                   9092:                                 $checked = ' checked="checked" ';
                   9093:                             }
                   9094:                         }
                   9095:                     }
1.664     raeburn  9096:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   9097:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  9098:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   9099:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   9100:                              '</td><td>';
1.663     raeburn  9101:                     if (ref($path) eq 'ARRAY') {
                   9102:                         push(@{$path},$name);
                   9103:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   9104:                         pop(@{$path});
                   9105:                     }
                   9106:                     $text .= '</td></tr>';
                   9107:                 }
                   9108:                 $text .= '</table></td>';
                   9109:             }
                   9110:         }
                   9111:     }
                   9112:     return $text;
                   9113: }
                   9114: 
1.655     raeburn  9115: ############################################################
                   9116: ############################################################
                   9117: 
                   9118: 
1.443     albertel 9119: sub commit_customrole {
1.664     raeburn  9120:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  9121:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 9122:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   9123:                          ($end?', ending '.localtime($end):'').': <b>'.
                   9124:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  9125:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 9126:                  '</b><br />';
                   9127:     return $output;
                   9128: }
                   9129: 
                   9130: sub commit_standardrole {
1.541     raeburn  9131:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   9132:     my ($output,$logmsg,$linefeed);
                   9133:     if ($context eq 'auto') {
                   9134:         $linefeed = "\n";
                   9135:     } else {
                   9136:         $linefeed = "<br />\n";
                   9137:     }  
1.443     albertel 9138:     if ($three eq 'st') {
1.541     raeburn  9139:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   9140:                                          $one,$two,$sec,$context);
                   9141:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  9142:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   9143:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 9144:         } else {
1.541     raeburn  9145:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 9146:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  9147:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   9148:             if ($context eq 'auto') {
                   9149:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   9150:             } else {
                   9151:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   9152:                &mt('Add to classlist').': <b>ok</b>';
                   9153:             }
                   9154:             $output .= $linefeed;
1.443     albertel 9155:         }
                   9156:     } else {
                   9157:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   9158:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  9159:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  9160:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  9161:         if ($context eq 'auto') {
                   9162:             $output .= $result.$linefeed;
                   9163:         } else {
                   9164:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   9165:         }
1.443     albertel 9166:     }
                   9167:     return $output;
                   9168: }
                   9169: 
                   9170: sub commit_studentrole {
1.541     raeburn  9171:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  9172:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  9173:     if ($context eq 'auto') {
                   9174:         $linefeed = "\n";
                   9175:     } else {
                   9176:         $linefeed = '<br />'."\n";
                   9177:     }
1.443     albertel 9178:     if (defined($one) && defined($two)) {
                   9179:         my $cid=$one.'_'.$two;
                   9180:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   9181:         my $secchange = 0;
                   9182:         my $expire_role_result;
                   9183:         my $modify_section_result;
1.628     raeburn  9184:         if ($oldsec ne '-1') { 
                   9185:             if ($oldsec ne $sec) {
1.443     albertel 9186:                 $secchange = 1;
1.628     raeburn  9187:                 my $now = time;
1.443     albertel 9188:                 my $uurl='/'.$cid;
                   9189:                 $uurl=~s/\_/\//g;
                   9190:                 if ($oldsec) {
                   9191:                     $uurl.='/'.$oldsec;
                   9192:                 }
1.626     raeburn  9193:                 $oldsecurl = $uurl;
1.628     raeburn  9194:                 $expire_role_result = 
1.652     raeburn  9195:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  9196:                 if ($env{'request.course.sec'} ne '') { 
                   9197:                     if ($expire_role_result eq 'refused') {
                   9198:                         my @roles = ('st');
                   9199:                         my @statuses = ('previous');
                   9200:                         my @roledoms = ($one);
                   9201:                         my $withsec = 1;
                   9202:                         my %roleshash = 
                   9203:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   9204:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   9205:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   9206:                             my ($oldstart,$oldend) = 
                   9207:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   9208:                             if ($oldend > 0 && $oldend <= $now) {
                   9209:                                 $expire_role_result = 'ok';
                   9210:                             }
                   9211:                         }
                   9212:                     }
                   9213:                 }
1.443     albertel 9214:                 $result = $expire_role_result;
                   9215:             }
                   9216:         }
                   9217:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  9218:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 9219:             if ($modify_section_result =~ /^ok/) {
                   9220:                 if ($secchange == 1) {
1.628     raeburn  9221:                     if ($sec eq '') {
                   9222:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   9223:                     } else {
                   9224:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   9225:                     }
1.443     albertel 9226:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  9227:                     if ($sec eq '') {
                   9228:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   9229:                     } else {
                   9230:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   9231:                     }
1.443     albertel 9232:                 } else {
1.628     raeburn  9233:                     if ($sec eq '') {
                   9234:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   9235:                     } else {
                   9236:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   9237:                     }
1.443     albertel 9238:                 }
                   9239:             } else {
1.628     raeburn  9240:                 if ($secchange) {       
                   9241:                     $$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;
                   9242:                 } else {
                   9243:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   9244:                 }
1.443     albertel 9245:             }
                   9246:             $result = $modify_section_result;
                   9247:         } elsif ($secchange == 1) {
1.628     raeburn  9248:             if ($oldsec eq '') {
                   9249:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
                   9250:             } else {
                   9251:                 $$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;
                   9252:             }
1.626     raeburn  9253:             if ($expire_role_result eq 'refused') {
                   9254:                 my $newsecurl = '/'.$cid;
                   9255:                 $newsecurl =~ s/\_/\//g;
                   9256:                 if ($sec ne '') {
                   9257:                     $newsecurl.='/'.$sec;
                   9258:                 }
                   9259:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   9260:                     if ($sec eq '') {
                   9261:                         $$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;
                   9262:                     } else {
                   9263:                         $$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;
                   9264:                     }
                   9265:                 }
                   9266:             }
1.443     albertel 9267:         }
                   9268:     } else {
1.626     raeburn  9269:         $$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 9270:         $result = "error: incomplete course id\n";
                   9271:     }
                   9272:     return $result;
                   9273: }
                   9274: 
                   9275: ############################################################
                   9276: ############################################################
                   9277: 
1.566     albertel 9278: sub check_clone {
1.578     raeburn  9279:     my ($args,$linefeed) = @_;
1.566     albertel 9280:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   9281:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   9282:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   9283:     my $clonemsg;
                   9284:     my $can_clone = 0;
                   9285: 
                   9286:     if ($clonehome eq 'no_host') {
1.578     raeburn  9287:         $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});     
1.566     albertel 9288:     } else {
                   9289: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.692.4.12  raeburn  9290:         if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   9291:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
                   9292:  	    $can_clone = 1;
1.566     albertel 9293: 	} else {
                   9294: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   9295: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   9296: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  9297:             if (grep(/^\*$/,@cloners)) {
                   9298:                 $can_clone = 1;
                   9299:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   9300:                 $can_clone = 1;
                   9301:             } else {
                   9302: 	        my %roleshash =
                   9303: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   9304: 					 $args->{'ccdomain'},
                   9305:                                          'userroles',['active'],['cc'],
                   9306: 					 [$args->{'clonedomain'}]);
                   9307: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
                   9308: 		    $can_clone = 1;
                   9309: 	        } else {
                   9310:                     $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   9311: 	        }
1.566     albertel 9312: 	    }
1.578     raeburn  9313:         }
1.566     albertel 9314:     }
                   9315:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   9316: }
                   9317: 
1.444     albertel 9318: sub construct_course {
1.692.4.14! raeburn  9319:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 9320:     my $outcome;
1.541     raeburn  9321:     my $linefeed =  '<br />'."\n";
                   9322:     if ($context eq 'auto') {
                   9323:         $linefeed = "\n";
                   9324:     }
1.566     albertel 9325: 
                   9326: #
                   9327: # Are we cloning?
                   9328: #
                   9329:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   9330:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  9331: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 9332: 	if ($context ne 'auto') {
1.578     raeburn  9333:             if ($clonemsg ne '') {
                   9334: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   9335:             }
1.566     albertel 9336: 	}
                   9337: 	$outcome .= $clonemsg.$linefeed;
                   9338: 
                   9339:         if (!$can_clone) {
                   9340: 	    return (0,$outcome);
                   9341: 	}
                   9342:     }
                   9343: 
1.444     albertel 9344: #
                   9345: # Open course
                   9346: #
                   9347:     my $crstype = lc($args->{'crstype'});
                   9348:     my %cenv=();
                   9349:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   9350:                                              $args->{'cdescr'},
                   9351:                                              $args->{'curl'},
                   9352:                                              $args->{'course_home'},
                   9353:                                              $args->{'nonstandard'},
                   9354:                                              $args->{'crscode'},
                   9355:                                              $args->{'ccuname'}.':'.
                   9356:                                              $args->{'ccdomain'},
1.692.4.12  raeburn  9357:                                              $args->{'crstype'},
1.692.4.14! raeburn  9358:                                              $cnum,$context,$category);
1.692.4.12  raeburn  9359: 
1.444     albertel 9360: 
                   9361:     # Note: The testing routines depend on this being output; see 
                   9362:     # Utils::Course. This needs to at least be output as a comment
                   9363:     # if anyone ever decides to not show this, and Utils::Course::new
                   9364:     # will need to be suitably modified.
1.541     raeburn  9365:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.444     albertel 9366: #
                   9367: # Check if created correctly
                   9368: #
1.479     albertel 9369:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 9370:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.541     raeburn  9371:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 9372: 
1.444     albertel 9373: #
1.566     albertel 9374: # Do the cloning
                   9375: #   
                   9376:     if ($can_clone && $cloneid) {
                   9377: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   9378: 	if ($context ne 'auto') {
                   9379: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   9380: 	}
                   9381: 	$outcome .= $clonemsg.$linefeed;
                   9382: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 9383: # Copy all files
1.637     www      9384: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 9385: # Restore URL
1.566     albertel 9386: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 9387: # Restore title
1.566     albertel 9388: 	$cenv{'description'}=$oldcenv{'description'};
1.444     albertel 9389: # Mark as cloned
1.566     albertel 9390: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      9391: # Need to clone grading mode
                   9392:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   9393:         $cenv{'grading'}=$newenv{'grading'};
                   9394: # Do not clone these environment entries
                   9395:         &Apache::lonnet::del('environment',
                   9396:                   ['default_enrollment_start_date',
                   9397:                    'default_enrollment_end_date',
                   9398:                    'question.email',
                   9399:                    'policy.email',
                   9400:                    'comment.email',
                   9401:                    'pch.users.denied',
1.692.4.2  raeburn  9402:                    'plc.users.denied',
                   9403:                    'hidefromcat',
                   9404:                    'categories'],
1.638     www      9405:                    $$crsudom,$$crsunum);
1.444     albertel 9406:     }
1.566     albertel 9407: 
1.444     albertel 9408: #
                   9409: # Set environment (will override cloned, if existing)
                   9410: #
                   9411:     my @sections = ();
                   9412:     my @xlists = ();
                   9413:     if ($args->{'crstype'}) {
                   9414:         $cenv{'type'}=$args->{'crstype'};
                   9415:     }
                   9416:     if ($args->{'crsid'}) {
                   9417:         $cenv{'courseid'}=$args->{'crsid'};
                   9418:     }
                   9419:     if ($args->{'crscode'}) {
                   9420:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   9421:     }
                   9422:     if ($args->{'crsquota'} ne '') {
                   9423:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   9424:     } else {
                   9425:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   9426:     }
                   9427:     if ($args->{'ccuname'}) {
                   9428:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   9429:                                         ':'.$args->{'ccdomain'};
                   9430:     } else {
                   9431:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   9432:     }
                   9433:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   9434:     if ($args->{'crssections'}) {
                   9435:         $cenv{'internal.sectionnums'} = '';
                   9436:         if ($args->{'crssections'} =~ m/,/) {
                   9437:             @sections = split/,/,$args->{'crssections'};
                   9438:         } else {
                   9439:             $sections[0] = $args->{'crssections'};
                   9440:         }
                   9441:         if (@sections > 0) {
                   9442:             foreach my $item (@sections) {
                   9443:                 my ($sec,$gp) = split/:/,$item;
                   9444:                 my $class = $args->{'crscode'}.$sec;
                   9445:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   9446:                 $cenv{'internal.sectionnums'} .= $item.',';
                   9447:                 unless ($addcheck eq 'ok') {
                   9448:                     push @badclasses, $class;
                   9449:                 }
                   9450:             }
                   9451:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   9452:         }
                   9453:     }
                   9454: # do not hide course coordinator from staff listing, 
                   9455: # even if privileged
                   9456:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9457: # add crosslistings
                   9458:     if ($args->{'crsxlist'}) {
                   9459:         $cenv{'internal.crosslistings'}='';
                   9460:         if ($args->{'crsxlist'} =~ m/,/) {
                   9461:             @xlists = split/,/,$args->{'crsxlist'};
                   9462:         } else {
                   9463:             $xlists[0] = $args->{'crsxlist'};
                   9464:         }
                   9465:         if (@xlists > 0) {
                   9466:             foreach my $item (@xlists) {
                   9467:                 my ($xl,$gp) = split/:/,$item;
                   9468:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   9469:                 $cenv{'internal.crosslistings'} .= $item.',';
                   9470:                 unless ($addcheck eq 'ok') {
                   9471:                     push @badclasses, $xl;
                   9472:                 }
                   9473:             }
                   9474:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   9475:         }
                   9476:     }
                   9477:     if ($args->{'autoadds'}) {
                   9478:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   9479:     }
                   9480:     if ($args->{'autodrops'}) {
                   9481:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   9482:     }
                   9483: # check for notification of enrollment changes
                   9484:     my @notified = ();
                   9485:     if ($args->{'notify_owner'}) {
                   9486:         if ($args->{'ccuname'} ne '') {
                   9487:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   9488:         }
                   9489:     }
                   9490:     if ($args->{'notify_dc'}) {
                   9491:         if ($uname ne '') { 
1.630     raeburn  9492:             push(@notified,$uname.':'.$udom);
1.444     albertel 9493:         }
                   9494:     }
                   9495:     if (@notified > 0) {
                   9496:         my $notifylist;
                   9497:         if (@notified > 1) {
                   9498:             $notifylist = join(',',@notified);
                   9499:         } else {
                   9500:             $notifylist = $notified[0];
                   9501:         }
                   9502:         $cenv{'internal.notifylist'} = $notifylist;
                   9503:     }
                   9504:     if (@badclasses > 0) {
                   9505:         my %lt=&Apache::lonlocal::texthash(
                   9506:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   9507:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   9508:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   9509:         );
1.541     raeburn  9510:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   9511:                            ' ('.$lt{'adby'}.')';
                   9512:         if ($context eq 'auto') {
                   9513:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 9514:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  9515:             foreach my $item (@badclasses) {
                   9516:                 if ($context eq 'auto') {
                   9517:                     $outcome .= " - $item\n";
                   9518:                 } else {
                   9519:                     $outcome .= "<li>$item</li>\n";
                   9520:                 }
                   9521:             }
                   9522:             if ($context eq 'auto') {
                   9523:                 $outcome .= $linefeed;
                   9524:             } else {
1.566     albertel 9525:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  9526:             }
                   9527:         } 
1.444     albertel 9528:     }
                   9529:     if ($args->{'no_end_date'}) {
                   9530:         $args->{'endaccess'} = 0;
                   9531:     }
                   9532:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   9533:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   9534:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   9535:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   9536:     if ($args->{'showphotos'}) {
                   9537:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   9538:     }
                   9539:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   9540:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   9541:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   9542:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  9543:             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'); 
                   9544:             if ($context eq 'auto') {
                   9545:                 $outcome .= $krb_msg;
                   9546:             } else {
1.566     albertel 9547:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  9548:             }
                   9549:             $outcome .= $linefeed;
1.444     albertel 9550:         }
                   9551:     }
                   9552:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   9553:        if ($args->{'setpolicy'}) {
                   9554:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9555:        }
                   9556:        if ($args->{'setcontent'}) {
                   9557:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   9558:        }
                   9559:     }
                   9560:     if ($args->{'reshome'}) {
                   9561: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   9562: 	$cenv{'reshome'}=~s/\/+$/\//;
                   9563:     }
                   9564: #
                   9565: # course has keyed access
                   9566: #
                   9567:     if ($args->{'setkeys'}) {
                   9568:        $cenv{'keyaccess'}='yes';
                   9569:     }
                   9570: # if specified, key authority is not course, but user
                   9571: # only active if keyaccess is yes
                   9572:     if ($args->{'keyauth'}) {
1.487     albertel 9573: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   9574: 	$user = &LONCAPA::clean_username($user);
                   9575: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     9576: 	if ($user ne '' && $domain ne '') {
1.487     albertel 9577: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 9578: 	}
                   9579:     }
                   9580: 
                   9581:     if ($args->{'disresdis'}) {
                   9582:         $cenv{'pch.roles.denied'}='st';
                   9583:     }
                   9584:     if ($args->{'disablechat'}) {
                   9585:         $cenv{'plc.roles.denied'}='st';
                   9586:     }
                   9587: 
                   9588:     # Record we've not yet viewed the Course Initialization Helper for this 
                   9589:     # course
                   9590:     $cenv{'course.helper.not.run'} = 1;
                   9591:     #
                   9592:     # Use new Randomseed
                   9593:     #
                   9594:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   9595:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   9596:     #
                   9597:     # The encryption code and receipt prefix for this course
                   9598:     #
                   9599:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   9600:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   9601:     #
                   9602:     # By default, use standard grading
                   9603:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   9604: 
1.541     raeburn  9605:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   9606:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9607: #
                   9608: # Open all assignments
                   9609: #
                   9610:     if ($args->{'openall'}) {
                   9611:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   9612:        my %storecontent = ($storeunder         => time,
                   9613:                            $storeunder.'.type' => 'date_start');
                   9614:        
                   9615:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  9616:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 9617:    }
                   9618: #
                   9619: # Set first page
                   9620: #
                   9621:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   9622: 	    || ($cloneid)) {
1.445     albertel 9623: 	use LONCAPA::map;
1.444     albertel 9624: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 9625: 
                   9626: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   9627:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   9628: 
1.444     albertel 9629:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   9630:         my $title; my $url;
                   9631:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   9632: 	    $title=&mt('Syllabus');
1.444     albertel 9633:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   9634:         } else {
1.690     bisitz   9635:             $title=&mt('Navigate Contents');
1.444     albertel 9636:             $url='/adm/navmaps';
                   9637:         }
1.445     albertel 9638: 
                   9639:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   9640: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   9641: 
                   9642: 	if ($errtext) { $fatal=2; }
1.541     raeburn  9643:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 9644:     }
1.566     albertel 9645: 
                   9646:     return (1,$outcome);
1.444     albertel 9647: }
                   9648: 
                   9649: ############################################################
                   9650: ############################################################
                   9651: 
1.378     raeburn  9652: sub course_type {
                   9653:     my ($cid) = @_;
                   9654:     if (!defined($cid)) {
                   9655:         $cid = $env{'request.course.id'};
                   9656:     }
1.404     albertel 9657:     if (defined($env{'course.'.$cid.'.type'})) {
                   9658:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  9659:     } else {
                   9660:         return 'Course';
1.377     raeburn  9661:     }
                   9662: }
1.156     albertel 9663: 
1.406     raeburn  9664: sub group_term {
                   9665:     my $crstype = &course_type();
                   9666:     my %names = (
1.692.4.6  raeburn  9667:                   'Course'    => 'group',
                   9668:                   'Community' => 'group',
1.406     raeburn  9669:                 );
                   9670:     return $names{$crstype};
                   9671: }
                   9672: 
1.156     albertel 9673: sub icon {
                   9674:     my ($file)=@_;
1.505     albertel 9675:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 9676:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 9677:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 9678:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   9679: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   9680: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9681: 	            $curfext.".gif") {
                   9682: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   9683: 		$curfext.".gif";
                   9684: 	}
                   9685:     }
1.249     albertel 9686:     return &lonhttpdurl($iconname);
1.154     albertel 9687: } 
1.84      albertel 9688: 
1.575     albertel 9689: sub lonhttpdurl {
1.692     www      9690: #
                   9691: # Had been used for "small fry" static images on separate port 8080.
                   9692: # Modify here if lightweight http functionality desired again.
                   9693: # Currently eliminated due to increasing firewall issues.
                   9694: #
1.575     albertel 9695:     my ($url)=@_;
1.692     www      9696:     return $url;
1.215     albertel 9697: }
                   9698: 
1.213     albertel 9699: sub connection_aborted {
                   9700:     my ($r)=@_;
                   9701:     $r->print(" ");$r->rflush();
                   9702:     my $c = $r->connection;
                   9703:     return $c->aborted();
                   9704: }
                   9705: 
1.221     foxr     9706: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     9707: #    strings as 'strings'.
                   9708: sub escape_single {
1.221     foxr     9709:     my ($input) = @_;
1.223     albertel 9710:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     9711:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   9712:     return $input;
                   9713: }
1.223     albertel 9714: 
1.222     foxr     9715: #  Same as escape_single, but escape's "'s  This 
                   9716: #  can be used for  "strings"
                   9717: sub escape_double {
                   9718:     my ($input) = @_;
                   9719:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   9720:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   9721:     return $input;
                   9722: }
1.223     albertel 9723:  
1.222     foxr     9724: #   Escapes the last element of a full URL.
                   9725: sub escape_url {
                   9726:     my ($url)   = @_;
1.238     raeburn  9727:     my @urlslices = split(/\//, $url,-1);
1.369     www      9728:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 9729:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     9730: }
1.462     albertel 9731: 
1.692.4.2  raeburn  9732: sub compare_arrays {
                   9733:     my ($arrayref1,$arrayref2) = @_;
                   9734:     my (@difference,%count);
                   9735:     @difference = ();
                   9736:     %count = ();
                   9737:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   9738:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   9739:         foreach my $element (keys(%count)) {
                   9740:             if ($count{$element} == 1) {
                   9741:                 push(@difference,$element);
                   9742:             }
                   9743:         }
                   9744:     }
                   9745:     return @difference;
                   9746: }
                   9747: 
1.462     albertel 9748: # -------------------------------------------------------- Initliaze user login
                   9749: sub init_user_environment {
1.463     albertel 9750:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 9751:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   9752: 
                   9753:     my $public=($username eq 'public' && $domain eq 'public');
                   9754: 
                   9755: # See if old ID present, if so, remove
                   9756: 
                   9757:     my ($filename,$cookie,$userroles);
                   9758:     my $now=time;
                   9759: 
                   9760:     if ($public) {
                   9761: 	my $max_public=100;
                   9762: 	my $oldest;
                   9763: 	my $oldest_time=0;
                   9764: 	for(my $next=1;$next<=$max_public;$next++) {
                   9765: 	    if (-e $lonids."/publicuser_$next.id") {
                   9766: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   9767: 		if ($mtime<$oldest_time || !$oldest_time) {
                   9768: 		    $oldest_time=$mtime;
                   9769: 		    $oldest=$next;
                   9770: 		}
                   9771: 	    } else {
                   9772: 		$cookie="publicuser_$next";
                   9773: 		last;
                   9774: 	    }
                   9775: 	}
                   9776: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   9777:     } else {
1.463     albertel 9778: 	# if this isn't a robot, kill any existing non-robot sessions
                   9779: 	if (!$args->{'robot'}) {
                   9780: 	    opendir(DIR,$lonids);
                   9781: 	    while ($filename=readdir(DIR)) {
                   9782: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   9783: 		    unlink($lonids.'/'.$filename);
                   9784: 		}
1.462     albertel 9785: 	    }
1.463     albertel 9786: 	    closedir(DIR);
1.462     albertel 9787: 	}
                   9788: # Give them a new cookie
1.463     albertel 9789: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      9790: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 9791: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 9792:     
                   9793: # Initialize roles
                   9794: 
                   9795: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
                   9796:     }
                   9797: # ------------------------------------ Check browser type and MathML capability
                   9798: 
                   9799:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   9800:         $clientunicode,$clientos) = &decode_user_agent($r);
                   9801: 
                   9802: # -------------------------------------- Any accessibility options to remember?
                   9803:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
                   9804: 	foreach my $option ('imagesuppress','appletsuppress',
                   9805: 			    'embedsuppress','fontenhance','blackwhite') {
                   9806: 	    if ($form->{$option} eq 'true') {
                   9807: 		&Apache::lonnet::put('environment',{$option => 'on'},
                   9808: 				     $domain,$username);
                   9809: 	    } else {
                   9810: 		&Apache::lonnet::del('environment',[$option],
                   9811: 				     $domain,$username);
                   9812: 	    }
                   9813: 	}
                   9814:     }
                   9815: # ------------------------------------------------------------- Get environment
                   9816: 
                   9817:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   9818:     my ($tmp) = keys(%userenv);
                   9819:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9820: 	# default remote control to off
                   9821: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
                   9822:     } else {
                   9823: 	undef(%userenv);
                   9824:     }
                   9825:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   9826: 	$form->{'interface'}=$userenv{'interface'};
                   9827:     }
                   9828:     $env{'environment.remote'}=$userenv{'remote'};
                   9829:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   9830: 
                   9831: # --------------- Do not trust query string to be put directly into environment
                   9832:     foreach my $option ('imagesuppress','appletsuppress',
                   9833: 			'embedsuppress','fontenhance','blackwhite',
                   9834: 			'interface','localpath','localres') {
                   9835: 	$form->{$option}=~s/[\n\r\=]//gs;
                   9836:     }
                   9837: # --------------------------------------------------------- Write first profile
                   9838: 
                   9839:     {
                   9840: 	my %initial_env = 
                   9841: 	    ("user.name"          => $username,
                   9842: 	     "user.domain"        => $domain,
                   9843: 	     "user.home"          => $authhost,
                   9844: 	     "browser.type"       => $clientbrowser,
                   9845: 	     "browser.version"    => $clientversion,
                   9846: 	     "browser.mathml"     => $clientmathml,
                   9847: 	     "browser.unicode"    => $clientunicode,
                   9848: 	     "browser.os"         => $clientos,
                   9849: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   9850: 	     "request.course.fn"  => '',
                   9851: 	     "request.course.uri" => '',
                   9852: 	     "request.course.sec" => '',
                   9853: 	     "request.role"       => 'cm',
                   9854: 	     "request.role.adv"   => $env{'user.adv'},
                   9855: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   9856: 
                   9857:         if ($form->{'localpath'}) {
                   9858: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   9859: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   9860:         }
                   9861: 	
                   9862: 	if ($public) {
                   9863: 	    $initial_env{"environment.remote"} = "off";
                   9864: 	}
                   9865: 	if ($form->{'interface'}) {
                   9866: 	    $form->{'interface'}=~s/\W//gs;
                   9867: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   9868: 	    $env{'browser.interface'}=$form->{'interface'};
                   9869: 	    foreach my $option ('imagesuppress','appletsuppress',
                   9870: 				'embedsuppress','fontenhance','blackwhite') {
                   9871: 		if (($form->{$option} eq 'true') ||
                   9872: 		    ($userenv{$option} eq 'on')) {
                   9873: 		    $initial_env{"browser.$option"} = "on";
                   9874: 		}
                   9875: 	    }
                   9876: 	}
                   9877: 
1.692.4.2  raeburn  9878:         foreach my $tool ('aboutme','blog','portfolio') {
                   9879:             $userenv{'availabletools.'.$tool} =
                   9880:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
                   9881:         }
                   9882: 
1.692.4.6  raeburn  9883:         foreach my $crstype ('official','unofficial','community') {
1.692.4.2  raeburn  9884:             $userenv{'canrequest.'.$crstype} =
                   9885:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   9886:                                                   'reload','requestcourses');
                   9887:         }
                   9888: 
1.462     albertel 9889: 	$env{'user.environment'} = "$lonids/$cookie.id";
                   9890: 	
                   9891: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   9892: 		 &GDBM_WRCREAT(),0640)) {
                   9893: 	    &_add_to_env(\%disk_env,\%initial_env);
                   9894: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   9895: 	    &_add_to_env(\%disk_env,$userroles);
1.463     albertel 9896: 	    if (ref($args->{'extra_env'})) {
                   9897: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   9898: 	    }
1.462     albertel 9899: 	    untie(%disk_env);
                   9900: 	} else {
                   9901: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
                   9902: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
                   9903: 	    return 'error: '.$!;
                   9904: 	}
                   9905:     }
                   9906:     $env{'request.role'}='cm';
                   9907:     $env{'request.role.adv'}=$env{'user.adv'};
                   9908:     $env{'browser.type'}=$clientbrowser;
                   9909: 
                   9910:     return $cookie;
                   9911: 
                   9912: }
                   9913: 
                   9914: sub _add_to_env {
                   9915:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  9916:     if (ref($env_data) eq 'HASH') {
                   9917:         while (my ($key,$value) = each(%$env_data)) {
                   9918: 	    $idf->{$prefix.$key} = $value;
                   9919: 	    $env{$prefix.$key}   = $value;
                   9920:         }
1.462     albertel 9921:     }
                   9922: }
                   9923: 
1.685     tempelho 9924: # --- Get the symbolic name of a problem and the url
                   9925: sub get_symb {
                   9926:     my ($request,$silent) = @_;
1.692.4.2  raeburn  9927:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 9928:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   9929:     if ($symb eq '') {
                   9930:         if (!$silent) {
                   9931:             $request->print("Unable to handle ambiguous references:$url:.");
                   9932:             return ();
                   9933:         }
                   9934:     }
                   9935:     &Apache::lonenc::check_decrypt(\$symb);
                   9936:     return ($symb);
                   9937: }
                   9938: 
                   9939: # --------------------------------------------------------------Get annotation
                   9940: 
                   9941: sub get_annotation {
                   9942:     my ($symb,$enc) = @_;
                   9943: 
                   9944:     my $key = $symb;
                   9945:     if (!$enc) {
                   9946:         $key =
                   9947:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   9948:     }
                   9949:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   9950:     return $annotation{$key};
                   9951: }
                   9952: 
                   9953: sub clean_symb {
1.692.4.2  raeburn  9954:     my ($symb,$delete_enc) = @_;
1.685     tempelho 9955: 
                   9956:     &Apache::lonenc::check_decrypt(\$symb);
                   9957:     my $enc = $env{'request.enc'};
1.692.4.2  raeburn  9958:     if ($delete_enc) {
                   9959:         delete($env{'request.enc'});
                   9960:     }
1.685     tempelho 9961: 
                   9962:     return ($symb,$enc);
                   9963: }
1.462     albertel 9964: 
1.41      ng       9965: =pod
                   9966: 
                   9967: =back
                   9968: 
1.112     bowersj2 9969: =cut
1.41      ng       9970: 
1.112     bowersj2 9971: 1;
                   9972: __END__;
1.41      ng       9973: 

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