Jojo Class Reference

Jojo:: Reference

Jojo provides a number of utility functions, these are all in the Jojo class and are static functions. They are available from any php file eg global.php in a theme, inside a plugin, inside php tags in smarty etc.


Database Functions

All database query functions take an SQL statement and any variables for variable binding. Variable binding frees you from worrying about escaping data before it gets passed to the database. Simply place a ? in the statement where the values are to go, and pass the values in an array as the second parameter.

Table name should be enclosed in in braces ({ and }) so the table can be prefixed correctly, if table prefixing is being used. See the examples below.

Jojo::selectQuery

Runs a select query and returns an array of associative arrays or each result row.

Jojo::selectQuery($query, [$variables = array()])
  $query     string The SQL query to run.
  $variables array An optional array of values to replace ? characters in query

Example:
$rows = Jojo::selectQuery('SELECT pageid, pg_title FROM {page} WHERE pg_url = ?', array('contact'));
var_dump($rows);

Jojo::updateQuery

Runs an update query and returns the numbers of affected rows.

Jojo::updateQuery($query, [$variables = array()])
  $query     string The SQL query to run.
  $variables array An optional array of values to replace ? characters in query

Example:
  $numrows = Jojo::updateQuery('UPDATE {page} SET pg_title = ? WHERE pg_url = ?', array('Contact Details', 'contact'));
  echo $numrows;

Jojo::insertQuery

Runs and insert query and returns the insert id of the new row.

Jojo::insertQuery($query, [$variables = array()])
  $query     string The SQL query to run.
  $variables array An optional array of values to replace ? characters in query

Example:
  $pageid = Jojo::insertQuery('INSERT INTO {page} SET pg_title = ?, pg_url = ?', array('Demo page', 'demo'));
  echo $pageid;

Jojo::deleteQuery

Runs a delete query and returns the numbers of delete rows.

Jojo::deleteQuery($query, [$variables = array()])
  $query     string The SQL query to run.
  $variables array An optional array of values to replace ? characters in query

Example:
  $numrows = Jojo::updateQuery('DELETE FROM {page} WHERE pg_url = ?', array('demo'));
  echo $numrows;

Jojo::structureQuery

Runs a table that changes the structure of a table or database.

Jojo::structureQuery($query)
  $query     string The SQL query to run.

Example:
  Jojo::structureQuery('DROP TABLE {demotable}');

Jojo::tableExists

Check if a talbe exists, returns true or false.

Jojo::tableExists($tablename, [$type = 'TABLES'])
  $tablename The name of the table to check for, without the prefix
  $type check if tablename is a 'TABLES' or 'VIEWS'.

Example:
  if (Jojo::tableExists('page')) {
    echo "Page table exists as a table";
  } elseif (Jojo::tableExists('page', 'VIEWS')) {
    echo "Page table exists as a view";
  }

Jojo::fieldExists

Checks if a field exists in a table, returns true or false.

Jojo::fieldExists($tablename, $fieldname)
  $tablename The name of the table to check in, without prefix
  $fieldname The name of the field to check for

Example:
  if (Jojo::fieldExists('page', 'pageid')) {
    // do something cool
  }

Jojo::clean

Escapes a string for use in a query. Sometimes using variable binding isn't going to work for a really complex query, but you still want to escape something before it goes into the query.

Jojo::clean($string)
  $string String to Clean

Example:
  $query = "SELECT * FROM page WHERE pg_body LIKE '%" . Jojo::clean($searchString) . "%'";
  $pages = Jojo::selectQuery($query);

Jojo::cleanInt (deprecated)

Prepares an integer for use in database queries - returns zero for any non-numeric input */

Jojo::cleanInt($string)
  $string Value to Clean

Jojo::getMySQLType (deprecated)

Returns the MySQL type of a database column, eg int, varchar.

Jojo::getMySQLType($tablename, $fieldname)
  $tablename The name of the table to check in, without prefix
  $fieldname The name of the field to check for

Example:
  if (Jojo::getMySQLType('page', 'pageid') == 'varchar') {
    // something is really broken
  }

File and Directory Handling

Helper functions to make working with files easier.

Jojo::getFileExtension

Returns the file extension of the supplied file name

Jojo::getFileExtension($filename)
  $filename The file name to extract the extension from.

Example:
  if (Jojo::getFileExtension($imagefilename) == 'jpg') {
      $im = imagecreatefromjpeg($imagefilename);
  }

Jojo::getMimeType

Converts a file name to a MIME type from based on the file extension. It looks up a list known types.

Jojo::getMimeType($filename)
  $filename The file name to return the mime type of.

Example:
  header('Content-type: ' . Jojo::getMimeType($imagefilename));
  echo file_get_contents($imagefilename);
  exit;

Jojo::recursiveMkdir

Recursively create a directory

 Jojo::recursiveMkdir($path)
   $path string Name of the directory to create

 Returns
   (boolean)true if the folder was created.
   (boolean)false if the folder could not be created.
   (int)-1 if the folder already exists.

Example:
  Jojo::recursiveMkdir(_CACHEDIR . '/dir/to/cache/stuff/in');

Jojo::fileExists

Check if a file exists and that it is a file. The standard file_exists() function will return true if a directory exists of the same name, this won't.

Jojo::fileExists($filename)
  $filename The name of the file to check

Returns
  (boolean) true if the file exists and is a file
  (boolean) false if the file does not exist, or is a folder

Example:
  if (Jojo::fileExists($somefile)) {
      echo 'I found a file!';
  }

Jojo::scanDirectory

Returns a array with all the file/dirctory names in a folder. Skips all 'dot files', files that start with a '.', like .svn and .git folders.

Jojo::scanDirectory($dir, [$sort = 0])
  $dir The name of the directory to scann
  $sort 0 for alphabetical order, 1 for reverse alphabetical order.

Example:
  $images = Jojo::scanDirectory('/some/images/dir');

Form Handling

Due to various php config settings, the values in $_POST and $_GET may not always be exactly as the user submitted them. Sometimes they may not be presennt resulting in php errors. The function are to make life easier for developers working with form data.

Jojo::getFormData

Returns the valaue submitted by the user, whether it was POSTed or GETted.

Jojo::getFormData($var, $default = null)
  $var The name of the variable to look for
  $default The value to return if nothing was submitted

Example:
  $username = Jojo::getFormData('name', 'Jo Bloggs');

Jojo::getPost

Returns the valaue submitted by the user, on checks $_POST.

Jojo::getPost($var, $default = null)
  $var The name of the variable to look for
  $default The value to return if nothing was submitted

Example:
  $username = Jojo::getPost('name', 'Jo Bloggs');

Jojo::getGet

Returns the valaue submitted by the user, on checks $_GET.

Jojo::getGet($var, $default = null)
  $var The name of the variable to look for
  $default The value to return if nothing was submitted

Example:
  $username = Jojo::getGet('name', 'Jo Bloggs');

Jojo::noFormInjection

Takes steps to prevent form injection attempts. If attempts are suspected to be from an automated tool then the script stops and exits. If attempts are thought to be from a web browser then the attacker is redirected to a Wikipedia page on Email Injection.

  Jojo::noFormInjection()
  Returns
    Returns if there are no suspected attempts. Aborts if attempts found

Example:
  Jojo::noFormInjection()

URL Functions

A couple of functions that make URLs easier to work with.

Jojo::urlPrefix

If needed, returns the prefix to go in front of a URI. Use this when generaating URLs in side your plugins. This will ensure that URLs always have the correct prefix when used in a mied secure/innsecure environmennt.

If a URL is being gennerate on an http site and the target is a secure page then urlPrefix will return the secure prefix. If on a https page it would return a normal relative url etc.

Jojo::urlPrefix([$link2secure = false])
  $link2secure Set to true if the target page is a secure page.
Returns
  The prefix to put on the URI to give a full URL, possibly a emtpy string

Example:
  /* Create a url to get image of https connection */
  $secureImageUrl = Jojo::urlPrefix(true) . '/images/myspecialimage.jpg';

Jojo::cleanURL

Cleans up user provided string so it can be used as part of a URL by making lowercase, removing special chars etc */

Jojo::cleanURL($url)
  $url The sring to be cleaned
Returns
  The sanitised string.

Example:
  /* Create article uri */
  $uri = 'articles/' . $articleid . '/' . Jojo::cleanUrl($articletitle);

Jojo::getAdminUri

Takes a URI for a page in the admin area and changes the default 'admin/' prefix if the admin section has been moved.

Jojo::getAdminUri($uri)
  $uri The uri of an admin page, including the 'admin/' prefix
Return
  The uri for the admin page, taking into account the configured admin address.

Example:
  $customAdminPageLink = Jojo::urlPrefix() . Jojo::getAdminUri . '/admin/myadminnpage';

Jojo::getAdminUriReverse

The opposite of getAdminUri. Takes a uri that has the configured admin prefix and changes it back to 'admin/'.

Jojo::getAdminUriReverse($uri)
  $uri The uri of an admin page, including the prefix
Returns
  The original uri for the admin page, taking into account the configured admin address.

Example:
  $originalUri = Jojo::getAdminUriReverse(_SITEURI);

Jojo::addhttp

Adds http:// to a url if it's not already there. Good for user submitted urls.

Jojo::addhttp($url)
  $url The url to add the prefix to if missing.
Returns
  A full url including the http:// prefix.

Example:
  $userUrl = Jojo::addhttp($userUrl);

Jojo::relative2Absolute

Not really a url functino, more of a string function but fits here too.

Converts all relative urls in a piece of html to absolute links. It checks for urls in img and a tags. Usefull when taking user content (eg an article) annd creating and external version (eg RSS feed or Email) that require absolute urls.

Jojo::relative2Absolute($text, $base)
  $text The html to scan for urls.
  $base The base url for the links.
Returns
  The full text with the links changed.

Example:
  $articleEmailContent = Jojo::relative2Absolute($articleHTML, _SITEURL);

Jojo::checkUrlFormat

Simple regex check on the url format. Only checks http urls, not https or ftp etc.

Jojo::checkUrlFormat($url)
  $url The url to check
Returns
  true is the link appear to be a valid http url, else false.

Example:
  if (!Jojo::checkUrlFormat($userUrl)) {
    // get the user to supply a valid url
  }

Text Functions

Jojo::getMetaKeywords

Given a string of page content, this script will return a short list of words to use in the META KEYWORDS tag on your page.

Jojo::getMetaKeywords($content,[$maxLength = 30])
  $content The page content to scan through for keywords.
  $maxLenngth (optinoal) The maximum number of keywords to return.
Returns
  A space seperate string of keywords

Example:
  echo '<meta name="keywords" content="' . Jojo::getMetaKeywords($content, 20) . '" />';

Jojo::html2text

Converts html to a useful text equivalent. Usings asterisks for bullet point, foot notes for link targets etc.

This uses the Horde Text_Filter 'html2text' filter.

Jojo::html2text($html)
  $html The html to convert to text.
Returns
  A plain text representationn of the html

Example:
  $textEmail = Jojo::html2text($htmlEmail);

Jojo::bb2Html

Converts from bbcode to html

Jojo::bb2Html($bbcode, [$options = array()])
  $bbcode String containing the bbcode to convert
  $options (optional) associative array of options to control the connversion process
Returns
  A string containing the html representation of the bbcode

Example:
  $forumPostHtml = Jojo::bb2Html($rawForumPost);

Jojo::randomString

Returns a random string of characters

Jojo::randomString([$length = 16, [$characters = null]])
  $length (option) the length of the string to return
  $characters (optionnal) A string of characters to pick from. Defaults to lowercase + uppercase + digits
Returns
  A string of sepcified length

Example:
  $defaultPassword = Jojo::randomString(10);

Jojo::iExplode

A case insessitive version of explode().

Jojo::iExplode($delimiter, $string, [$limit])
  $delimiter The string to split by
  $string The string to be split up
  $limit (optional) The maxinum piece to break it into, otherwise unlimited.
Returns
  An array of pieces

Example:
  $pieces = Jojo::iExplode('jojo', "We keeps typing jojo and JOJO, and JoJo, but it should just be Jojo");

Options

These are the options that the user can configure in the admin interface. Use these functions to retreive and set the values of plugins.

Jojo::getOptions

Get an array of all options and their values from the database. Will return a cached array if available.

Jojo::getOptions([$forceclean = false])
  $forceclean (optional) Set to true to force a requery of values from the database
Returns
  A associative array of option_name => option_value

Example:
  $allOptions = Jojo::getOptions();

Jojo::getOption

Get the value of an option. Returning the cached value if available.

Jojo::getOption($name, [$default = null, [$forceclean = false]])
  $name      string  Name of the option
  $default   string  Value to return if the option is not found
  $foreclean boolean True will force all options to be refreshed from the database
Return
  The value of the option or the default value if the option was not found.

Example:
  $webmasterEmail = Jojo::getOption('webmasteraddress');

Jojo::setOption

Set the value of an option.

Jojo::setOption($name, $value)
  $name      string  Name of the option
  $value     string  Net value for the option

Example:
  Jojo::setOption('webmasteraddress', 'webmaster@example.com');

Jojo::removeOption

Remove an option from the database. Use this in uninstall scripts.

Jojo::removeOption($name)
  $name      string  Name of the option

Example:
  Jojo::removeOption('demooption');

Filters

Filters are Jojo's way of a plugin requesting to modify the value of a variable somewhere in the code. This allows for filtering of content going to the user or other structures like the sitemap or search results.

To use a filter, the plugin must register the filter, and specify the class annd function name to run on the content.
When the filter is called, the function gets passed the value, and must return the same or updated/filtered value.

Jojo::addFilter

Add a filter call back. Tell Jojo that a filter is to be run on a value at a certain point.

Jojo::addFilter($tag, $functionname, $pluginname, [$priority = 10])
  $tag          string Name of the filter to hook.
  $functionname string Name of function to add
  $pluginname   string Name of the plugin providing the function
  $priority     int    (optional) Prority of this filter, default is 10

Example:
  Jojo::addFilter('output', 'pageFilterFunction', 'myplugin_class');

Jojo::removeFilter

Remove a filter added prviously. Called with the same arguments as addfilter

Jojo::removeFilter($tag, $functionname, $pluginname, [$priority = 10])
  $tag          string Name of the filter to hook.
  $functionname string Name of function to add
  $pluginname   string Name of the plugin providing the function
  $priority     int    (optional) Prority of this filter, default is 10

Example:
  Jojo::removeFilter('output', 'pageFilterFunction', 'myplugin_class');

Jojo::applyFilter

Run registered filters on my piece of data.

Jojo::applyFilter($tag, $data, [$optionalArgs = null])
  $tag          string Name of the filter
  $data         string The data the filter has to work on
  $optionalArgs mixed  Any number of optional arguements to pass to the filter functions
Returns
  The filtered value, after all registered filters have made their changes, or the orginal value is no fiters are registered.

Example:
$outputHtml = Jojo::applyFilter('output', $outputHtml);

Hooks

Hooks are Jojo's way of for a plugin to request some code be run at certain points during the execution.

Jojo::addHook

Tell Jojo that a plugin has a hook to be run, and where the code is to run.

Jojo::addHook($tag, $functionname, $pluginname, [$priority = 10])
  $tag          string Name of the hook.
  $functionname string Name of the function to run
  $pluginname   string Name of the plugin class providing the function
  $priority     int    Priority of this hook, default is 10

Example:
Jojo::addHook('foot', 'debugmodestatus', 'jojo_core');

Jojo::removeHook

Remove a previously registered hook, must be called with the same argument as it was added.

Jojo::removeHook($tag, $functionname, $pluginname, [$priority = 10])
  $tag          string Name of the hook.
  $functionname string Name of the function to run
  $pluginname   string Name of the plugin class providing the function
  $priority     int    Priority of this hook, default is 10

Example:
Jojo::removeHook('foot', 'debugmodestatus', 'jojo_core');

Jojo::runHook

Runs a hook. Add these in you plugins as point where you think other code might want to do something. Hooks can also be added into smarty templates as smarty will call them.

Jojo::runHook($tag, [$optionalArgs = array()])
  $tag          string Name of the hook.
  $optionalArgs mixed  (optional) Any number of optional arguements to pass to the function

Example:
  Jojo::runHook('foot');

Date and Time Functions

Jojo::timer

Basic Script timer - to start timing, don't give any arguments. To stop timing, give start time as argument. Returns start time or total seconds elapsed

Jojo::timer([$starttime])
  $starttime  int (optional) Time the timer was started.
Returns
  The current time if no argument is passed, else the elapsed time if a start time is passed.

Example:
  $start = Jojo::timer();
  // Do time consuming thing
  $timeTaken = Jojo::timer($start);

Jojo::strToTimeUK

Convert to date sting into a unix timestamp. Assumes Kiwi date format first, dd/mm/yyyy. Then reverts to built in strtotime() if that doesn't work.

Jojo::strToTimeUK($dateString)
  $dateString string The date in text format to convert to a timestamp
Returns
  Unix timestamp on sucess or false on failure

Example:
  $mikesDOB = Jojo::strToTimeUK('02/04/1981');

Jojo::mysql2date

Convert a mysql date into a particular format

Valid formats are:
rss:      Wed, 02 Oct 2007 15:00:00 +0200
short:    2/10/2007
medium:   j M y
long:     j F Y
vlong:    D, j F Y
friendly: tomorrow, j M y

Jojo::mysql2date($mysqldate, [$format = 'short'])
  $mydqldate string The date from mysql
  $format    string (optional) The format to convert to.

Example:
$mikesDOBwithTimezone = Jojo::mysql2date('04021981', 'rss');

Jojo::relativeDate

Date formatting routine to give an easy to understand date to the user, giving only as much info as is needed
Coming Week = This Wednesday, 8:30am
Tomorrow = Tomorrow, 8:30am
Today (afternoon) = Today, 8:30am
Today (morning) = Today, 8:30 (no need to specify am or pm)
Yesterday = Yesterday, 8:30am
The last week = Last Monday, 8:30am
In the last month = Monday, Dec 12
In the same calendar year = Feb 23
Last year or prior = May 16, 2004
The full date / time should be given on the rollover, outside the scope of this function

Jojo::relativeDate($timestamp, [$showtime = true])
  $timestamp int     Unix time stamp to compare to now
  $showtime  boolean (optional) Show the time in the result
Returns
  String with the relative date.

Example:
  $whenIsMikesDOB = Jojo::relativeDate(Jojo::strToTimeUK('02/04/1981'), false);

Redirection functons

Used to redirect the user to different pages

Jojo::redirect

Performs a redirect

Jojo::redirect($url, [$type = 301])
  $url  string The full url to redirect the browser too
  $type int    (optional) The type o redirect to do.

Example:
  if (!$oldEnough) {
    Jojo::redirect('http://www.disneyland.com');
  }

Jojo::redirectBack

Redirects the user back to where they came from, or the homepage if they came via an external link

Jojo::redirectBack()

Example:
  // Thanks for logging in, now go back where you came from
  Jojo::redirectBack()

Email Functions

Jojo::checkEmailFormat

A regex to check the format of the email address conforms to the commonnly used one.

Jojo::checkEmailFormat($email)
  $email string The email address to check
Returns
  true if the email address appears to be valid

Example:
  if (!Jojo::checkEmailForm($userEmailAddress)) {
    // User's email address looks invalid ask again
  }

Jojo::obfuscateEmail

Takes an email address user@domain.co.nz
Splits into 3 parts
$addressname = user (just the first part of the address)
$addressdomain1 = niamod (the first part of the domain name reversed)
$addressdomain2 = co.nz (the remaining part of the domain name, without the first dot)
Final output looks like this...
<a href="/contact" onmouseover="this.href=xyz('co.nz','user','niamod');">

Jojo::obfuscateEmail($address)
  $address string The email address to obfuscate
Return
  The full html for the a link, minus the conetent and the close tag.

Example:
  echo Jojo::obfuscateEmail('mikec@jojocms.org') . 'Email Mike</a>';

Jojo::emailFooter

Returns a block of text that is useful for adding to admin emails

Jojo::emailFooter()
Returns
  A string to add to the end of an email.

Example:
 $emailContent = "User bought your product\n" . Jojo::emailFooter();

Jojo::simpleMail

Send an email.

Jojo::simpleMail($toname, $toaddress, $subject, $message, [$fromname=_FROMNAME], [$fromaddress=_FROMADDRESS])
  $tonname     string The name of the person to send the email to
  $toaddress   string The email address of the recipient
  $subject     string Subject for the email
  $message     string The conntent of the email
  $fromname    string (optional) The name of the sender
  $fromaddress string (optional) The email address of the sender

Jojo Functions

These are functions that are mainly used internally but you may find them useful.

Jojo::parsePage

Parses a URI and attempts to match that to a page id. This could be usefull in the setup.php for your plugin so it can add a child to a particular page, or detecting if a page exists before it creates one in the same location.

Jojo::parsepage($uri)
  $uri string the Uri to match
Returns
  Page id or false on not found.

Example:
  $adminEditPageId = Jojo::parsepage('admin/edit/page');

Jojo::ctrlF5

Looks at the request headers to see if the user is doing a force refresh.

Jojo::ctrlF5()
Returns
  true if a force refresh has been requested.

Example:
  if ($cachedCopyExists && !Jojo::ctrlF5()) {
    // return the cached content
  } else {
    // generate it from scratch
    // save it to the cache
    // return the fresh content
  }

Jojo::getMultiLanguageData

Return a bunch of information about the languages that have been configured in Jojo.

Jojo::getMultiLanguageData()
Returns
  Array of stuff

Example:
// Get langauge data
$language = 'en';
$mldata = Jojo::getMultiLanguageData();
$navigationRoot = $mldata['roots'][$language];
$homepageId     = $mldata['homes'][$language];
$urlPrefix      = $mldata['longcodes'][$language];
// Use language data to create a full url in a multilangauge ennvironment
if (_MULTILANGUAGE) {
  $url = Jojo::urlPrefix() . '/' . $urlPreix . $uri;
} else {
  $url = Jojo::urlPrefix() . '/' . $uri;
}