> pictools > doc > SiteProps
> pictools > doc > SiteProps
Pictools: How Things Work
V3.3 (342)
SiteProps.php
/scripts/SiteProps.php
Php access to properties for Pictools client pages
usage, in beginpage: include_once $_SERVER['DOCUMENT_ROOT']."/scripts/SiteProps.php";

SiteProps defines a number of variables and functions of general use, especially those for files, properties, and logging. To avoid excessive "global" declarations, variables are enclosed in an object of class SiteProps. Only one such object is created; it is accessible via global variable $sp. In php source files that want to refer to $sp, it should be declared global both at the beginning of the file and at the beginning of each client function (See PHP's global).

There are four forms of file and directory name,

  • relative - no initial slash; value is relative to $sp->thisdir
  • site-rooted - begins with /, but not $root. If value is a directory, the last character is '/'.
  • file-rooted - begins with $root and continues with the site-rooted name
  • fullurl - begins with http://physpics.com and continues with the site-rooted name  (fullurl names are not used)

Names incoming as URLs are converted to site-rooted and processed in that form. The function siterooted() converts any name to site-rooted. The function filerooted() converts any name to file-rooted. (These functions are rarely used. $sp->request_uri() produces a site-rooted name and file-rooted values are derived by prepending $sp->root.

The SiteProp Object

The following variables and functions are essential to creating and managing SiteProp objects.

Variables

$root
location on server of the tree of files for the site. Corresponds to directory named by environment variable SRCROOT. Also corresponds to the directory given by properties SSHDEST/PICSDIR. $root has no trailing slash.
$thispage
page being processed. This value can be changed by setThisPage(); as happens when initial php code is needed to determine exactly what page needs to be served.
$thisdir
site-rooted page directory location; a single "/" or "/' at both ends. Nominally $thisdir = dirname($thispage), but "//" is convered to "/". Tests reveal these values from dirname:
dirname('/etc/foo')=>'/etc'; 
dirname('/etc/')=>'/';
dirname('/etc')=>'/';
dirname('/')=>'/';
dirname('.'=>'.';
$errorURL
set by error.php to the url with the error; this value is accessed by beginpage to initiate inclusion of box404.

Functions

function __construct()
INITIALIZE
function setThisPage($page, $from="unknown")
Adapt this SiteProp object for $page: set $thispage, $thisdir, and the properties set. The $from value may be printed in debugging logs. The $page argument must be site-rooted.
function request_uri()
Fetch and clean the incoming URI request. The value is site-rooted. The value will have been processed by urldecode (prior to setting $_SERVER['REQUEST_URI']), strip_tags, htmlspecialchars, and abspath(defined below). The query is not returned, but remains available in $_SERVER['QUERY_STRING'] and $_GET.

File and Directory Functions

function maybeinclude($file)
Include a file iff it is readable and not a directory. The name must be site-rooted.
function inclood($f)
Carefully include file $f and return true. Return false if $f cannot be read. $f must be site-rooted. if there is a file in /new/ matching $f, it will be included instead of $f itself
function inclood_once($f)
Line inclood(), but resorts to include_once
static function newer($f1, $f2)
file_newer() compares two file's modification times If the first does not exist, return false. Otherwise, if the second does not exist, return true. Otherwise, return true if the date of the first is AFTER the date of the second NOTE: $f1 and $f2 are file-rooted.
function siterooted($fnm)
Convert any file or directory name to site-rooted form. However, if the name is null or the empty string, return null. If the name is a drectory, it will be made to end with '/'. To be sure we have canonical names, the algorithm converts to file-rooted form and then removes the initial $root.
function filerooted($f)
Convert a site-rooted file name to file-rooted. Does so by simply prepending $root.
function parentdir($dir)
Computes the name of the parent directory of $dir. Ensures the result is site-rooted, with a trailing slash.
function nearestancestorfile($dot, $name)
Find the file $name in (site-rooted) directory $dot or an ancestor directory. Return the site-rooted path to the file.
function getFilestamp()
Get a timestamp for the time of $sp->thispage. If thispage does not actually exist, get time of the nearest existing ancestor directory.

Properties System

The propcon tool defines a properties scheme. The methods below extend that scheme into php so a script can ask for the properties defined for $sp->thisdir, or any other directory. Once fetched the the properties for a directory are cached. These variables in SiteProp objects are part of the properties scheme; they are set by setThisPage():

Variables

$propcache = array()
Cache for property sets fetched by getpropsfor. Elements are in form directory-name=>array($props, $propsource).
$props, an array
The properties in force for this page's directory. Each array element is in form property-name=>property-value.
$propsource - an array
For each property in props, the directory where that property was defined. Property p is local if $propsource[$p] === $sp->thisdir . This is an old feature. Locality can now be ensured by preceding the property definition with the pragma: #! private

Functions

function rebuildlocalphps($dir, &$count)
Force rebuild of Pictools.php in $dir and all subordinate directories. Works by deleting all Pictools.php files; they will be rebuilt as needed. $count is set to the number of directories visited. The return value is the number of files deleted.
function recompilePropcon()
When the propcon source file is uploaded it must be rebuilt to supplant the existing binary executable. The page displayed by /admin/command.php has a button to run this command. The compilation command is "gcc -g -o propcon.exe propcon.c src.c strtbl.c".
function runPropcon($dir)
If necessary, runs the propcon command in the given directory. Execution is necessary if Pictools.php is absent or predates the local Pictools.properties. This function does not check parent directories; hence the need to delete out-of-date instances of Pictools.php.
function getpropsfor($dir)
Get the properties for a given directory. The result is in form array(props, propsource). $dir must be site-rooted.
function getpropfrom($dir, $key)
Get property $key from those for directory $dir. $dir must be site-rooted.
function getprop($key)
Get the value of the named property for the current directory (whether or not inherited). If the property is not set, returns null.
function setprop($key, $val)
Set the (in-memory) value of the key to val. Sets only properties internal to this execution.
function getfnmprop($key)
Fetch a property whose value is expected to be a file or directory name. Convert the value to site-rooted form.

Other Tools

The functions below depend on a few variables. The first two can be used directly to sanitize values:

Variables

$BaseNameChars = "\-\_[:alnum:]";
A string containing the characters and classes allowed in file base names,  that is a filename without directory. Includes [:alnum:], dash, and underline. Suitable for building a character class. For a file name and extension, the dot must also be allowed. "u" can be appended to the pattern to allow utf-8. To create a pattern that recognizes file names without extension one might write:
$bnc = $sp->BaseNameChars
$pattern = "<[$bnc\.]*>u";
$PathNameChars; // = $this->BaseNameChars . "\.\/\:\~";
A string containing the characters and classes allowed in file path names. In addition to $BaseNameChars there are dot, slash, tilde, and colon Suitable for building a character class.
$prefetch;
Array of items to prefetch. Initially empty. Appended to by prefetchlist() and used by doprefetches().

Functions

function linkstyles($dir)
Generate links to styles.css in $dir and its parents. Do it in top-down order, so the style in the closest ancestor supercedes all others. $dir is site-rooted.
function prefetchlist($list)
The $list value is a space-separated string where the first element is a directory and all others are image-names for images in that directory. For each image name, the function appends directory/imagename to $prefetch.
function doprefetches()
Generate prefetch links for the items on the prefetch list. Each item generates a link in the form:
<link rel='prefetch' href='/directory/imagename'> 
function pathNameQuery($field, $default = null, $error = null)
Fetch a filename-like value from $_GET[$field]. All characters of the value must match $PathNameChars. If the field is absent, the $default value is returned. If the field contains an invalid value, the $error value is returned.
function intQuery($field, $default)
Fetch an integer-valued field from the url's query area. If the field is absent or empty or has non-digits, the default will be returned.

Static functions

Useful tools that are independant of the file and directory being processed.

function abspath($path)
Canonicalize a directory name: reduce multiple consecutive slashes to a single slash, process away instances of /.. and /.
$path must begin with slash. Result will begin with slash and will not end with slash unless the value is "/".
filterFileName($name)
Remove from $name any characters which are not allowed in a (restricted) file name. The allowed characters are letters, digits, / : . - _ ~ \
function show_from_GET($s)
Convert a string from $_GET to one that can be sent through html for viewing. Applies htmlspecialchars.
function show_from_URL($s)
Convert a URL encoded string to one that can be sent through html for viewing. Applies first urldecode and then htmlspecialchars.
function print_a($subject)
Does print_r($subject) and converts the output to html.
function util_ezec($cmd, $input='', $cwd=null, $env=null)
Executes $cmd via proc_open. Passes $input on stdin. If $cwd is not null, it is set as the current working directory. If $env is not null, it must be an associative array mapping variables to values; it is passed as the environment for xecuting the command. 
 
Returns the result as an array where
"cmd" ⇒ the original command
"cwd" ⇒ the working directory
"stdout" ⇒ commands output to stdout
"stderr" ⇒ commands output to stderr
"return" ⇒ the exit status from the command
function stringToDOMDoc($s)
Create a DOMDocument from a String. Arbitrary entity references are passed through unharmed by a simple trick: ALL instances of "&" are converted to "&amp;". at some future time the entities need to be reconstituted by passing the string through disAmp().
function disAmp($text)
Convert &amp; back to &, thus undoing stringToDOMDoc.
function dumpnodes($node, $linestart="", $eol = "\n")
Dump the node tree of a DOMNode. The output is produced via echo() This can add an HTML-comment to a web page. If $linestart is not empty, the error comments are omited; if inside HTML, the text will appear on the page. If $eol is to not be "\n", it should usually be "<br/>\n" to insert a newline into the wegpage text.
function b2s($b)
Converts a boolean value to the string "true" or "false".
function startsWith($hay, $key)
Returns true iff $hay starts with the string $key.
function endsWith($hay, $key)
Returns true iff $hay ends with the string $key.

Reporting tools

Definitions of the following methods depend on whether the "admin" cookie is set. Normally, it is set only for the site manager. If not set, the methods do nothing. All but the last generate comments into the html code. They are not used much. The last logs the message; I use it a lot.

function echoing()
Returns true if these methods are actually producing output, otherwise false.
function echo_msg($msg)
Echoes to HTML a comment line containing the message.
function echo_var($nm, $val)
Echoes a message that the given variable has the given value. Call it with the $nm as a string: echo_var("x", x).
function echo_prop($pnm)
Echoes to HTML a comment line giving the name and value of the property and the directory where it was declared.
function echo_elapsed($msg)
Echoes to HTML a comment line giving the time-since-load-SiteProps and the message.
function php_debug($msg)
Appends to /admin/logs/debug.txt the date and $msg. By convention, each message begins with the name of the script generating it. (To skip this is but one of many paths to madness.) The section on debugging pages describes a tool for viewing debug.txt.

Beyond Definitions

After all the preceding definitions, the script finally does something. It creates an instance object of SiteProps and sets the global varabiable $sp to refer to it:

$sp = new SiteProps();

If $thispage is set (as it is in instances of the PhyspicsMain template), the script calls $sp->setThisPage($thispage).

 
Copyright © 2016 ZweiBieren, All rights reserved. Jul 4, 2016 21:35 GMT Page maintained by ZweiBieren