Functional Helpers

In which I define a load of helpful little functions.

Some of these are stolen from elsewhere, credit given where due.

author Barnaby Walters http://waterpigs.co.uk

 Methods

Date to ATOM Date

atomDate(string | string $date) 
Static
todo Allow $date to be a DateTime object

Parameters

$date

stringstring

A string representing the date to process

Parse a representation of an author out of a URI

authorFromUri(string $uri) : string
Static

Given a URI, returns a plaintext representation of the author of that URI, nice and ready to be processed/auto linked in whatever way you see fit. Currently enabled for the following services:

  • Twitter
  • Indiewebsite domain (sans protocol) — assumed if doesn’t fit anything else

Parameters

$uri

string

The URI to parse

Returns

stringThe parsed author representation, e.g. @barnabywalters or waterpigs.co.uk

Auto Link Hashtags

autolinkHashTags(string $text, string $baseUrl) : string
Static

Given a string and a baseurl, finds all hashtags matching #[\-_a-zA-Z0-9]+ and wraps them in an a element with rel=tag set and a href of baseurl + '/' + tagname without the #.

todo Improve the regex to limit false matches

Parameters

$text

string

$baseUrl

string

Returns

stringThe original text with all hashtags auto-linked

Create XML-RPC Fault Response

createXmlRpcFaultResponse(string | int $fault, bool $asString) : \DOMDocument
Static

Creates an XML-RPC Fault response with either an int or a string as the fault.

Parameters

$fault

stringint

$asString

bool

Returns

Create XML-RPC Success Response

createXmlRpcSuccessResponse(string $retVal, bool $asString) : \DOMDocument
Static

Given the value to return (can only be a string at the mo), creates a response.

Parameters

$retVal

string

The string to return

$asString

bool

Whether or not to return the respons as a string or DOMDocument

Returns

Replace <img> elements with their @href

expandImg(string $str) : string
Static

Finds all img elements and replaces them with the value of their @href. Very useful for content syndication to services which do not allow HTML

Parameters

$str

string

The string to process

Returns

stringThe original $str with all tags replaced by their @href value

Find URLs

findUrls(string $text, bool $tidy) : array
Static

Parameters

$text

string

The string to find URLs in

$tidy

bool

Whether or not to tidy the URLs with cassis web_address_to_uri(, true)

Returns

arrayAn array containing all the URLs found in $text

Get Privacy Tags

getAuthTags(array $tags) 
Static

Given an array of the tags associated with an object, find any which are in the auth namespace, parse them and return them.

Multiple Tag Rules

Authorization tags are all positive and additive. That is, it is impossible for one tag to contradict another.

  • All auth tags are machine tags of the form auth:(:any)=(:any), where the wildcards must be:
    1. An auth keyword from the list below
    2. A valid hostname, e.g. example.com, waterpigs.co.uk, bill.someservice.org

Auth Keywords

  • private
    • If an object contains ANY auth:private=* tags, it is a private post and MUST ONLY be exposed to users who are authenticated as one of the private-* domains
    • Multiple auth:private-* tags MAY be specified, resulting in ANY of the specified users being able to view the content
  • editable
    • auth:editable=user.com states that user.com is allowed to edit this object. An edit UI should be made available to them.
    • Users who can edit an object due to auth:editable CANNOT add or remove auth:editable tags UNLESS they have role == super-admin Users with role == 'super-admin' MUST be able to perform ANY action on ANY object. These users SHOULD be limited to server administrators. AuthTag implementations should be aware of this but MUST NOT implement it directly, it must be left to the outer authorization code as the super-admin role may have different names on different systems.

Example Tags

All of these examples are comma-separated tagstrings.

  • auth:private=example.com states that the object is private but user example.com can view it
  • auth:private=example.com, auth:private=someguy.org states that the object is private but both example.com someguy.org can view it
  • auth:private=someguy.org, auth:private=somegirl.com, auth:editable=somegirl.com states that the object is private but both someguy.org and somegirl.com can view it. somegirl.com can also edit it, but cannot change authtag permissions

Parameters

$tags

Get Machine Tags

getMachineTags(array $tags, string $namespace, boolean $trunc) : array
Static

Given an array of opaque string tags, return an array of all the machine tags of format namespace:predicate=value, optionally filtering by namespace.

If the tags are filtered by namespace and $trunc is set, the namespace and following colon are removed from the results.

The return value is always an associative array of namespace:predicate => value.

Parameters

$tags

array

$namespace

string

$trunc

boolean

Returns

array

Get Plain Tags

getPlainTags(array $tags) : array
Static

Returns an array of all the non-machine tags in the passed array.

Parameters

$tags

array

Returns

arrayThe input with all machine tags removed

Humanise String

humanise(string $string) : string
Static

Makes a slugified/ASCIIfied string nice again

todo make this happen for CamelCase too?
todo add more intelligent dash/underscore selection

Parameters

$string

string

Returns

string

Microformats from geo: tags

mfFromGeotags(array $tags) : array
Static

Given an array containing some tags in the geo: namespace, produces a h-geo and h-adr µf2 array structure from the data available

Parameters

$tags

array

Returns

arrayµf2 array representation of a h-adr composed from the parts

Parse XML-RPC Method Call

parseXmlRpcMethodCall(string $request) : array
Static

Given an XML-RPC request body, returns an array like this:

[
	'methodName': 'example.ex',
	'params': ['string1', 'string2]
]

NOTE: Only currently accepts string parameters.

todo Make this handle param types other than `string`

Parameters

$request

string

Returns

array

Get Relative Time Element

relativeTimeElement(\DateTime $dateTime, \DateTime $comparison, array $attrs) : string
Static
todo write tests

Parameters

$dateTime

\DateTime

The datetime in question

$comparison

\DateTime

Date to compare with. Defaults to now

$attrs

array

Assoc array of attributes to add to the element

Returns

stringThe time HTML element with human value inside

Same Hostname

sameHostname(string $a, string $b) : bool
Static

Checks whether or not two given URLs have the same hostname

Parameters

$a

string

$b

string

Returns

boolWhether or not a and b share a hostname

String to Hex Colour

stringToHexColour(string $word) : string
Static

Inspired by the Dopplr colours and the work of Brian Suda and Sandeep Shetty. This differs a little from the md5 technique as it should create similar colours for similar sounding words -- only time will tell if this is any use and/or completely ineffective.

todo Write tests

Parameters

$word

string

The string to calculate the colour for

Returns

stringa css hex colour of the form XXXXXX

Clean Tagstring

tagstringClean(string $tagstring) : string
Static

Normalises a tag string by converting it to an array, then collapsing the array into a string.

Parameters

$tagstring

string

The comma-delimited string to clean

Returns

stringThe cleaned string

Tagstring to Array

tagstringToArray(string $tagstring) : array
Static

Takes a comma delimited tag string, returns an array of the tags contained within.

Parameters

$tagstring

string

The comma delimited string to process

Returns

arrayAn array of the tags contained within $tagstring

DateTime to <time>

timeElement(\DateTime $datetime) : string
Static

Generates a

todo Add support for more precise times
todo Add support for string dates using strtotime()

Parameters

$datetime

\DateTime

The datetime to turn into a

Returns

stringA

Slugify

toAscii(string $str, array $replace, string $delimiter) : string
Static

The ultimate safe URL generator, courtesy of http://cubiq.org/the-perfect-php-clean-url-generator

Given a string, makes it uber-readable and URI safe

Parameters

$str

string

The string to process

$replace

array

An array of characters to replace with whitespace

$delimiter

string

The character to use to separate words, defaulting to '-'

Returns

stringThe cleaned string

Returns the truest of the args presented.

truest() 
Static

This is a dirty shortcut.

Find the length a string would be if all URLs were a certain length

uriMbStrlen(string $string, int $urilen) : int
Static

Parameters

$string

string

The string to process

$urilen

int

The length to treat all URIs in $string as

Returns

intThe length $string would be if all URIs were $urilen long