Apache::loncommon - pile of common routines
Common routines for manipulating connections, student answers, domains, common Javascript fragments, etc.
A collection of commonly used subroutines that don't have a natural home anywhere else. This collection helps remove redundancy from other modules and increase efficiency of memory usage.
Performs an ssi with some number of retries. Retries continue either until the result is ok or until the retry count supplied by the caller is exhausted.
Inputs:
resource - Identifies the resource to insert.
retries - Count of the number of retries allowed.
form - Hash that identifies the rendering options.
Returns:
content - The content of the response. If retries were exhausted this is empty.
response - The response from the last attempt (which may or may not have been successful.
Returns a string
containing javascript with two functions, openbrowser
and
opensearcher
. Returned string does not contain <script>
tags.
inputs: formname, elementname, only, omit
formname and elementname indicate the name of the html form and name of the element that the results of the browsing selection are to be placed in.
Specifying 'only' will restrict the browser to displaying only files with the given extension. Can be a comma separated list.
Specifying 'omit' will restrict the browser to NOT displaying files with the given extension. Can be a comma separated list.
Inputs: formname, elementname
formname and elementname specify the name of the html form and the name of the element the selection from the search results will be placed in.
linked_select_forms returns a string containing a <script></script> block and html for two <select> menus. The select menus will be linked in that changing the value of the first menu will result in new values being placed in the second menu. The values in the select menu will appear in alphabetical order unless a defined order is provided.
linked_select_forms takes the following ordered inputs:
Below is an example of such a hash. Only the 'text', 'default', and
'select2' keys must appear as stated. keys(%menu)
are the possible
values for the first select menu. The text that coincides with the
first menu value is given in $menu{$choice1}->{'text'}. The values
and text for the second menu are given in the hash pointed to by
$menu{$choice1}->{'select2'}.
my %menu = ( A1 => { text =>"Choice A1" , default => "B3", select2 => { B1 => "Choice B1", B2 => "Choice B2", B3 => "Choice B3", B4 => "Choice B4" }, order => ['B4','B3','B1','B2'], }, A2 => { text =>"Choice A2" , default => "C2", select2 => { C1 => "Choice C1", C2 => "Choice C2", C3 => "Choice C3" }, order => ['C2','C1','C3'], }, A3 => { text =>"Choice A3" , default => "D6", select2 => { D1 => "Choice D1", D2 => "Choice D2", D3 => "Choice D3", D4 => "Choice D4", D5 => "Choice D5", D6 => "Choice D6", D7 => "Choice D7" }, order => ['D4','D3','D2','D1','D7','D6','D5'], } );
Returns a string corresponding to an HTML link to the given help $topic, where $topic corresponds to the name of a .tex file in /home/httpd/html/adm/help/tex, with underscores replaced by spaces.
$text will optionally be linked to the same topic, allowing you to link text in addition to the graphic. If you do not want to link text, but wish to specify one of the later parameters, pass an empty string.
$stayOnPage is a value that will be interpreted as a boolean. If true, the link will not open a new window. If false, the link will open a new window using Javascript. (Default is false.)
$width and $height are optional numerical parameters that will override the width and height of the popped up window, which may be useful for certain help topics with big pictures included.
This and the next function allow you to create small sections of an otherwise static HTML page that you can update on the fly with Javascript, even in Netscape 4.
The Javascript fragment returned by this function (no <script> tag)
must be written to the HTML page once. It will prove the Javascript
function ``change(name, content)''. Calling the change function with the
name of the section
you want to update, matching the name passed to changable_area
, and
the new content you want to put in there, will put the content into
that area.
Note: Netscape 4 only reserves enough space for the changable area to contain room for the original contents. You need to ``make space'' for whatever changes you wish to make, and be sure to check your code in Netscape 4. This feature in Netscape 4 is not powerful; it's adequate for updating a one-line status display, but little more. This script will set the space to 100% width, so you only need to worry about height in Netscape 4.
Modern browsers are much less limiting, and if you can commit to the user not using Netscape 4, this feature may be used freely with pretty much any HTML.
This provides a ``changable area'' that can be modified on the fly via
the Javascript code provided in change_content_javascript
. $name is
the name you will use to reference the area later; do not repeat the
same name on a given HTML page more then once. $origContent is what
the area will originally contain, which can be left blank.
Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
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.
emits the needed javascript to resize a textarea to be as big as possible
creates a function resize_textrea that takes two IDs first should be the id of the element to resize, second should be the id of a div that surrounds everything that comes after the textarea, this routine needs to be attached to the <body> for the onload and onresize events.
Translate $text to allow it to be output as a 'comma separated values' format.
Define some commonly used Excel cell formats.
Currently supported formats:
Inputs: $workbook
Returns: $format, a hash reference.
Create an Excel worksheet. If it fails, output message on the request object and return undefs.
Inputs: Apache request object
Returns (undef) on failure, Excel worksheet object, scalar with filename, and formats from &Apache::loncommon::define_excel_formats on success
Create a file to write to and eventually make available to the user. If file creation fails, outputs an error message on the request object and return undefs.
Inputs: Apache request object, and file suffix
Returns (undef) on failure, Filehandle and filename on success.
Returns a string containing a <select> element int multiple mode
Args: $name - name of the <select> element $value - scalar or array ref of values that should already be selected $size - number of rows long the select element is $hash - the elements should be 'option' => 'shown text' (shown text should already have been &mt()) $order - (optional) array ref of the order to show the elements in
Returns a string containing a <select name='$name' size='1'> form to allow a user to select options from a ref to a hash containing: option_name => displayed text. An optional $onchange can include a javascript onchange item, e.g., onchange=``this.form.submit();''
See lonrights.pm for an example invocation and use.
Returns a string containing a <select name='$name' size='1'> form to allow a user to select the domain to preform an operation in. See loncreateuser.pm for an example invocation and use.
If the $includeempty flag is set, it also includes an empty choice (``no domain selected'');
If the $showdomdesc flag is set, the domain name is followed by the domain description.
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.
The optional $incdoms is a reference to an array of domains which will be the only available options.
input: 4 arguments (two required, two optional) - $domain - domain of new user $name - name of form element $default - Value of 'default' causes a default item to be first option, and selected by default. $hide - Value of 'hide' causes hiding of the name of the server, if 1 server found, or default, if 0 found. output: returns 2 items: (a) form element which contains either: (i) <select name=``$name''> <option value=``$hostid1''>$hostid $servers{$hostid}</option> <option value=``$hostid2''>$hostid $servers{$hostid}</option> </select> form item if there are multiple library servers in $domain, or (ii) an <input type=``hidden'' name=``$name'' value=``$hostid'' /> form item if there is only one library server in $domain.
(b) number of library servers found.
See loncreateuser.pm for example of use.
Inputs: $r
Outputs:
The authform_xxxxxx subroutines provide javascript and html forms which handle some of the conveniences required for authentication forms. This is not an optimal method, but it works.
See loncreateuser.pm for invocation and use examples.
get_kerberos_defaults($target_domain)
returns the default kerberos
version and domain. If not found, it defaults to version 4 and the
domain of the server.
($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
Initializes the package variable %Keywords if it is empty. Uses the package variable $thesaurus_db_file.
Returns true if $word is a keyword. A keyword is a word that appears more than the average number of times in the thesaurus database. Calls &initialize_keywords
Look up a word in the thesaurus. Takes a scalar argument and returns an array of words. If the keyword is not in the thesaurus, an empty array will be returned. The order of the words returned is determined by the database which holds them.
Uses global $thesaurus_db_file.
Takes a users logon name and returns it as a string in ``first middle last generation'' form if $first is set to 'lastname' then it returns it as 'lastname generation, firstname middlename' if their is a lastname
Gets a users name and returns it as a string as
``"nickname"''
if the user has a nickname or
``first middle last generation''
if the user does not
Gets a user's email information and returns it as a hash with keys: notification, critnotification, permanentemail
For notification and critnotification, values are comma-separated lists of e-mail addresses; for permanentemail, value is a single e-mail address.
Gets a user's language preference and returns it as a hash with key: language.
Gets a users screenname and returns it as a string
Wrap messages about completion of operation in box
returns list of all language ids
returns description of a specified language id
returns list of all copyrights
returns description of a specified copyright id
returns list of all source copyrights
returns description of a specified source copyright id
returns list of all file categories
returns list of file types belonging to a given file category
returns embedding style for a specified file type
returns description for a specified file type
returns description for a specified file type with extra formatting
Return string with previous attempt on problem. Arguments:
The output string is a table containing all desired attempts, if any.
show a snapshot of what student was looking at
show a snapshot of how student was answering problem
Inputs: $text $uname $udom $symb $target
Returns: A link to grades.pm such as to see the SUBM view of a student
Inputs: $text $uname $udom $symb $target
Returns: A link to grades.pm such as to see the PGRD view of a student
Inputs: $text $uname $udom $symb $target
Returns: A link to parmset.pm such as to see the PPRM view of a student and a specific resource
Inputs: $domain (usually will be undef)
Returns: Determines which domain should be used for designs
Inputs: $domain (usually will be undef)
Returns: A link to a domain logo, if the domain logo exists. If the domain logo does not exist, a description of the domain.
Inputs: $which parameter; $domain (usually will be undef)
Returns: value of designparamter $which
Inputs: ./.
Returns: Path to the Construction Space of the current user's accessed author space The author space will be that of the current user when accessing the own author space and that of the co-author/assistent co-author when accessing the co-author's/assistent co-author's space
Inputs: $content (contains HTML code with page functions, etc.)
Returns: HTML div with $content To be included in page header
Input: (optional) filename from which breadcrumb trail is built. In most cases no input is needed, as $env{'request.filename'} is appropriate for use in building the breadcrumb trail.
Returns: HTML div with CSTR path and recent box To be included on Construction Space pages
Returns a uniform header for LON-CAPA web pages.
Inputs:
Returns: A uniform header for LON-CAPA web pages. If $bodyonly is nonzero, a string containing a <body> tag will be returned. If $bodyonly is undef or zero, an html string containing a <body> tag and other decorations will be returned.
Returns a uniform footer for LON-CAPA web pages.
Inputs: 1 - optional reference to an args hash If in the hash, key for noredirectlink has a value which evaluates to true, a 'Continue' link is not displayed if the page contains an internal redirect in the <head></head> section, i.e., $env{'internal.head.redirect'} exists
Returns a style sheet
Inputs: (all optional) domain -> force to color decorate a page for a specific domain function -> force usage of a specific rolish color scheme bgcolor -> override the default page bgcolor
Returns a uniform footer for LON-CAPA web pages.
Inputs: $title - optional title for the head $head_extra - optional extra HTML to put inside the <head> $args - optional arguments force_register - if is true call registerurl so the remote is informed redirect -> array ref of 1- seconds before redirect occurs 2- url to redirect to 3- whether the side effect should occur (side effect of setting $env{'internal.head.redirect'} to the url redirected too) domain -> force to color decorate a page for a specific domain function -> force usage of a specific rolish color scheme bgcolor -> override the default page bgcolor no_auto_mt_title -> prevent &mt()ing the title arg
Returns neccessary <meta> to set the proper encoding
Inputs: none
Returns the needed doctype and <html>
Inputs: none
Returns a uniform </head> for LON-CAPA web pages.
Inputs: none
Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
Inputs:
$title - optional title for the page
$head_extra - optional extra HTML to put inside the <head>
Returns a complete <html> .. <body> section for LON-CAPA web pages.
Inputs:
$title - optional title for the page
$head_extra - optional extra HTML to incude inside the <head>
$args - additional optional args supported are:
only_body -> is true will set &bodytag() onlybodytag arg on no_nav_bar -> is true will set &bodytag() no_nav_bar arg on add_entries -> additional attributes to add to the <body> domain -> force to color decorate a page for a specific domain function -> force usage of a specific rolish color scheme redirect -> see &headtag() bgcolor -> override the default page bg color js_ready -> return a string ready for being used in a javascript writeln html_encode -> return a string ready for being used in a html attribute force_register -> if is true will turn on the &bodytag() $forcereg arg frameset -> if true will start with a <frameset> rather than <body> skip_phases -> hash ref of head -> skip the <html><head> generation body -> skip all <body> generation no_inline_link -> if true and in remote mode, don't show the 'Switch To Inline Menu' link no_auto_mt_title -> prevent &mt()ing the title arg inherit_jsmath -> when creating popup window in a page, should it have jsmath forced on by the current page bread_crumbs -> Array containing breadcrumbs bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
Returns a complete </body></html> section for LON-CAPA web pages.
Inputs: $args - additional optional args supported are: js_ready -> return a string ready for being used in a javascript writeln html_encode -> return a string ready for being used in a html attribute frameset -> if true will start with a <frameset> rather than <body> dicsussion -> if true will get discussion from lonxml::xmlend (you can pass the target and parser arguments through optional 'target' and 'parser' args to this routine)
Checks for a inhibitmenu state and generates output to preserve it
Inputs: $arg - can be any of - undef - in which case the return value is a string to add into arguments list of a uri - 'input' - in which case the return value is a HTML <form> <input> field of type hidden to preserve the value - a url - in which case the return value is the url with the neccesary cgi args added to preserve the inhibitmenu state - a ref to a url - no return value, but the string is updated to include the neccessary cgi args to preserve the inhibitmenu state
Used by &bodytag to determine the current users primary role. Returns either 'student','coordinator','admin', or 'author'.
Used by lonmenu.pm and lonroles.pm to determine whether to use the word 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
Inputs: None
Outputs: Scalar: 1 if 'Course' to be used, 0 otherwise.
Determines current status of supplied role for a specific user. Roles can be active, previous or future.
Inputs: user's domain, user's username, course's domain, course's number, optional section ID.
Outputs: role status: active, previous or future.
Determines all the sections for a course including sections with students and sections containing other roles. Incoming parameters:
1. domain 2. course number 3. reference to array containing roles for which sections should be gathered (optional). 4. reference to array containing status types for which sections should be gathered (optional).
If the third argument is undefined, sections are gathered for any role. If the fourth argument is undefined, sections are gathered for any status. Permissible values are 'active' or 'future' or 'previous'.
Returns section hash (keys are section IDs, values are number of users in each section), subject to the optional roles filter, optional status filter
Retrieves usernames:domains for users in the specified course with specific role(s), and access status.
Incoming parameters: 1. course domain 2. course number 3. access status: users must have - either active, previous, future, or all. 4. reference to array of permissible roles 5. reference to array of section restrictions (optional) 6. reference to results object (hash of hashes). 7. reference to optional userdata hash 8. reference to optional statushash 9. flag if privileged users (except those set to unhide in course settings) should be excluded Keys of top level results hash are roles. Keys of inner hashes are username:domain, with values set to access type. Optional userdata hash returns an array with arguments in the same order as loncoursedata::get_classlist() for student data.
Optional statushash returns
Entries for end, start, section and status are blank because of the possibility of multiple values for non-student roles.
Retrieves quota assigned for storage of portfolio files for a user
Incoming parameters: 1. user's username 2. user's domain
Returns: 1. Disk quota (in Mb) assigned to student. 2. (Optional) Type of setting: custom or default (individually assigned or default for user's institutional status). 3. (Optional) - User's institutional status (e.g., faculty, staff or student - types as defined in localenroll::inst_usertypes for user's domain, which determines default quota for user. 4. (Optional) - Default quota which would apply to the user.
If a value has been stored in the user's environment,
it will return that, otherwise it returns the maximal default
defined for the user's instituional status(es)
in the domain.
Retrieves default quota assigned for storage of user portfolio files, given an (optional) user's institutional status.
Incoming parameters: 1. domain 2. (Optional) institutional status(es). This is a : separated list of status types (e.g., faculty, staff, student etc.) which apply to the user for whom the default is being retrieved. If the institutional status string in undefined, the domain default quota will be returned.
Returns: 1. Default disk quota (in Mb) for user portfolios in the domain. 2. (Optional) institutional type which determined the value of the default quota.
If a value has been stored in the domain's configuration db, it will return that, otherwise it returns 20 (for backwards compatibility with domains which have not set up a configuration db file; the original statically defined portfolio quota was 20 Mb).
If the user's status includes multiple types (e.g., staff and student), the largest default quota which applies to the user determines the default quota returned.
sorted_slots()
Sorts an array of slot names in order of slot start time (earliest first).
Inputs:
slotsarr - Reference to array of unsorted slot names.
slots - Reference to hash of hash, where outer hash keys are slot names.
Returns:
sorted - An array of slot names sorted by the start time of the slot.
Modify the %env hash to contain unprocessed CGI form parameters held in $query. The parameters listed in $possible_names (an array reference), will be set in $env{'form.name'} if they do not already exist.
Typically called with $ENV{'QUERY_STRING'} as the first parameter. $possible_names is an ref to an array of form element names. As an example: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']); will result in $env{'form.uname'} and $env{'form.udom'} being set.
returns cache-controlling header code
specifies header code to not have cache
adds $name to the %env hash with value $value, if $name already exists, the entry is converted to an array reference and $value is added to the array.
gets $name from the %env hash, it seemlessly handles the cases where multiple values may be defined and end up as an array ref.
returns an array of values
Store uploaded file, $r should be the HTTP Request object, needs $env{'form.upfile'} returns $datatoken to be put into hidden field
Load uploaded file from tmp, $r should be the HTTP Request object, needs $env{'form.datatoken'}, sets $env{'form.upfile'} to the contents of the file
Separate uploaded file into records returns array of records, needs $env{'form.upfile'} and $env{'form.upfiletype'}
Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
Return HTML code to select a file from the users machine and specify the file type.
Prints a table of sample values from each column uploaded $r is an Apache Request ref, $records is an arrayref from &Apache::loncommon::upfile_record_sep
Prints a table to create associations between values and table columns.
$r is an Apache Request ref, $records is an arrayref from &Apache::loncommon::upfile_record_sep, $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
Prints a table of sample values from the upload and can make associate samples to internal names.
$r is an Apache Request ref, $records is an arrayref from &Apache::loncommon::upfile_record_sep, $d is an array of 2 element arrays (internal name, displayed name)
Returns a replacement for $name which does not contain any illegal characters.
Returns either 1 or undef
1 if the part is to be hidden, undef if it is to be shown
Arguments are:
$id the id of the part to be checked $symb, optional the symb of the resource to check $udom, optional the domain of the user to check for $uname, optional the username of the user to check for
Inputs: none
Returns an id which can be used to pass environment variables to various cgi-bin scripts. These environment variables will be removed from the users environment after a given time by the routine &Apache::lonnet::transfer_profile_to_env.
Facilitates the plotting of data in a (stacked) bar graph. Puts plot definition data into the users environment in order for graph.png to plot it. Returns an <img> tag for the plot. The bars on the plot are labeled '1','2',...,'n'.
Inputs:
Returns:
An <img> tag which references graph.png and the appropriate identifying information for the plot.
Facilitates the plotting of data in an XY graph. Puts plot definition data into the users environment in order for graph.png to plot it. Returns an <img> tag for the plot.
Inputs:
Returns:
An <img> tag which references graph.png and the appropriate identifying information for the plot.
Facilitates the plotting of data in an XY graph with two Y axes. Puts plot definition data into the users environment in order for graph.png to plot it. Returns an <img> tag for the plot.
Inputs:
Returns:
An <img> tag which references graph.png and the appropriate identifying information for the plot.
Bad place for them but what the hell.
Returns a link to the chart for a specific student.
Inputs:
Restores/Store indicated form parameters from the course environment. Will not overwrite existing values of the form parameters.
Inputs: a scalar describing the data (e.g. 'chart', 'problem_analysis')
a hash ref describing the data to be stored. For example:
%Save_Parameters = ('Status' => 'scalar', 'chartoutputmode' => 'scalar', 'chartoutputdata' => 'scalar', 'Section' => 'array', 'Group' => 'array', 'StudentData' => 'array', 'Maps' => 'array');
Returns: both routines return nothing
Build recipient lists for five types of e-mail: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors (d) Help requests, (e) Course requests needing approval, generated by lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and loncoursequeueadmin.pm respectively.
Inputs: defmail (scalar - email address of default recipient), mailing type (scalar - errormail, packagesmail, or helpdeskmail), defdom (domain for which to retrieve configuration settings), origmail (scalar - email address of recipient from loncapa.conf, i.e., predates configuration by DC via domainprefs.pm
Returns: comma separated list of addresses to which to send e-mail.
Converts category definitions - keys of categories hash stored in coursecategories in configuration.db on the primary library server in a domain - to an array. Also generates javascript and idx hash used to generate Domain Coordinator interface for editing Course Categories.
Inputs:
categories (reference to hash of category definitions).
cats (reference to array of arrays/hashes which encapsulates hierarchy of categories and subcategories).
idx (reference to hash of counters used in Domain Coordinator interface for editing Course Categories).
jsarray (reference to array of categories used to create Javascript arrays for Domain Coordinator interface for editing Course Categories).
Returns: nothing
Side effects: populates cats, idx and jsarray.
Used to generate breadcrumb trails for course categories.
Inputs:
categories (reference to hash of category definitions).
cats (reference to array of arrays/hashes which encapsulates hierarchy of categories and subcategories).
trails (reference to array of breacrumb trails for each category).
allitems (reference to hash - key is category key (format: escaped(name):escaped(parent category):depth in hierarchy).
idx (reference to hash of counters used in Domain Coordinator interface for editing Course Categories).
jsarray (reference to array of categories used to create Javascript arrays for Domain Coordinator interface for editing Course Categories).
subcats (reference to hash of arrays containing all subcategories within each category, -recursive)
Returns: nothing
Side effects: populates trails and allitems hash references.
Recursively used to generate breadcrumb trails for course categories.
Inputs:
cats (reference to array of arrays/hashes which encapsulates hierarchy of categories and subcategories).
depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
category (current course category, for which breadcrumb trail is being generated).
trails (reference to array of breadcrumb trails for each category).
allitems (reference to hash - key is category key (format: escaped(name):escaped(parent category):depth in hierarchy).
parents (array containing containers directories for current category, back to top level).
Returns: nothing
Side effects: populates trails and allitems hash references
Create a datatable for display of hierarchical categories in a domain, with checkboxes to allow a course to be categorized.
Inputs:
cathash - reference to hash of categories defined for the domain (from configuration.db)
currcat - scalar with an & separated list of categories assigned to a course.
type - scalar contains course type (Course or Community).
Returns: $output (markup to be displayed)
Create a datatable row for display of nested categories in a domain, with checkboxes to allow a course to be categorized,called recursively.
Inputs:
itemcount - track row number for alternating colors
cats - reference to array of arrays/hashes which encapsulates hierarchy of categories and subcategories.
depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
parent - parent of current category item
path - Array containing all categories back up through the hierarchy from the current category to the top level.
currcategories - reference to array of current categories assigned to the course
Returns: $output (markup to be displayed).