[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> common.php (summary)

Common DokuWiki functions

Author: Andreas Gohr
License: GPL 2 (http://www.gnu.org/licenses/gpl.html)
File Size: 2038 lines (61 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 59 functions

  hsc()
  sexplode()
  blank()
  stripctl()
  getSecurityToken()
  checkSecurityToken()
  formSecurityToken()
  basicinfo()
  pageinfo()
  jsinfo()
  mediainfo()
  buildURLparams()
  buildAttributes()
  breadcrumbs()
  idfilter()
  wl()
  exportlink()
  ml()
  script()
  checkwordblock()
  clientIP()
  clientismobile()
  link_isinterwiki()
  gethostsbyaddrs()
  checklock()
  lock()
  unlock()
  cleanText()
  formText()
  rawLocale()
  rawWiki()
  pageTemplate()
  parsePageTemplate()
  rawWikiSlices()
  con()
  detectExternalEdit()
  saveWikiText()
  saveOldRevision()
  notify()
  getGoogleQuery()
  filesize_h()
  datetime_h()
  dformat()
  date_iso8601()
  obfuscate()
  unslash()
  php_to_byte()
  preg_quote_cb()
  shorten()
  editorinfo()
  userlink()
  license_img()
  is_mem_available()
  send_redirect()
  valid_input_set()
  get_doku_pref()
  set_doku_pref()
  stripsourcemaps()
  inlineSVG()

Functions
Functions that are not part of a class:

hsc($string)   X-Ref
Wrapper around htmlspecialchars()

return: string converted string
param: string $string the string being converted
author: Andreas Gohr <andi@splitbrain.org>
see: htmlspecialchars()

sexplode($separator, $string, $limit, $default = null)   X-Ref
A safer explode for fixed length lists

This works just like explode(), but will always return the wanted number of elements.
If the $input string does not contain enough elements, the missing elements will be
filled up with the $default value. If the input string contains more elements, the last
one will NOT be split up and will still contain $separator

return: array
param: string $separator The boundary string
param: string $string The input string
param: int $limit The number of expected elements
param: mixed $default The value to use when filling up missing elements
see: explode

blank(&$in, $trim = false)   X-Ref
Checks if the given input is blank

This is similar to empty() but will return false for "0".

Please note: when you pass uninitialized variables, they will implicitly be created
with a NULL value without warning.

To avoid this it's recommended to guard the call with isset like this:

(isset($foo) && !blank($foo))
(!isset($foo) || blank($foo))

return: bool
param: $in
param: bool $trim Consider a string of whitespace to be blank

stripctl($string)   X-Ref
strips control characters (<32) from the given string

return: string
param: string $string being stripped
author: Andreas Gohr <andi@splitbrain.org>

getSecurityToken()   X-Ref
Return a secret token to be used for CSRF attack prevention

return: string
link: http://en.wikipedia.org/wiki/Cross-site_request_forgery
link: http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
author: Andreas Gohr <andi@splitbrain.org>

checkSecurityToken($token = null)   X-Ref
Check the secret CSRF token

return: bool success if the token matched
param: null|string $token security token or null to read it from request variable

formSecurityToken($print = true)   X-Ref
Print a hidden form field with a secret CSRF token

return: string html of hidden form field
param: bool $print  if true print the field, otherwise html of the field is returned
author: Andreas Gohr <andi@splitbrain.org>

basicinfo($id, $htmlClient = true)   X-Ref
Determine basic information for a request of $id

return: array with info for a request of $id
param: string $id         pageid
param: bool   $htmlClient add info about whether is mobile browser
author: Andreas Gohr <andi@splitbrain.org>
author: Chris Smith <chris@jalakai.co.uk>

pageinfo()   X-Ref
Return info about the current document as associative
array.

return: array with info about current document
author: Andreas Gohr <andi@splitbrain.org>

jsinfo()   X-Ref
Initialize and/or fill global $JSINFO with some basic info to be given to javascript


mediainfo()   X-Ref
Return information about the current media item as an associative array.

return: array with info about current media item

buildURLparams($params, $sep = '&amp;')   X-Ref
Build an string of URL parameters

return: string query string
param: array  $params    array with key-value pairs
param: string $sep       series of pairs are separated by this character
author: Andreas Gohr

buildAttributes($params, $skipEmptyStrings = false)   X-Ref
Build an string of html tag attributes

Skips keys starting with '_', values get HTML encoded

return: string
param: array $params           array with (attribute name-attribute value) pairs
param: bool  $skipEmptyStrings skip empty string values?
author: Andreas Gohr

breadcrumbs()   X-Ref
This builds the breadcrumb trail and returns it as array

return: string[] with the data: array(pageid=>name, ... )
author: Andreas Gohr <andi@splitbrain.org>

idfilter($id, $ue = true)   X-Ref
Filter for page IDs

This is run on a ID before it is outputted somewhere
currently used to replace the colon with something else
on Windows (non-IIS) systems and to have proper URL encoding

See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
unaffected servers instead of blacklisting affected servers here.

Urlencoding is ommitted when the second parameter is false

return: string
param: string $id pageid being filtered
param: bool   $ue apply urlencoding?
author: Andreas Gohr <andi@splitbrain.org>

wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')   X-Ref
This builds a link to a wikipage

It handles URL rewriting and adds additional parameters

return: string
param: string       $id             page id, defaults to start page
param: string|array $urlParameters  URL parameters, associative array recommended
param: bool         $absolute       request an absolute URL instead of relative
param: string       $separator      parameter separator
author: Andreas Gohr <andi@splitbrain.org>

exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')   X-Ref
This builds a link to an alternate page format

Handles URL rewriting if enabled. Follows the style of wl().

return: string
param: string       $id             page id, defaults to start page
param: string       $format         the export renderer to use
param: string|array $urlParameters  URL parameters, associative array recommended
param: bool         $abs            request an absolute URL instead of relative
param: string       $sep            parameter separator
author: Ben Coburn <btcoburn@silicodon.net>

ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)   X-Ref
Build a link to a media file

Will return a link to the detail page if $direct is false

The $more parameter should always be given as array, the function then
will strip default parameters to produce even cleaner URLs

return: string
param: string  $id     the media file id or URL
param: mixed   $more   string or array with additional parameters
param: bool    $direct link to detail page if false
param: string  $sep    URL parameter separator
param: bool    $abs    Create an absolute URL

script()   X-Ref
Returns the URL to the DokuWiki base script

Consider using wl() instead, unless you absoutely need the doku.php endpoint

return: string
author: Andreas Gohr <andi@splitbrain.org>

checkwordblock($text = '')   X-Ref
Spamcheck against wordlist

Checks the wikitext against a list of blocked expressions
returns true if the text contains any bad words

Triggers COMMON_WORDBLOCK_BLOCKED

Action Plugins can use this event to inspect the blocked data
and gain information about the user who was blocked.

Event data:
data['matches']  - array of matches
data['userinfo'] - information about the blocked user
[ip]           - ip address
[user]         - username (if logged in)
[mail]         - mail address (if logged in)
[name]         - real name (if logged in)

return: bool         - true if a spam word was found
param: string $text - optional text to check, if not given the globals are used
author: Andreas Gohr <andi@splitbrain.org>
author: Michael Klier <chi@chimeric.de>

clientIP($single = false)   X-Ref
Return the IP of the client

Honours X-Forwarded-For and X-Real-IP Proxy Headers

It returns a comma separated list of IPs if the above mentioned
headers are set. If the single parameter is set, it tries to return
a routable public address, prefering the ones suplied in the X
headers

return: string
param: boolean $single If set only a single IP is returned
author: Andreas Gohr <andi@splitbrain.org>

clientismobile()   X-Ref
Check if the browser is on a mobile device

Adapted from the example code at url below

return: bool if true, client is mobile browser; otherwise false
link: http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code

link_isinterwiki($link)   X-Ref
check if a given link is interwiki link

return: bool
param: string $link the link, e.g. "wiki>page"

gethostsbyaddrs($ips)   X-Ref
Convert one or more comma separated IPs to hostnames

If $conf['dnslookups'] is disabled it simply returns the input string

return: string a comma separated list of hostnames
param: string $ips comma separated list of IP addresses
author: Glen Harris <astfgl@iamnota.org>

checklock($id)   X-Ref
Checks if a given page is currently locked.

removes stale lockfiles

return: bool page is locked?
param: string $id page id
author: Andreas Gohr <andi@splitbrain.org>

lock($id)   X-Ref
Lock a page for editing

param: string $id page id to lock
author: Andreas Gohr <andi@splitbrain.org>

unlock($id)   X-Ref
Unlock a page if it was locked by the user

return: bool true if a lock was removed
param: string $id page id to unlock
author: Andreas Gohr <andi@splitbrain.org>

cleanText($text)   X-Ref
convert line ending to unix format

also makes sure the given text is valid UTF-8

return: string
param: string $text
author: Andreas Gohr <andi@splitbrain.org>
see: formText() for 2crlf conversion

formText($text)   X-Ref
Prepares text for print in Webforms by encoding special chars.
It also converts line endings to Windows format which is
pseudo standard for webforms.

return: string
param: string $text
author: Andreas Gohr <andi@splitbrain.org>
see: cleanText() for 2unix conversion

rawLocale($id, $ext = 'txt')   X-Ref
Returns the specified local text in raw format

return: string
param: string $id   page id
param: string $ext  extension of file being read, default 'txt'
author: Andreas Gohr <andi@splitbrain.org>

rawWiki($id, $rev = '')   X-Ref
Returns the raw WikiText

return: string
param: string $id   page id
param: string|int $rev  timestamp when a revision of wikitext is desired
author: Andreas Gohr <andi@splitbrain.org>

pageTemplate($id)   X-Ref
Returns the pagetemplate contents for the ID's namespace

triggers: COMMON_PAGETPL_LOAD
return: string parsed pagetemplate content
param: string $id the id of the page to be created
author: Andreas Gohr <andi@splitbrain.org>

parsePageTemplate(&$data)   X-Ref
Performs common page template replacements
This works on data from COMMON_PAGETPL_LOAD

return: string
param: array $data array with event data
author: Andreas Gohr <andi@splitbrain.org>

rawWikiSlices($range, $id, $rev = '')   X-Ref
Returns the raw Wiki Text in three slices.

The range parameter needs to have the form "from-to"
and gives the range of the section in bytes - no
UTF-8 awareness is needed.
The returned order is prefix, section and suffix.

return: string[] with three slices
param: string $range in form "from-to"
param: string $id    page id
param: string $rev   optional, the revision timestamp
author: Andreas Gohr <andi@splitbrain.org>

con($pre, $text, $suf, $pretty = false)   X-Ref
Joins wiki text slices

function to join the text slices.
When the pretty parameter is set to true it adds additional empty
lines between sections if needed (used on saving).

return: string
param: string $pre   prefix
param: string $text  text in the middle
param: string $suf   suffix
param: bool $pretty add additional empty lines between sections
author: Andreas Gohr <andi@splitbrain.org>

detectExternalEdit($id)   X-Ref
Checks if the current page version is newer than the last entry in the page's
changelog. If so, we assume it has been an external edit and we create an
attic copy and add a proper changelog line.

This check is only executed when the page is about to be saved again from the
wiki, triggered in @see saveWikiText()

param: string $id the page ID

saveWikiText($id, $text, $summary, $minor = false)   X-Ref
Saves a wikitext by calling io_writeWikiPage.
Also directs changelog and attic updates.

param: string $id       page id
param: string $text     wikitext being saved
param: string $summary  summary of text update
param: bool   $minor    mark this saved version as minor update
author: Andreas Gohr <andi@splitbrain.org>
author: Ben Coburn <btcoburn@silicodon.net>

saveOldRevision($id)   X-Ref
moves the current version to the attic and returns its revision date

return: int|string revision timestamp
param: string $id page id
author: Andreas Gohr <andi@splitbrain.org>

notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)   X-Ref
Sends a notify mail on page change or registration

return: bool
param: string     $id       The changed page
param: string     $who      Who to notify (admin|subscribers|register)
param: int|string $rev      Old page revision
param: string     $summary  What changed
param: boolean    $minor    Is this a minor edit?
param: string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
param: int|string $current_rev  New page revision
author: Andreas Gohr <andi@splitbrain.org>

getGoogleQuery()   X-Ref
extracts the query from a search engine referrer

return: array|string
author: Andreas Gohr <andi@splitbrain.org>
author: Todd Augsburger <todd@rollerorgans.com>

filesize_h($size, $dec = 1)   X-Ref
Return the human readable size of a file

return: string human readable size
param: int $size A file size
param: int $dec A number of decimal places
author: Martin Benjamin <b.martin@cybernet.ch>
author: Aidan Lister <aidan@php.net>

datetime_h($dt)   X-Ref
Return the given timestamp as human readable, fuzzy age

return: string
param: int $dt timestamp
author: Andreas Gohr <gohr@cosmocode.de>

dformat($dt = null, $format = '')   X-Ref
Wraps around strftime but provides support for fuzzy dates

The format default to $conf['dformat']. It is passed to
strftime - %f can be used to get the value from datetime_h()

return: string
param: int|null $dt      timestamp when given, null will take current timestamp
param: string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
author: Andreas Gohr <gohr@cosmocode.de>
see: datetime_h

date_iso8601($int_date)   X-Ref
Formats a timestamp as ISO 8601 date

return: string
link: http://php.net/manual/en/function.date.php#54072
param: int $int_date current date in UNIX timestamp
author: <ungu at terong dot com>

obfuscate($email)   X-Ref
return an obfuscated email address in line with $conf['mailguard'] setting

return: string
param: string $email email address
author: Harry Fuecks <hfuecks@gmail.com>
author: Christopher Smith <chris@jalakai.co.uk>

unslash($string, $char = "'")   X-Ref
Removes quoting backslashes

return: string
param: string $string
param: string $char backslashed character
author: Andreas Gohr <andi@splitbrain.org>

php_to_byte($value)   X-Ref
Convert php.ini shorthands to byte

On 32 bit systems values >= 2GB will fail!

-1 (infinite size) will be reported as -1

return: int
link: https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
param: string $value PHP size shorthand

preg_quote_cb($string)   X-Ref
Wrapper around preg_quote adding the default delimiter

return: string
param: string $string

shorten($keep, $short, $max, $min = 9, $char = '…')   X-Ref
Shorten a given string by removing data from the middle

You can give the string in two parts, the first part $keep
will never be shortened. The second part $short will be cut
in the middle to shorten but only if at least $min chars are
left to display it. Otherwise it will be left off.

return: string
param: string $keep   the part to keep
param: string $short  the part to shorten
param: int    $max    maximum chars you want for the whole string
param: int    $min    minimum number of chars to have left for middle shortening
param: string $char   the shortening character to use

editorinfo($username, $textonly = false)   X-Ref
Return the users real name or e-mail address for use
in page footer and recent changes pages

return: string html or plain text(not escaped) of formatted user name
param: string|null $username or null when currently logged-in user should be used
param: bool $textonly true returns only plain text, true allows returning html
author: Andy Webber <dokuwiki AT andywebber DOT com>

userlink($username = null, $textonly = false)   X-Ref
Returns users realname w/o link

triggers: COMMON_USER_LINK
return: string html or plain text(not escaped) of formatted user name
param: string|null $username or null when currently logged-in user should be used
param: bool $textonly true returns only plain text, true allows returning html

license_img($type)   X-Ref
Returns the path to a image file for the currently chosen license.
When no image exists, returns an empty string

return: string
param: string $type - type of image 'badge' or 'button'
author: Andreas Gohr <andi@splitbrain.org>

is_mem_available($mem, $bytes = 1_048_576)   X-Ref
Checks if the given amount of memory is available

If the memory_get_usage() function is not available the
function just assumes $bytes of already allocated memory

return: bool
param: int  $mem    Size of memory you want to allocate in bytes
param: int  $bytes  already allocated memory (see above)
author: Filip Oscadal <webmaster@illusionsoftworks.cz>
author: Andreas Gohr <andi@splitbrain.org>

send_redirect($url)   X-Ref
Send a HTTP redirect to the browser

Works arround Microsoft IIS cookie sending bug. Exits the script.

link: http://support.microsoft.com/kb/q176113/
param: string $url url being directed to
author: Andreas Gohr <andi@splitbrain.org>

valid_input_set($param, $valid_values, $array, $exc = '')   X-Ref
Validate a value using a set of valid values

This function checks whether a specified value is set and in the array
$valid_values. If not, the function returns a default value or, if no
default is specified, throws an exception.

return: mixed
param: string $param        The name of the parameter
param: array  $valid_values A set of valid values; Optionally a default may
param: array  $array        The array containing the value (typically $_POST
param: string $exc          The text of the raised exception
author: Adrian Lang <lang@cosmocode.de>

get_doku_pref($pref, $default)   X-Ref
Read a preference from the DokuWiki cookie
(remembering both keys & values are urlencoded)

return: string preference value
param: string $pref     preference key
param: mixed  $default  value returned when preference not found

set_doku_pref($pref, $val)   X-Ref
Add a preference to the DokuWiki cookie
(remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
Remove it by setting $val to false

param: string $pref  preference key
param: string $val   preference value

stripsourcemaps(&$text)   X-Ref
Strips source mapping declarations from given text #601

param: string &$text reference to the CSS or JavaScript code to clean

inlineSVG($file, $maxsize = 2048)   X-Ref
Returns the contents of a given SVG file for embedding

Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
files are embedded.

This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!

return: string|false the SVG content, false if the file couldn't be loaded
param: string $file full path to the SVG file
param: int $maxsize maximum allowed size for the SVG to be embedded