Login / Status
developer.Resource
Home . Documentation . Document Library . Core Documentation
Sponsors
hosted by punkt.deTYPO3 and Open Source Magazine

3.2. General functions

There are a few core classes in TYPO3 which contain general functionality. These classes are (typically) just a collection of individual functions you call non-instantiated, like [class name]::[method name].

These are the most important classes to know about in TYPO3:

Class name:

Description:

Usage:

t3lib_DB

Database Abstraction Base API

All access to the database must go through this object. That is the first step towards DBAL compliance in your code. The class contains MySQL wrapper functions which can almost be search/replaced with your existing calls.

$GLOBALS['TYPO3_DB'] in both frontend and backend

t3lib_cs

Character Set handling API

Contains native PHP code to handle character set conversion based on charset tables from Unicode.org. It is not certain that you will have to use this class directly but if you need to do charset conversion at any time you should use this class.

In backend, $GLOBALS['LANG']->csConvObj

In frontend, $GLOBALS['TSFE']->csConvObj

t3lib_div

General Purpose Functions

A collection of multi-purpose PHP functions. Some are TYPO3 specific but not all.

t3lib_div::

(Non-instantiated!)

t3lib_BEfunc

Backend Specific Functions

Contains functions specific for the backend of TYPO3. You will typically need these when programming backend modules or other backend functionality.

This class is NOT available in the frontend!

t3lib_BEfunc::

(Non-instantiated!)

t3lib_extMgm

Extension API functions

Functions for extensions to interface with the core system. Many of these functions are used in ext_localconf.php and ext_tables.php files of extensions. They let extensions register their features with the system.

See extension programming tutorials for more details.

t3lib_extMgm::

(Non-instantiated!)

t3lib_iconWorks

Icons / Part of skinning API

Contains a few functions for getting the right icon for a database table record or the skinned version of any other icon.

This class is NOT available in the frontend!

t3lib_iconWorks::

(Non-instantiated!)

template

Backend Template Class

Contains functions for producing the layout of backend modules, setting up HTML headers, wrapping JavaScript sections correctly for XHTML etc.

$GLOBALS['TBE_TEMPLATE'] or

$GLOBALS['SOBE'] or

$this->doc (inside of Script Classes)

These classes are always included and available in the TYPO3 backend and frontend (except "t3lib_BEfunc" and "t3lib_iconWorks").

The following pages will list methods from these classes in priority of importance. You should at least acquaint yourself with all High-priority functions since these are a part of the Coding Guidelines requirements. In addition you might like to know about other functions which are very often used since they might be very helpful to you (they were to others!).

High priority functions (CGL requirements)

The functions listed in this table is of high priority. Generally they provide APIs to functionality which TYPO3 should always handle in the same way. This will help you to code TYPO3 applications with less bugs and greater compatibility with various system conditions it will run under.

Remember, this list only serves to point out important functions! The real documentation is found in the source scripts. The comments given is only a supplement to that.

Function

Comments

t3lib_div::_GP

t3lib_div::_GET

t3lib_div::_POST

Getting values from GET or POST vars

APIs for getting values in GET or POST variables with slashes stripped regardless of PHP environment. Always use these functions instead of direct access to $_GET, $_POST or $HTTP_GET_VARS/$HTTP_POST_VARS.

t3lib_div::_GP($varname) will give you the value of either the GET or POST variable with priority to POST if present. This is useful if you don't know whether a parameter is passed as GET or POST. Many scripts will use this function to read variables in the init function:

    // Setting GPvars:

$this->file = t3lib_div::_GP('file');

$this->size = t3lib_div::_GP('size');

t3lib_div::_GET() will give you GET vars. For security reasons you should use this if you know your parameters are passed as GET variables. This example gives you the whole $_GET array:

$params = t3lib_div::_GET();

t3lib_div::POST() will give you POST variables. Works like t3lib_div::_GET(). For security reasons you should use this if you know your parameters are passed as POST variables.

This example gives you the content of the POST variable TSFE_ADMIN_PANEL, for instance it could come from a form field like "<input name="TSFE_ADMIN_PANEL[command]" ..../>

$input = t3lib_div::_POST('TSFE_ADMIN_PANEL');

t3lib_div::makeInstance

t3lib_div::makeInstanceClassName

Creating objects

Factory APIs for creating an object instance of a class name (or getting the correct class name to instantiate). These functions make sure the "XCLASS extension" principle can be used on (almost) any class in TYPO3. You must use either of these functions for creating objects in TYPO3.

Examples:

// Making an instance of class "t3lib_TSparser":

$parseObj = t3lib_div::makeInstance('t3lib_TSparser');

// Make an object with an argument passed to the constructor:

$className=t3lib_div::makeInstanceClassName("t3lib_xml");

$xmlObj = new $className("typo3_export");

t3lib_div::getIndpEnv

Environment-safe server  and environment variables.

API function for delivery of system and environment variables on any web-server brand and server OS. Always use this API instead of $_ENV/$_SERVER or getenv() if possible.

Examples:

if (t3lib_div::getIndpEnv('HTTP_ACCEPT_LANGUAGE') == $test)...

if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $pcs[1]))...

$prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');

$redirectTo = t3lib_div::getIndpEnv('TYPO3_SITE_URL').$redirectTo;

if (!t3lib_div::getIndpEnv('TYPO3_SSL')) ...

t3lib_div::loadTCA

Loading full table description into $TCA

If you want to access or change any part of the $TCA array for a table except the ['ctrl'] part then you should call this function first. The $TCA might not contain the full configuration for the table (depending on configuration of the table) and to make sure it is loaded if it isn't already you call this function.

Examples of PHP code which traverses the ['columns'] part of an unknown  table and loads the table before.

t3lib_div::loadTCA($this->table);

reset($TCA[$this->table]["columns"]);

while(list($fN)=each($TCA[$this->table]["columns"]))    {

    $fieldListArr[]=$fN;

}

t3lib_BEfunc::deleteClause

Get SQL WHERE-clause  filtering "deleted" records

Tables from $TCA might be configured to set an integer flag when deleted instead of being physically deleted from the database. In any case records with the deleted-flag set must never be selected in TYPO3. To make sure you never make that mistake always call this function which will pass you a SQL WHERE-clause like " AND deleted=0" if the table given as argument has been configured with a deleted-field.

(Notice: In the frontend this is build into the "enableFields()" function.)

Example:

$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(

                'pid,uid,title,TSconfig,is_siteroot,storage_pid',

                'pages',

                'uid='.intval($uid).' '.

                    t3lib_BEfunc::deleteClause('pages').' '.

                    $clause    

            );

t3lib_extMgm::isLoaded

Returns true if an extension is loaded (installed)

If you need to check if an extension is loaded in a TYPO3 installation simply use this function to ask for that.

Example:

  // If the extension "sys_note" is loaded, then...

if (t3lib_extMgm::isLoaded('sys_note'))    ...

  // If the "cms" extension is NOT loaded, return false

if (!t3lib_extMgm::isLoaded('cms'))    return;

  // Check if the "indexed_search" extension is loaded. If not, exit PHP!

t3lib_extMgm::isLoaded("indexed_search",1);

  // Assign value "popup" if extension "tsconfig_help" is loaded

$type = t3lib_extMgm::isLoaded('tsconfig_help')?'popup':'';

t3lib_extMgm::extPath

t3lib_extMgm::extRelPath

t3lib_extMgm::siteRelPath

Get file path to an extension directory

If you need to get the absolute or relative filepaths to an extension you should use these functions. Extension can be located in three different positions in the filesystem whether they are local, global or system extensions. These functions will always give you the right path.

Examples:

  // Include a PHP file from the extension "extrep_wizard".

  // t3lib_extMgm::extPath() returns the absolute path to the

  // extension directory.

require_once(

    t3lib_extMgm::extPath('extrep_wizard').

    'pi/class.tx_extrepwizard.php'

);

  // Get relative path (relative to PATH_typo3) to an icon (backend)

$icon = t3lib_extMgm::extRelPath("tt_rating")."rating.gif";

  // Get relative path (relative to PATH_site) to an icon (frontend)

return '<img src="'.

    t3lib_extMgm::siteRelPath("indexed_search").'pi/res/locked.gif"

    ... />';

t3lib_div::getFileAbsFileName

t3lib_div::validPathStr

t3lib_div::isAbsPath

t3lib_div::isAllowedAbsPath

t3lib_div::fixWindowsFilePath

Evaluate files and directories for security reasons

When you allow references to files to be inputted from users there is always the risk that they try to cheat the system to include something else than intended. These functions makes it easy for you to evaluate filenames for validity before reading, writing or including them.

Here the functions are described in order of importance:

t3lib_div::getFileAbsFileName() - Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns false if checks failed. Does not check if the file exists.

  // Getting absolute path of a temporary file:

$cacheFile = t3lib_div::getFileAbsFileName('typo3temp/tempfile.tmp');

  // Include file if it exists:

$file = t3lib_div::getFileAbsFileName($fileRef);

if (@is_file($file))    {

    include($file);

}

t3lib_div::validPathStr() - Checks for malicious file paths. Returns true if no '//', '..' or '\' is in the $theFile. This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.

    // If the path is true and validates as a valid path string:

if ($path && t3lib_div::validPathStr($path))    ...

t3lib_div::isAbsPath() - Checks if the input path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.

  // Returns relative filename for icon:

if (t3lib_div::isAbsPath($Ifilename))    {

    $Ifilename = '../'.substr($Ifilename,strlen(PATH_site));

}

t3lib_div::isAllowedAbsPath() - Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath. Contrary to t3lib_div::getFileAbsFileName() this function can also validate files in filemounts outside the web-root of the installation, but this is rarely used!

if (@file_exists($path) && t3lib_div::isAllowedAbsPath($path))    {

    $fI = pathinfo($path);

         ....

t3lib_div::fixWindowsFilePath() - Fixes a path for Windows-backslashes and reduces double-slashes to single slashes

t3lib_div::mkdir

Creates directory

One would think that creating directories is one thing you can do directly with PHP. Well, it turns out to be quite error-prone if it should be compatible with Windows servers and safe-mode at the same time. So TYPO3 offers a substitution function you should always use.

Example:

$root.=$dirParts.'/';

if (!is_dir($extDirPath.$root))    {

    t3lib_div::mkdir($extDirPath.$root);

    if (!@is_dir($extDirPath.$root))    {

        return 'Error: The directory "'.

                $extDirPath.$root.

                '" could not be created...';

    }

}

t3lib_div::upload_to_tempfile

t3lib_div::unlink_tempfile

t3lib_div::tempnam

Functions for handling uploads and temporary files

You need to use these functions for managing uploaded files you want to access as well as creating temporary files within the same session. These functions are safe_mode and open_basedir compatible which is the main point of you using them!

t3lib_div::upload_to_tempfile() - Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it under safe_mode. Remember to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are not automatically deleted in PATH_site."typo3temp/"!

t3lib_div::unlink_tempfile() - Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input. The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe. Use this after upload_to_tempfile() or tempnam() from this class!

This example shows how to handle an uploaded file you just want to read and then delete again:

    // Read uploaded file:

$uploadedTempFile = t3lib_div::upload_to_tempfile(

    $GLOBALS['HTTP_POST_FILES']['upload_ext_file']['tmp_name']

);

$fileContent = t3lib_div::getUrl($uploadedTempFile);

t3lib_div::unlink_tempfile($uploadedTempFile);

t3lib_div::tempnam() - Create temporary filename (creates file with unique file name). This function should be used for getting temporary filenames - will make your applications safe for "open_basedir = on". Remember to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()

In the following example it is shown how two temporary filenames are created for being processed with an external program (diff) after which they are deleted again:

    // Create file 1 and write string

$file1 = t3lib_div::tempnam('diff1_');

t3lib_div::writeFile($file1,$str1);

    // Create file 2 and write string

$file2 = t3lib_div::tempnam('diff2_');

t3lib_div::writeFile($file2,$str2);

    // Perform diff.

$cmd = $GLOBALS['TYPO3_CONF_VARS']['BE']['diff_path'].

           ' '.$this->diffOptions.' '.$file1.' '.$file2;

exec($cmd,$res);

unlink($file1);

unlink($file2);

t3lib_div::fixed_lgd_cs

Truncating a string for visual display, observing the character set (backend only)

This function allows you to truncate a string from eg. "Hello World" to "Hello Wo..." so for example very long titles of records etc. will not break the visual appearance of your backend modules.

Since text strings cannot be cropped at any byte if the character set is utf-8 or another multibyte charset this function will process the string assuming the character set to be the one used in the backend.

It is recommended to use $BE_USER->uc['titleLen'] for the length parameter.

  // Limits Record title to 30 chars

t3lib_div::fixed_lgd_cs($thisRecTitle,30);

  // Limits string to title-length configured for backend user:

$title = t3lib_div::fixed_lgd_cs(

             $row['title'],

             $this->BE_USER->uc['titleLen']

);

t3lib_div::formatForTextarea

Preparing a string for output between <textarea> tags.

Use this function to prepare content for <textarea> tags. Then you will avoid extra / stripped whitespace when the form is submitted multiple times.

    // Create item:

$item = '

    <textarea>'.

    t3lib_div::formatForTextarea($value).

    '</textarea>';

t3lib_div::locationHeaderUrl

Preparing a URL for a HTTP location-header

Use this to prepare redirection URLs for location-headers. It will convert the URL to be absolute. This is needed for some webservers (Windows) while unix servers will work fine without. So to honor compatibility, use this function like this:

Header('Location: '.t3lib_div::locationHeaderUrl($this->retUrl));

exit;

t3lib_BEfunc::getFuncMenu

t3lib_BEfunc::getFuncCheck

Create "Function menu" in backend modules

Creates a selector box menu or checkbox with states automatically saved in the backend user session. Such a function menu could look like this:

The selector box is made by this function call. It sets the ID variable (zero if not available), the GET var name, "SET[mode]", the current value from MOD_SETTINGS and finally the array of menu options, MOD_MENU['mode']:

t3lib_BEfunc::getFuncMenu(

    $this->id,

    'SET[mode]',

    $this->MOD_SETTINGS['mode'],

    $this->MOD_MENU['mode']

)

Prior to making the menu it is required that the MOD_MENU array is set up with an array of options. This could look like this (getting some labels from the "locallang" system). In addition the incoming "SET" GET-variable must be registered in the session which is also done in this listing:

$this->MOD_MENU = array(

    'mode' => array(

        0 => $LANG->getLL('user_overview'),

        'perms' => $LANG->getLL('permissions')

    )

);    // Clean up settings:$this->MOD_SETTINGS = t3lib_BEfunc::getModuleData(                        $this->MOD_MENU,                        t3lib_div::_GP('SET'),

                        $this->MCONF['name']

                    );

You can have a checkbox as well:

Then the function call looks like this. Notice the fourth argument is gone because a checkbox does not have any information about options like a selector box would have.

t3lib_BEfunc::getFuncCheck(

    0,

    'SET[own_member_only]',

    $this->MOD_SETTINGS['own_member_only']

);

For checkboxes you must set the key in the MOD_MENU array as well. Otherwise the values are not registered in the user session:

'own_member_only' => '',

t3lib_BEfunc::editOnClick

Create onclick-JavaScript code that links to edit form for a record

Use this function to create a link to the "alt_doc.php" core script which can generate editing forms for any $TCA configured record. The actual editing command is passed to "alt_doc.php" through the GET parameter "&edit".

See the section with "Various examples" for detailed examples of this!

Example:

$params='&edit[pages]['.$row['uid'].']=edit';

$link = '<a href="#" onclick="'.

            htmlspecialchars(t3lib_BEfunc::editOnClick($params,'',-1)).

            '">Edit</a>';

t3lib_BEfunc::viewOnClick

Create onclick-JavaScript code that opens a page in the frontend

It will detect the correct domain name if needed and provide the link with the right back path. Also it will re-use any window already open.

    // "View page" link is added:

$link = '<a href="#" onclick="'.

        htmlspecialchars(t3lib_BEfunc::viewOnClick(

            $pageId,

            $GLOBALS['BACK_PATH'],

            t3lib_BEfunc::BEgetRootLine($pageId)

        )).'">View page</a>';

$GLOBALS['TBE_TEMPLATE']->

issueCommand

Creates a link to "tce_db.php" (with a command like copy, move,delete for records)

Creates a URL to the TYPO3 Core Engine interface provided from the core script, "tce_db.php". The $params array is filled with date or cmd values. For detailed list of options see section about TCE elsewhere in this document.

Example:

    // Delete

$params = '&cmd[tt_content]['.$row['uid'].'][delete]=1';

$out.= '<a href="'.

    htmlspecialchars($GLOBALS['SOBE']->doc->issueCommand($params)).

    '" onclick="'.

    htmlspecialchars("return confirm('Want to delete?');").

    '">Delete record</a>';

t3lib_BEfunc::helpTextIcon

t3lib_BEfunc::helpText

t3lib_BEfunc::cshItem

Create icon or short description for Context Sensitive Help (CSH)

You are encouraged to integrate Content Sensitive help in your backend modules and for your database tables. This will help users to use TYPO3 and your TYPO3 applications more easily.

With these functions you can create content sensitive help texts (and links to more details) like this:

(Note: For the short description to be displayed and not only the icon the user must set up "Field help mode" in the User>Setup module to "Display full text message".)

Examples:

  // Setting "table name" to module name with prefix

$tableIdent = '_MOD_'.$this->MCONF['name'];

  // Creating CSH icon and short description:

$HTMLcode.=

    t3lib_BEfunc::helpTextIcon($tableIdent,'quickEdit',$BACK_PATH).

    t3lib_BEfunc::helpText($tableIdent,'quickEdit',$BACK_PATH).

    '<br />';

Prior to calling helpTextIcon and helpText you might need to load the description table with:

if ($BE_USER->uc['edit_showFieldHelp'])    {

    $LANG->loadSingleTableDescription($tableIdent);

}

Alternatively you can use t3lib_BEfunc::cshItem(). It's a quicker way  of integrating the descriptions since description files are loaded automatically and the text/icon mode is integrated in a single function call. This is recommended for sporadic usage:

$HTMLcode.=t3lib_BEfunc::cshItem($tableIdent,'quickEdit',$BACK_PATH);

t3lib_iconWorks::getIconImage

t3lib_iconWorks::getIcon

Getting correct icon for database table record

Always use these functions if you need to get the icon for a record. Works only for records from tables which are defined in $TCA

  // Getting default icon for the "tt_content" table:

t3lib_iconWorks::getIconImage('tt_content',array(),$this->backPath,'');

  // Getting an icon where record content may define the look:

$icon = t3lib_iconWorks::getIconImage(

            $this->table,

            $row,

            $this->backPath,

            'align="top" class="c-recIcon"'

        );

  // Getting the icon filename only:

$ficon = t3lib_iconWorks::getIcon($table,$row);

t3lib_iconWorks::skinImg

Processing icons for skin API

Pass the filename and width/height attributes of all images you use in your backend applications through this function. See Skin API description for more details.

$skin_enabled_icon = '<img'.

    t3lib_iconWorks::skinImg(

        $this->doc->backPath,

        'gfx/recordlock_warning3.gif',

        'width="17" height="12"'

    ).

    ' alt="" />';

$GLOBALS['TYPO3_DB']->

exec_INSERTquery

exec_UPDATEquery

exec_DELETEquery

exec_SELECTquery

Database Access API

To be compatible with Database Abstraction Layers you should always use the global object $TYPO3_DB for database access. The class "t3lib_db" contains a list of MySQL wrapper functions (sql(), sql_fetch_assoc(), etc...) which you can use almost out of the box as a start. Just search/replace.

But it is recommended that you port your application to using the four execution functions directly. These will both build the query for you and execute it.

See the Coding Guidelines, t3lib_db API and Inside TYPO3 document for more information.

Inserting a record:

Just fill an array with "fieldname => value" pairs and pass it to exec_INSERTquery() along with the table name in which it should be inserted:

$insertFields = array(

    'md5hash' => $md5,

    'tstamp' => time(),

    'type' => 2,

    'params' => $inUrl

);

$GLOBALS['TYPO3_DB']->exec_INSERTquery(

    'cache_md5params',

    $insertFields

);

Updating a record:

Create an array of "fieldname => value" pairs before calling exec_UPDATEquery(). The function call is almost like inserting, but you need to add a WHERE clause to target the update to the record you want to update. It is the second argument you set to a value like "uid=???".

$fields_values = array(

    'title' => $data['sys_todos'][$key]['title'],

    'deadline' => $data['sys_todos'][$key]['deadline'],

    'description' => $data['sys_todos'][$key]['description'],

    'tstamp' => time()

);

$GLOBALS['TYPO3_DB']->exec_UPDATEquery(

    'sys_todos',

    'uid='.intval($key),

    $fields_values

);

Deleting a record:

Call exec_DELETEquery() with the tablename and the WHERE clause selecting the record to delete:

$GLOBALS['TYPO3_DB']->exec_DELETEquery(

    'sys_todos',

    'uid='.intval($key)

);

Selecting a record:

Call exec_SELECTquery() with at least the first three arguments (field list to select, table name and WHERE clause). The return value is a result pointer (or object) which should be passed to ->sql_fetch_assoc() in a loop in order to traverse the result rows.

$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(

    '*',

    $theTable,

    $theField.'="'.

        $GLOBALS['TYPO3_DB']->quoteStr($theValue, $theTable).'"'.

        $this->deleteClause($theTable).' '.

        $whereClause,

    $groupBy,

    $orderBy,

    $limit

);

$rows = array();

while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))    {

    $rows[] = $row;

}

$GLOBALS['TYPO3_DB']->sql_free_result($res);

if (count($rows))    return $rows;

$GLOBALS['BE_USER']->

isAdmin

Return true if current backend user is "admin"

Use this if you need to restrict a user from doing something unless he is "admin".

$GLOBALS['BE_USER']->

getPagePermsClause

Return WHERE clause for filtering pages which permission mismatch for current user

The most typical usage of this is to call the function with the value "1". Then the WHERE clause returned will filter away all pages to which the user has no read-access.

TYPO3 Coding Guidelines

You should also refer to the TYPO3 Coding Guidelines (CGL) document which is the authoritative source to know about which coding practices are required for TYPO3 core and extension programming. That document also mentions the most important API calls that you have to use and gives further insights.

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 "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"

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

Programming with workspaces in mind

The concept of workspaces needs attension from extension programmers. The implementation of workspaces is however made so that no critical problems can appear with old extensions;

  1. First of all the “Live workspace” is no different from how TYPO3 has been working for years so that will be supported out of the box (except placeholder records must be filtered out in the frontend with “t3ver_state!=” , see below).

  2. Secondly, all permission related issues are implemented in TCEmain so the worst your users can experience is an error message.

However, you probably want to update your extension so that in the backend the current workspace is reflected in the records shown and the preview of content in the frontend works as well. Therefore this chapter has been written with instructions and insight into the issues you are facing.

Frontend challenges in general

For the frontend the challenges are mostly related to creating correct previews of content in workspaces. For most extensions this will work transparently as long as they use the API functions in TYPO3 to request records from the system.

The most basic form of a preview is when a live record is selected and you lookup a future version of that record belonging to the current workspace of the logged in backend user. This is very easy as long as a record is selected based on its “uid” or “pid” fields which are not subject to versioning; You simply call “sys_page->versionOL()” after record selection.

However, when other fields are involved in the where clause it gets dirty. This happens all the time! For instance, all records displayed in the frontend must be selected with respect to “enableFields” configuration! What if the future version is hidden and the live version is not? Since the live version is selected first (not hidden) and then overlaid with the content of the future version (hidden) the effect of the hidden field we wanted to preview is lost unless we also check the overlaid record for its hidden field (->versionOL() actually does this). But what about the opposite; if the live record was hidden and the future version not? Since the live version is never selected the future version will never have a chance to display itself! So we must first select the live records with no regard to the hidden state, then overlay the future version and eventually check if it is hidden and if so exclude it. The same problem applies to all other “enableFields”, future versions with “delete” flags and current versions which are invisible placeholders for future records. Anyway, all that is handled by TYPO3s t3lib_page class which includes functions for “enableFields” and “deleted” so it will work out of the box for you. But as soon as you do selection based on other fields like email, username, alias etc. it will fail.

Summary:

Challenge: How to preview elements which are disabled by “enableFields” in the live version but not necessarily in the offline version. Also, how to filter out new live records with “t3ver_state” set to 1 (placeholder for new elements) but only when not previewed.

Solution: Disable check for “enableFields”/”where_del_hidden” on live records and check for them in versionOL on input record.

Frontend implementation guidelines

  1. Any place where enableFields() are not used for selecting in the frontend you must at least check that “t3ver_state!=1” so placeholders for new records are not displayed.

  2. Make sure never to select any record with pid = -1! (related to versioning).

  3. If you need to detect preview mode for versioning and workspaces you can read these variables:

    1. $GLOBALS['TSFE']->sys_page->versioningPreview: If true, you are allowed to display previews of other record versions.

    2. $GLOBALS['TSFE']->sys_page->versioningWorkspaceId: Will tell you the id of the workspace of the current backend user. Used for preview of workspaces.

  4. Use these API functions for support of version previews in the backend:

Function

Description

$GLOBALS['TSFE']->sys_page->versionOL($table,&$row)

Versioning Preview Overlay.

Generally ALWAYS used when records are selected based on uid or pid. If records are selected on other fields than uid or pid (eg. "email = ....") then usage might produce undesired results and that should be evaluated on individual basis.

Principle; Record online! => Find offline?

Example:

This is how simple it is to use this record in your frontend plugins when you do queries directly (not using API functions already using them):

$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(...);
while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))      {
        $GLOBALS['TSFE']->sys_page->versionOL($table,$row);

        if (is_array($row))     {

...

When the live record is selected, call ->versionOL() and make sure to check if the input row (passed by reference) is still an array.

$GLOBALS['TSFE']->sys_page->fixVersioningPid()

Finding online PID for offline version record.

Will look if the "pid" value of the input record is -1 (it is an offline version) and if the table supports versioning; if so, it will translate the -1 PID into the PID of the original record

Used whenever you are tracking something back, like making the root line. In fact, it is currently only used by the root line function and chances are that you will not need this function often.

Principle; Record offline! => Find online?

Frontend scenarios impossible to preview

These issues are not planned to be supported for preview:

  1. Lookups and searching for records based on other fields than uid,pid,”enableFields” will never reflect workspace content since overlays happen to online records after they are selected.

    1. This problem can largely be avoided for versions of new records because versions of a "New"-placeholder can mirrow certain fields down onto the placeholder record. For the "tt_content" table this is configured as 'shadowColumnsForNewPlaceholders' => 'sys_language_uid,l18n_parent,colPos,header',  so that these fields used for column position, language and header title are also updated in the placeholder thus creating a correct preview in the frontend.

    2. For versions of existing records  the problem is in reality reduced a lot because normally you don't change the column or language fields after the record is first created anyways! But in theory the preview can fail.

    3. When changing the type of a page (eg. from "Standard" to "External URL") the preview might fail in cases where a look up is done on the "doktype" field of the live record.

      1. Page shortcuts might not work properly in preview.

      2. Mount Points might not work propertly in preview.

  2. It is impossible to preview the value of “count(*)” selections since we would have to traverse all records and pass them through ->versionOL() before we would have a reliable result!

  3. In tslib_fe::getPageShortcut() sys_page->getMenu() is called with an additional WHERE clause which will not respect if those fields are changed for a future version. This could be the case other places where getmenu() is used (but a search shows it is not a big problem). In this case we will for now accept that a wrong shortcut destination can be experienced during previews.

Backend challenges

The main challenge in the backend is to reflect how the system will look when the workspace gets published. To create a transparent experience for backend users we have to overlay almost every selected record with any possible new version it might have. Also when we are tracking records back to the page tree root point we will have to correct pid-values. All issues related to selecting on fields other than pid and uid also relates to the backend as they did for the frontend.

Workspace related API functions for backend modules

Function

Description

t3lib_BEfunc::workspaceOL()

Overlaying record with workspace version if any. Works like ->sys_page->versionOL() does, but for the backend. Input record must have fields only from the table (no pseudo fields) and the record is passed by reference.

Example:

$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id).$delClause);
$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);

t3lib_BEfunc::workspaceOL('pages', $row);

t3lib_BEfunc::getRecordWSOL()

Gets record from table and overlays the record with workspace version if any.

Example:

$row = t3lib_BEfunc::getRecordWSOL($table,$uid);

// This is the same as:

$row = t3lib_BEfunc::getRecord($table,$uid);

t3lib_BEfunc::workspaceOL($table,$row);

t3lib_BEfunc::fixVersioningPid()

Translating versioning PID -1 to the pid of the live record. Same as sys_page->fixVersioningPid() but for the backend.

t3lib_BEfunc::isPidInVersionizedBranch()

Will fetch the rootline for the pid, then check if anywhere in the rootline there is a branch point. Returns either "branchpoint" (if branch) or "first" (if page) or false if nothing. Alternatively, it returns the value of "t3ver_stage" for the branchpoint (if any)

t3lib_BEfunc::getWorkspaceVersionOfRecord()

Returns offline workspace version of a record, if found.

t3lib_BEfunc::getLiveVersionOfRecord()

Returns live version of workspace version.

t3lib_BEfunc::versioningPlaceholderClause()

Returns a WHERE-clause which will deselect placeholder records from other workspaces. This should be implemented almost everywhere records are selected based on other fields than uid and where t3lib_BEfunc::deleteClause() is used.

Example:

$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
   'count(*)',
   $this->table,
   $this->parentField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($uid, $this->table).
   t3lib_BEfunc::deleteClause($this->table).
   t3lib_BEfunc::versioningPlaceholderClause($this->table).
   $this->clause

);

$BE_USER->workspaceCannotEditRecord()

Checking if editing of an existing record is allowed in current workspace if that is offline.

$BE_USER->workspaceCannotEditOfflineVersion()

Like $BE_USER->workspaceCannotEditRecord() but also requires version to be offline (draft)

$BE_USER->workspaceCreateNewRecord()

Checks if new records can be created in a certain page (according to workspace restrictions).

$BE_USER->workspacePublishAccess($wsid)

Returns true if user has access to publish in workspace.

$BE_USER->workspaceSwapAccess()

Returns true if user has access to swap versions.

$BE_USER->checkWorkspace()

Checks how the users access is for a specific workspace.

$BE_USER->checkWorkspaceCurrent()

Like ->checkWorkspace() but returns status for the current workspace.

$BE_USER->setWorkspace()

Setting another workspace for backend user.

$BE_USER->setWorkspacePreview()

Setting frontend preview state.

Backend module access

You can restrict access to backend modules by using $MCONF['workspaces'] in the conf.php files. The variable is a list of keywords defining where the module is available:

$MCONF['workspaces'] = online,offline,custom

You can also restrict function menu items to certain workspaces if you like. This is done by an argument sent to the function t3lib_extMgm::insertModuleFunction(). See that file for more details.

Detecting current workspace

You can always check what the current workspace of the backend user is by reading $GLOBALS['BE_USER']->workspace. If the workspace is a custom workspace you will find its record loaded in $GLOBALS['BE_USER']->workspaceRec.

The values for workspaces are as following:

  1. workspace 0 = online (live)

  2. workspace -1 = offline (draft)

  3. workspace > 0 = custom (projects)

  4. workspace -99 = none selected at all (ERROR!)

Using TCEmain with workspaces

Since admin-users are also restricted by the workspace it is not possible to save any live records when in a workspace. However for very special occasions you might need to bypass this and to do so, you can set the instance variable t3lib_tcemain::bypassWorkspaceRestrictions to TRUE. An example of this is when users are updating their user profile using the User > Setup module; that actually allows them to save to a live record (their user record) while in a draft workspace.