Core API

3.2.2. Functions typically used and nice to know

These functions are generally just nice to know. They provide functionality which you will often need in TYPO3 applications and therefore they will save you time and make your applications easier for others to understand as well since you use commonly known functions.

Please take time to learn these functions!

Function

Comments

t3lib_div::inList

Check if an item exists in a comma-separated list of items.

 

  if (t3lib_div::inList('gif,jpg,png',$ext)) {

t3lib_div::intInRange

Forces the input variable (integer) into the boundaries of $min and $max.

 

  t3lib_div::intInRange($row['priority'],1,5);

t3lib_div::isFirstPartOfStr

Returns true if the first part of input string matches the second argument.

 

  t3lib_div::isFirstPartOfStr($path,PATH_site);

t3lib_div::testInt

Tests if the input is an integer.

t3lib_div::shortMD5

t3lib_div::md5int

Creates partial/truncated MD5 hashes. Useful when a 32 byte hash is too long or you rather work with an integer than a string.

 

t3lib_div::shortMD5() - Creates a 10 byte short MD5 hash of input string

 

  $addQueryParams.= '&cHash='.t3lib_div::shortMD5(serialize($pA));

t3lib_div::md5int() - Creates an integer from the first 7 hex chars of the MD5 hash string

 

  'mpvar_hash' => t3lib_div::md5int($GLOBALS['TSFE']->MP),

t3lib_div::deHSCentities

t3lib_div::htmlspecialchars_decode

Reverse conversions of htmlspecialchars()

 

t3lib_div::deHSCentities() - Re-converts HTML entities if they have been converted by htmlspecialchars(). For instance "&" which should stay "&". Or "Ӓ" to "Ӓ". Or "" to ""

 

  $value = t3lib_div::deHSCentities(htmlspecialchars($value));

t3lib_div::htmlspecialchars_decode() - Inverse version of htmlspecialchars()

t3lib_div::modifyHTMLColor

t3lib_div::modifyHTMLColorAll

Modifies the RGB values of an 6-digit HTML hex color by adding/subtracting. Useful for increasing or decreasing brightness of colors.

 

  t3lib_div::modifyHTMLColor('#cca823',+10,+10,+10)
  t3lib_div::modifyHTMLColorAll($this->doc->bgColor,-20);

t3lib_div::formatSize

Formats a number of bytes as Kb/Mb/Gb for visual output.

 

  $size = ' ('.t3lib_div::formatSize(filesize($v)).'bytes)';

t3lib_div::validEmail

Evaluates a string as an email address.

 

  if ($email && t3lib_div::validEmail($email))    {

t3lib_div::trimExplode

t3lib_div::intExplode

t3lib_div::revExplode

Various flavours of exploding a string by a token.

 

t3lib_div::trimExplode() - Explodes a string by a token and trims the whitespace away around each item. Optionally any zero-length elements are removed. Very often used to explode strings from configuration, user input etc. where whitespace can be expected between values but is insignificant.

 

  array_unique(t3lib_div::trimExplode(',',$rawExtList,1));
  t3lib_div::trimExplode(chr(10),$content);

t3lib_div::intExplode() - Explodes a by a token and converts each item to an integer value. Very useful to force integer values out of a value list, for instance for an SQL query.

 

  // Make integer list
  implode(t3lib_div::intExplode(',',$row['subgroup']),',');

t3lib_div::revExplode() - Reverse explode() which allows you to explode a string into X parts but from the back of the string instead.

 

  $p=t3lib_div::revExplode('/',$path,2);

t3lib_div::array_merge_recursive_overrule

t3lib_div::array_merge

Merging arrays with fixes for "PHP-bugs"

 

t3lib_div::array_merge_recursive_overrule() - Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar the values in the first array ($arr0) with the values of the second array ($arr1). In case of identical keys, ie. keeping the values of the second.

 

t3lib_div::array_merge() - An array_merge function where the keys are NOT renumbered as they happen to be with the real php-array_merge function. It is "binary safe" in the sense that integer keys are overridden as well.

t3lib_div::array2xml

t3lib_div::xml2array

Serialization of PHP variables into XML.

 

These functions are made to serialize and unserialize PHParrays to XML files. They are used for the FlexForms content in TYPO3, Data Structure definitions etc. The XML output is optimized for readability since associative keys are used as tagnames. This also means that only alphanumeric characters are allowed in the tag names and only keys not starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem. Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats). The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string. The PHP variable type of the data is preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set.

 

t3lib_div::array2xml() - Converts a PHP array into an XML string.

 

  t3lib_div::array2xml($this->FORMCFG['c'],'',0,'T3FormWizard');

t3lib_div::xml2array() - Converts an XML string to a PHP array. This is the reverse function of array2xml()

 

  if ($this->xmlStorage)    {
      $cfgArr = t3lib_div::xml2array($row[$this->P['field']]);
  }

t3lib_div::getURL

t3lib_div::writeFile

Reading / Writing files

 

t3lib_div::getURL() - Reads the full content of a file or URL. Used throughout the TYPO3 sources.

 

  $templateCode = t3lib_div::getURL($templateFile);

t3lib_div::writeFile() - Writes a string into an absolute filename.

 

  t3lib_div::writeFile($extDirPath.$theFile,$fileData['content']);

t3lib_div::split_fileref

Splits a reference to a file in 5 parts. Alternative to "path_info" and fixes some "PHP-bugs" which makes page_info() unattractive at times.

t3lib_div::get_dirs

t3lib_div::getFilesInDir

t3lib_div::getAllFilesAndFoldersInPath

t3lib_div::removePrefixPathFromList

Read content of file system directories.

 

t3lib_div::get_dirs() - Returns an array with the names of folders in a specific path

 

  if (@is_dir($path))    {
      $directories = t3lib_div::get_dirs($path);
      if (is_array($directories))    {
          foreach($directories as $dirName)    {
              ...
          }
      }
  }

t3lib_div::getFilesInDir() - Returns an array with the names of files in a specific path

 

  $sFiles = t3lib_div::getFilesInDir(PATH_typo3conf,'',1,1);
  $files = t3lib_div::getFilesInDir($dir,'png,jpg,gif');

t3lib_div::getAllFilesAndFoldersInPath() - Recursively gather all files and folders of a path.

t3lib_div::removePrefixPathFromList() - Removes the absolute part of all files/folders in fileArr (useful for post processing of content from t3lib_div::getAllFilesAndFoldersInPath())

 

      // Get all files with absolute paths prefixed:
  $fileList_abs = 
      t3lib_div::getAllFilesAndFoldersInPath(array(),$absPath,'php,inc');
   
      // Traverse files and remove abs path from each (becomes relative)
  $fileList_rel = 
      t3lib_div::removePrefixPathFromList($fileList_abs,$absPath);

t3lib_div::implodeArrayForUrl

Implodes a multidimentional array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)

 

  $pString = t3lib_div::implodeArrayForUrl('',$params);

t3lib_div::get_tag_attributes

t3lib_div::implodeAttributes

Works on HTML tag attributes

 

t3lib_div::get_tag_attributes() - Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z

 

  $attribs = t3lib_div::get_tag_attributes('<'.$subparts[0].'>');

t3lib_div::implodeAttributes() - Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)

 

  $tag = '<img '.t3lib_div::implodeAttributes($attribs,1).' />';

t3lib_div::resolveBackPath

Resolves "../" sections in the input path string. For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"

t3lib_div::callUserFunction

t3lib_div::getUserObj

General purpose functions for calling user functions (creating hooks).

See the chapter about Hooks in this document for detailed description of these functions.

 

t3lib_div::callUserFunction() - Calls a userdefined function/method in class. Such a function/method should look like this: "function proc(&$params, &$ref) {...}"

 

  function procItems($items,$iArray,$config,$table,$row,$field) {
      global $TCA;
      $params=array();
      $params['items'] = &$items;
      $params['config'] = $config;
      $params['TSconfig'] = $iArray;
      $params['table'] = $table;
      $params['row'] = $row;
      $params['field'] = $field;
   
      t3lib_div::callUserFunction(
          $config['itemsProcFunc'],
          $params,
          $this
      );
      return $items;
  }

t3lib_div::getUserObj() - Creates and returns reference to a user defined object.

 

  $_procObj = &t3lib_div::getUserObj($_classRef);
  $_procObj->pObj = &$this;
  $value = $_procObj->transform_rte($value,$this);

t3lib_div::linkThisScript

Returns the URL to the current script. You can an array with associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.

t3lib_div::plainMailEncoded

t3lib_div::quoted_printable

Mail sending functions

 

t3lib_div::plainMailEncoded() - Simple substitute for the PHP function mail() which allows you to specify encoding and character set.

t3lib_div::quoted_printable() - Implementation of quoted-printable encode.

t3lib_BEfunc::getRecord

t3lib_BEfunc::getRecordsByField

Functions for selecting records by uid or field value.

 

t3lib_BEfunc::getRecord() - Gets record with uid=$uid from $table

 

    // Getting array with title field from a page:
  t3lib_BEfunc::getRecord('pages',intval($row['shortcut']),'title');
   
    // Getting a full record with permission WHERE clause
  $pageinfo = t3lib_BEfunc::getRecord(
          'pages',
          $id,
          '*',
          ($perms_clause ? ' AND '.$perms_clause : '')
      );

t3lib_BEfunc::getRecordsByField() - Returns records from table, $theTable, where a field ($theField) equals the value, $theValue

 

      // Checking if the id-parameter is an alias.
  if (!t3lib_div::testInt($id))    {
      list($idPartR) = 
          t3lib_BEfunc::getRecordsByField('pages','alias',$id);
      $id = intval($idPartR['uid']);
  }

t3lib_BEfunc::getRecordPath

Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"

 

  $label = t3lib_BEfunc::getRecordPath(
          intval($row['shortcut']),
          $perms_clause,
          20
      );

t3lib_BEfunc::readPageAccess

Returns a page record (of page with $id) with an extra field "_thePath" set to the record path if the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.

 

  $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
  $pageinfo = t3lib_BEfunc::readPageAccess($id,$perms_clause);

t3lib_BEfunc::date

t3lib_BEfunc::datetime

t3lib_BEfunc::calcAge

Date/Time formatting functions using date/time format from TYPO3_CONF_VARS.

 

t3lib_BEfunc::date() - Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])

 

  t3lib_BEfunc::datetime($row["crdate"])

t3lib_BEfunc::datetime() - Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])

 

  t3lib_BEfunc::datetime($row["item_mtime"])

t3lib_BEfunc::calcAge() - Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.

 

  $agePrefixes = ' min| hrs| days| yrs';
  t3lib_BEfunc::calcAge(time()-$row['crdate'], $agePrefixes);

t3lib_BEfunc::titleAttribForPages

Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.

 

  $out = t3lib_BEfunc::titleAttribForPages($row,'',0);
  $out = t3lib_BEfunc::titleAttribForPages($row,'1=1 '.$this->clause,0);

t3lib_BEfunc::thumbCode

t3lib_BEfunc::getThumbNail

Returns image tags for thumbnails

 

t3lib_BEfunc::thumbCode() - Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field. Slightly advanced. It's more likely you will need t3lib_BEfunc::getThumbNail() to do the job.

t3lib_BEfunc::getThumbNail() - Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)

 

  t3lib_BEfunc::getThumbNail(
      $this->doc->backPath.'thumbs.php',
      $filepath,
      'hspace="5" vspace="5" border="1"'
  );

t3lib_BEfunc::storeHash

t3lib_BEfunc::getHash

Get/Set cache values.

 

t3lib_BEfunc::storeHash() - Stores the string value $data in the 'cache_hash' table with the hash key, $hash, and visual/symbolic identification, $ident

t3lib_BEfunc::getHash() - Retrieves the string content stored with hash key, $hash, in cache_hash

 

Example of how both functions are used together; first getHash() to fetch any possible content and if nothing was found how the content is generated and stored in the cache:

 

      // Parsing the user TS (or getting from cache)
  $userTS = implode($TSdataArray,chr(10).'[GLOBAL]'.chr(10));
  $hash = md5('pageTS:'.$userTS);
  $cachedContent = t3lib_BEfunc::getHash($hash,0);
  $TSconfig = array();
  if (isset($cachedContent))    {
      $TSconfig = unserialize($cachedContent);
  } else {
      $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
      $parseObj->parse($userTS);
      $TSconfig = $parseObj->setup;
      t3lib_BEfunc::storeHash($hash,serialize($TSconfig),'IDENT');
  }

t3lib_BEfunc::getRecordTitle

t3lib_BEfunc::getProcessedValue

Get processed / output prepared value from record

 

t3lib_BEfunc::getRecordTitle() - Returns the "title" value from the input records field content.

 

  $line.= t3lib_BEfunc::getRecordTitle('tt_content',$row,1);

t3lib_BEfunc::getProcessedValue() - Returns a human readable output of a value from a record. For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.

 

  $outputValue = nl2br(
      htmlspecialchars(
          trim(
              t3lib_div::fixed_lgd_cs(
                  t3lib_BEfunc::getProcessedValue(
                      $table,
                      $fieldName,
                      $row[$fieldName]
                  ),
                  250
              )
          )
      )
  );

t3lib_BEfunc::getFileIcon

Returns file icon name (from $FILEICONS) for the fileextension $ext

 

  $fI = pathinfo($filePath);
  $fileIcon = t3lib_BEfunc::getFileIcon(strtolower($fI['extension']));
  $fileIcon = '<img'.
      t3lib_iconWorks::skinImg(
          $this->backPath,
          'gfx/fileicons/'.$fileIcon,
          'width="18" height="16"'
      ).' alt="" />';

t3lib_BEfunc::getPagesTSconfig

Returns the Page TSconfig for page with id, $id.

This example shows how an object path, "mod.web_list" is extracted from the Page TSconfig for page $id:

 

  $modTSconfig = $GLOBALS["BE_USER"]->getTSConfig(
      "mod.web_list",
      t3lib_BEfunc::getPagesTSconfig($id)
  );

t3lib_extMgm::addTCAcolumns

Adding fields to an existing table definition in $TCA

For usage in "ext_tables.php" files

 

      // tt_address modified
  t3lib_div::loadTCA('tt_address');
  t3lib_extMgm::addTCAcolumns('tt_address',array(
           'module_sys_dmail_category' => 
              Array('config'=>array('type'=>'passthrough')),
          'module_sys_dmail_html' => 
              Array('config'=>array('type'=>'passthrough'))
  ));

t3lib_extMgm::addToAllTCAtypes

Makes fields visible in the TCEforms, adding them to the end of (all) "types"-configurations

For usage in "ext_tables.php" files

 

  t3lib_extMgm::addToAllTCAtypes(
      "fe_users",
      "tx_myext_newfield;;;;1-1-1, tx_myext_another_field"
  );

t3lib_extMgm::allowTableOnStandardPages

Add tablename to default list of allowed tables on pages (in $PAGES_TYPES)

For usage in "ext_tables.php" files

 

  t3lib_extMgm::allowTableOnStandardPages('tt_board');

t3lib_extMgm::addModule

Adds a module (main or sub) to the backend interface

For usage in "ext_tables.php" files

 

  t3lib_extMgm::addModule(
      'user',
      'setup',
      'after:task',
      t3lib_extMgm::extPath($_EXTKEY).'mod/'
  );
   
  t3lib_extMgm::addModule(
      'tools',
      'txcoreunittestM1',
      '',
      t3lib_extMgm::extPath($_EXTKEY).'mod1/'
  );

t3lib_extMgm::insertModuleFunction

Adds a "Function menu module" ('third level module') to an existing function menu for some other backend module

For usage in "ext_tables.php" files

 

  t3lib_extMgm::insertModuleFunction(
      'web_func',
      'tx_cmsplaintextimport_webfunc',
      t3lib_extMgm::extPath($_EXTKEY).
          'class.tx_cmsplaintextimport_webfunc.php',
      'LLL:EXT:cms_plaintext_import/locallang.php:menu_1'
  );

t3lib_extMgm::addPlugin

Adds an entry to the list of plugins in content elements of type "Insert plugin"

For usage in "ext_tables.php" files

 

  t3lib_extMgm::addPlugin(
      Array(
          'LLL:EXT:newloginbox/locallang_db.php:tt_content.list_type1', 
          $_EXTKEY.'_pi1'
      ),
      'list_type'
  );

t3lib_extMgm::addPItoST43

Add PlugIn to Static Template #43

When adding a frontend plugin you will have to add both an entry to the TCA definition of tt_content table AND to the TypoScript template which must initiate the rendering. Since the static template with uid 43 is the "content.default" and practically always used for rendering the content elements it's very useful to have this function automatically adding the necessary TypoScript for calling your plugin. It will also work for the extension "css_styled_content"

 

For usage in "ext_locallang.php" files

 

  t3lib_extMgm::addPItoST43($_EXTKEY);

 

To top


Valid XHTML 1.0!