[ 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: 2089 lines (66 kb)
Included or required: 1 time
Referenced: 0 times
Includes or requires: 0 files

Defines 59 functions

  hsc()
  blank()
  ptln()
  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()

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

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))

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

ptln($string, $indent = 0)   X-Ref
print a newline terminated string

You can give an indention as optional parameter

param: string $string  line of text
param: int    $indent  number of spaces indention
author: Andreas Gohr <andi@splitbrain.org>

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

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

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

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

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

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

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

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

basicinfo($id, $htmlClient=true)   X-Ref
Determine basic information 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>
return: array with info for a request of $id

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

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

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

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

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

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

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

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

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

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/splitbrain/dokuwiki/pull/84 and
https://github.com/splitbrain/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

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

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

It handles URL rewriting and adds additional parameters

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>
return: string

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().

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>
return: string

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

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
return: string

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

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

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

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)

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>
return: bool         - true if a spam word was found

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

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

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

Adapted from the example code at url below

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

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

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

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

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

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

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

removes stale lockfiles

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

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

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

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

also makes sure the given text is valid UTF-8

param: string $text
author: Andreas Gohr <andi@splitbrain.org>
return: string
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.

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

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

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

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

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

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

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

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

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

rawWikiSlices($range, $id, $rev = '')   X-Ref


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).

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>
return: string

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

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

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

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
author: Andreas Gohr <andi@splitbrain.org>
return: bool

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

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

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

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>
return: string human readable size

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

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

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()

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>
return: string
see: datetime_h

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

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

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

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

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

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

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

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

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

param: string $string
return: 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.

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
return: string

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

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>
return: string html or plain text(not escaped) of formatted user name

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

triggers: COMMON_USER_LINK
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
return: string html or plain text(not escaped) of formatted user name

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

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

is_mem_available($mem, $bytes = 1048576)   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

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>
return: bool

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

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

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

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.

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>
return: mixed

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

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

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!

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