tag with the class attribute set to the prefixId.
* All content returned from your plugins should be returned through this function so all content from your plugin is encapsulated in a
-tag nicely identifying the content of your plugin.
*
* @param string $str HTML content to wrap in the div-tags with the "main class" of the plugin
* @return string HTML content wrapped, ready to return to the parent object.
*/
public function pi_wrapInBaseClass($str)
{
$content = '
' . $str . '
';
if (!$this->frontendController->config['config']['disablePrefixComment']) {
$content = '
' . $content . '
';
}
return $content;
}
/***************************
*
* Frontend editing: Edit panel, edit icons
*
**************************/
/**
* Returns the Backend User edit panel for the $row from $tablename
*
* @param array $row Record array.
* @param string $tablename Table name
* @param string $label A label to show with the panel.
* @param array $conf TypoScript parameters to pass along to the EDITPANEL content Object that gets rendered. The property "allow" WILL get overridden/set though.
* @return string Returns FALSE/blank if no BE User login and of course if the panel is not shown for other reasons. Otherwise the HTML for the panel (a table).
* @see ContentObjectRenderer::EDITPANEL()
*/
public function pi_getEditPanel($row = [], $tablename = '', $label = '', $conf = [])
{
$panel = '';
if (!$row || !$tablename) {
$row = $this->internal['currentRow'];
$tablename = $this->internal['currentTable'];
}
if ($this->frontendController->isBackendUserLoggedIn()) {
// Create local cObj if not set:
if (!is_object($this->pi_EPtemp_cObj)) {
$this->pi_EPtemp_cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
$this->pi_EPtemp_cObj->setParent($this->cObj->data, $this->cObj->currentRecord);
}
// Initialize the cObj object with current row
$this->pi_EPtemp_cObj->start($row, $tablename);
// Setting TypoScript values in the $conf array. See documentation in TSref for the EDITPANEL cObject.
$conf['allow'] = 'edit,new,delete,move,hide';
$panel = $this->pi_EPtemp_cObj->cObjGetSingle('EDITPANEL', $conf, 'editpanel');
}
if ($panel) {
if ($label) {
return '
| ' . $label . ' | ' . $panel . ' |
';
}
return '' . $panel . '';
}
return $label;
}
/**
* Adds edit-icons to the input content.
* ContentObjectRenderer::editIcons used for rendering
*
* @param string $content HTML content to add icons to. The icons will be put right after the last content part in the string (that means before the ending series of HTML tags)
* @param string $fields The list of fields to edit when the icon is clicked.
* @param string $title Title for the edit icon.
* @param array $row Table record row
* @param string $tablename Table name
* @param array $oConf Conf array
* @return string The processed content
* @see ContentObjectRenderer::editIcons()
*/
public function pi_getEditIcon($content, $fields, $title = '', $row = [], $tablename = '', $oConf = [])
{
if ($this->frontendController->isBackendUserLoggedIn()) {
if (!$row || !$tablename) {
$row = $this->internal['currentRow'];
$tablename = $this->internal['currentTable'];
}
$conf = array_merge([
'beforeLastTag' => 1,
'iconTitle' => $title
], $oConf);
$content = $this->cObj->editIcons($content, $tablename . ':' . $fields, $conf, $tablename . ':' . $row['uid'], $row, '&viewUrl=' . rawurlencode(GeneralUtility::getIndpEnv('REQUEST_URI')));
}
return $content;
}
/***************************
*
* Localization, locallang functions
*
**************************/
/**
* Returns the localized label of the LOCAL_LANG key, $key
* Notice that for debugging purposes prefixes for the output values can be set with the internal vars ->LLtestPrefixAlt and ->LLtestPrefix
*
* @param string $key The key from the LOCAL_LANG array for which to return the value.
* @param string $alternativeLabel Alternative string to return IF no value is found set for the key, neither for the local language nor the default.
* @return string The value from LOCAL_LANG.
*/
public function pi_getLL($key, $alternativeLabel = '')
{
$word = null;
if (!empty($this->LOCAL_LANG[$this->LLkey][$key][0]['target'])
|| isset($this->LOCAL_LANG_UNSET[$this->LLkey][$key])
) {
$word = $this->LOCAL_LANG[$this->LLkey][$key][0]['target'];
} elseif ($this->altLLkey) {
$alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
$alternativeLanguageKeys = array_reverse($alternativeLanguageKeys);
foreach ($alternativeLanguageKeys as $languageKey) {
if (!empty($this->LOCAL_LANG[$languageKey][$key][0]['target'])
|| isset($this->LOCAL_LANG_UNSET[$languageKey][$key])
) {
// Alternative language translation for key exists
$word = $this->LOCAL_LANG[$languageKey][$key][0]['target'];
break;
}
}
}
if ($word === null) {
if (!empty($this->LOCAL_LANG['default'][$key][0]['target'])
|| isset($this->LOCAL_LANG_UNSET['default'][$key])
) {
// Get default translation (without charset conversion, english)
$word = $this->LOCAL_LANG['default'][$key][0]['target'];
} else {
// Return alternative string or empty
$word = isset($this->LLtestPrefixAlt) ? $this->LLtestPrefixAlt . $alternativeLabel : $alternativeLabel;
}
}
return isset($this->LLtestPrefix) ? $this->LLtestPrefix . $word : $word;
}
/**
* Loads local-language values from the file passed as a parameter or
* by looking for a "locallang" file in the
* plugin class directory ($this->scriptRelPath).
* Also locallang values set in the TypoScript property "_LOCAL_LANG" are
* merged onto the values found in the "locallang" file.
* Supported file extensions xlf, xml
*
* @param string $languageFilePath path to the plugin language file in format EXT:....
*/
public function pi_loadLL($languageFilePath = '')
{
if ($this->LOCAL_LANG_loaded) {
return;
}
if ($languageFilePath === '' && $this->scriptRelPath) {
$languageFilePath = 'EXT:' . $this->extKey . '/' . PathUtility::dirname($this->scriptRelPath) . '/locallang.xlf';
}
if ($languageFilePath !== '') {
/** @var LocalizationFactory $languageFactory */
$languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
$this->LOCAL_LANG = $languageFactory->getParsedData($languageFilePath, $this->LLkey);
$alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
foreach ($alternativeLanguageKeys as $languageKey) {
$tempLL = $languageFactory->getParsedData($languageFilePath, $languageKey);
if ($this->LLkey !== 'default' && isset($tempLL[$languageKey])) {
$this->LOCAL_LANG[$languageKey] = $tempLL[$languageKey];
}
}
// Overlaying labels from TypoScript (including fictitious language keys for non-system languages!):
if (isset($this->conf['_LOCAL_LANG.'])) {
// Clear the "unset memory"
$this->LOCAL_LANG_UNSET = [];
foreach ($this->conf['_LOCAL_LANG.'] as $languageKey => $languageArray) {
// Remove the dot after the language key
$languageKey = substr($languageKey, 0, -1);
// Don't process label if the language is not loaded
if (is_array($languageArray) && isset($this->LOCAL_LANG[$languageKey])) {
foreach ($languageArray as $labelKey => $labelValue) {
if (!is_array($labelValue)) {
$this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
if ($labelValue === '') {
$this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
}
}
}
}
}
}
}
$this->LOCAL_LANG_loaded = true;
}
/***************************
*
* Database, queries
*
**************************/
/**
* Executes a standard SELECT query for listing of records based on standard input vars from the 'browser' ($this->internal['results_at_a_time'] and $this->piVars['pointer']) and 'searchbox' ($this->piVars['sword'] and $this->internal['searchFieldList'])
* Set $count to 1 if you wish to get a count(*) query for selecting the number of results.
* Notice that the query will use $this->conf['pidList'] and $this->conf['recursive'] to generate a PID list within which to search for records.
*
* @param string $table The table name to make the query for.
* @param bool $count If set, you will get a "count(*)" query back instead of field selecting
* @param string $addWhere Additional WHERE clauses (should be starting with " AND ....")
* @param mixed $mm_cat If an array, then it must contain the keys "table", "mmtable" and (optionally) "catUidList" defining a table to make a MM-relation to in the query (based on fields uid_local and uid_foreign). If not array, the query will be a plain query looking up data in only one table.
* @param string $groupBy If set, this is added as a " GROUP BY ...." part of the query.
* @param string $orderBy If set, this is added as a " ORDER BY ...." part of the query. The default is that an ORDER BY clause is made based on $this->internal['orderBy'] and $this->internal['descFlag'] where the orderBy field must be found in $this->internal['orderByList']
* @param string $query If set, this is taken as the first part of the query instead of what is created internally. Basically this should be a query starting with "FROM [table] WHERE ... AND ...". The $addWhere clauses and all the other stuff is still added. Only the tables and PID selecting clauses are bypassed. May be deprecated in the future!
* @return Statement
*/
public function pi_exec_query($table, $count = false, $addWhere = '', $mm_cat = '', $groupBy = '', $orderBy = '', $query = '')
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->from($table);
// Begin Query:
if (!$query) {
// This adds WHERE-clauses that ensures deleted, hidden, starttime/endtime/access records are NOT
// selected, if they should not! Almost ALWAYS add this to your queries!
$queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
// Fetches the list of PIDs to select from.
// TypoScript property .pidList is a comma list of pids. If blank, current page id is used.
// TypoScript property .recursive is an int+ which determines how many levels down from the pids in the pid-list subpages should be included in the select.
$pidList = GeneralUtility::intExplode(',', $this->pi_getPidList($this->conf['pidList'], $this->conf['recursive']), true);
if (is_array($mm_cat)) {
$queryBuilder->from($mm_cat['table'])
->from($mm_cat['mmtable'])
->where(
$queryBuilder->expr()->eq($table . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_local')),
$queryBuilder->expr()->eq($mm_cat['table'] . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_foreign')),
$queryBuilder->expr()->in(
$table . '.pid',
$queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
)
);
if (strcmp($mm_cat['catUidList'], '')) {
$queryBuilder->andWhere(
$queryBuilder->expr()->in(
$mm_cat['table'] . '.uid',
$queryBuilder->createNamedParameter(
GeneralUtility::intExplode(',', $mm_cat['catUidList'], true),
Connection::PARAM_INT_ARRAY
)
)
);
}
} else {
$queryBuilder->where(
$queryBuilder->expr()->in(
'pid',
$queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
)
);
}
} else {
// Restrictions need to be handled by the $query parameter!
$queryBuilder->getRestrictions()->removeAll();
// Split the "FROM ... WHERE" string so we get the WHERE part and TABLE names separated...:
list($tableListFragment, $whereFragment) = preg_split('/WHERE/i', trim($query), 2);
foreach (QueryHelper::parseTableList($tableListFragment) as $tableNameAndAlias) {
list($tableName, $tableAlias) = $tableNameAndAlias;
$queryBuilder->from($tableName, $tableAlias);
}
$queryBuilder->where(QueryHelper::stripLogicalOperatorPrefix($whereFragment));
}
// Add '$addWhere'
if ($addWhere) {
$queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($addWhere));
}
// Search word:
if ($this->piVars['sword'] && $this->internal['searchFieldList']) {
$searchWhere = QueryHelper::stripLogicalOperatorPrefix(
$this->cObj->searchWhere($this->piVars['sword'], $this->internal['searchFieldList'], $table)
);
if (!empty($searchWhere)) {
$queryBuilder->andWhere($searchWhere);
}
}
if ($count) {
$queryBuilder->count('*');
} else {
// Add 'SELECT'
$fields = $this->pi_prependFieldsWithTable($table, $this->pi_listFields);
$queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true));
// Order by data:
if (!$orderBy && $this->internal['orderBy']) {
if (GeneralUtility::inList($this->internal['orderByList'], $this->internal['orderBy'])) {
$sorting = $this->internal['descFlag'] ? ' DESC' : 'ASC';
$queryBuilder->orderBy($table . '.' . $this->internal['orderBy'], $sorting);
}
} elseif ($orderBy) {
foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
list($fieldName, $sorting) = $fieldNameAndSorting;
$queryBuilder->addOrderBy($fieldName, $sorting);
}
}
// Limit data:
$pointer = (int)$this->piVars['pointer'];
$results_at_a_time = MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
$queryBuilder->setFirstResult($pointer * $results_at_a_time)
->setMaxResults($results_at_a_time);
// Grouping
if (!empty($groupBy)) {
$queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
}
}
return $queryBuilder->execute();
}
/**
* Returns the row $uid from $table
* (Simply calling $this->frontendEngine->sys_page->checkRecord())
*
* @param string $table The table name
* @param int $uid The uid of the record from the table
* @param bool $checkPage If $checkPage is set, it's required that the page on which the record resides is accessible
* @return array If record is found, an array. Otherwise FALSE.
*/
public function pi_getRecord($table, $uid, $checkPage = false)
{
return $this->frontendController->sys_page->checkRecord($table, $uid, $checkPage);
}
/**
* Returns a commalist of page ids for a query (eg. 'WHERE pid IN (...)')
*
* @param string $pid_list A comma list of page ids (if empty current page is used)
* @param int $recursive An integer >=0 telling how deep to dig for pids under each entry in $pid_list
* @return string List of PID values (comma separated)
*/
public function pi_getPidList($pid_list, $recursive = 0)
{
if (!strcmp($pid_list, '')) {
$pid_list = $this->frontendController->id;
}
$recursive = MathUtility::forceIntegerInRange($recursive, 0);
$pid_list_arr = array_unique(GeneralUtility::trimExplode(',', $pid_list, true));
$pid_list = [];
foreach ($pid_list_arr as $val) {
$val = MathUtility::forceIntegerInRange($val, 0);
if ($val) {
$_list = $this->cObj->getTreeList(-1 * $val, $recursive);
if ($_list) {
$pid_list[] = $_list;
}
}
}
return implode(',', $pid_list);
}
/**
* Having a comma list of fields ($fieldList) this is prepended with the $table.'.' name
*
* @param string $table Table name to prepend
* @param string $fieldList List of fields where each element will be prepended with the table name given.
* @return string List of fields processed.
*/
public function pi_prependFieldsWithTable($table, $fieldList)
{
$list = GeneralUtility::trimExplode(',', $fieldList, true);
$return = [];
foreach ($list as $listItem) {
$return[] = $table . '.' . $listItem;
}
return implode(',', $return);
}
/**
* Will select all records from the "category table", $table, and return them in an array.
*
* @param string $table The name of the category table to select from.
* @param int $pid The page from where to select the category records.
* @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
* @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
* @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
* @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
* @return array The array with the category records in.
*/
public function pi_getCategoryTableContents($table, $pid, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
$queryBuilder->select('*')
->from($table)
->where(
$queryBuilder->expr()->eq(
'pid',
$queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
),
QueryHelper::stripLogicalOperatorPrefix($whereClause)
);
if (!empty($orderBy)) {
foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
list($fieldName, $sorting) = $fieldNameAndSorting;
$queryBuilder->addOrderBy($fieldName, $sorting);
}
}
if (!empty($groupBy)) {
$queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
}
if (!empty($limit)) {
$limitValues = GeneralUtility::intExplode(',', $limit, true);
if (count($limitValues) === 1) {
$queryBuilder->setMaxResults($limitValues[0]);
} else {
$queryBuilder->setFirstResult($limitValues[0])
->setMaxResults($limitValues[1]);
}
}
$result = $queryBuilder->execute();
$outArr = [];
while ($row = $result->fetch()) {
$outArr[$row['uid']] = $row;
}
return $outArr;
}
/***************************
*
* Various
*
**************************/
/**
* Returns TRUE if the piVars array has ONLY those fields entered that is set in the $fList (commalist) AND if none of those fields value is greater than $lowerThan field if they are integers.
* Notice that this function will only work as long as values are integers.
*
* @param string $fList List of fields (keys from piVars) to evaluate on
* @param int $lowerThan Limit for the values.
* @return bool|null Returns TRUE (1) if conditions are met.
*/
public function pi_isOnlyFields($fList, $lowerThan = -1)
{
$lowerThan = $lowerThan == -1 ? $this->pi_lowerThan : $lowerThan;
$fList = GeneralUtility::trimExplode(',', $fList, true);
$tempPiVars = $this->piVars;
foreach ($fList as $k) {
if (!MathUtility::canBeInterpretedAsInteger($tempPiVars[$k]) || $tempPiVars[$k] < $lowerThan) {
unset($tempPiVars[$k]);
}
}
if (empty($tempPiVars)) {
//@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
return 1;
}
return null;
}
/**
* Returns TRUE if the array $inArray contains only values allowed to be cached based on the configuration in $this->pi_autoCacheFields
* Used by ->pi_linkTP_keepPIvars
* This is an advanced form of evaluation of whether a URL should be cached or not.
*
* @param array $inArray An array with piVars values to evaluate
* @return bool|null Returns TRUE (1) if conditions are met.
* @see pi_linkTP_keepPIvars()
*/
public function pi_autoCache($inArray)
{
if (is_array($inArray)) {
foreach ($inArray as $fN => $fV) {
if (!strcmp($inArray[$fN], '')) {
unset($inArray[$fN]);
} elseif (is_array($this->pi_autoCacheFields[$fN])) {
if (is_array($this->pi_autoCacheFields[$fN]['range']) && (int)$inArray[$fN] >= (int)$this->pi_autoCacheFields[$fN]['range'][0] && (int)$inArray[$fN] <= (int)$this->pi_autoCacheFields[$fN]['range'][1]) {
unset($inArray[$fN]);
}
if (is_array($this->pi_autoCacheFields[$fN]['list']) && in_array($inArray[$fN], $this->pi_autoCacheFields[$fN]['list'])) {
unset($inArray[$fN]);
}
}
}
}
if (empty($inArray)) {
//@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
return 1;
}
return null;
}
/**
* Will process the input string with the parseFunc function from ContentObjectRenderer based on configuration
* set in "lib.parseFunc_RTE" in the current TypoScript template.
*
* @param string $str The input text string to process
* @return string The processed string
* @see ContentObjectRenderer::parseFunc()
*/
public function pi_RTEcssText($str)
{
$parseFunc = $this->frontendController->tmpl->setup['lib.']['parseFunc_RTE.'];
if (is_array($parseFunc)) {
$str = $this->cObj->parseFunc($str, $parseFunc);
}
return $str;
}
/*******************************
*
* FlexForms related functions
*
*******************************/
/**
* Converts $this->cObj->data['pi_flexform'] from XML string to flexForm array.
*
* @param string $field Field name to convert
*/
public function pi_initPIflexForm($field = 'pi_flexform')
{
// Converting flexform data into array:
if (!is_array($this->cObj->data[$field]) && $this->cObj->data[$field]) {
$this->cObj->data[$field] = GeneralUtility::xml2array($this->cObj->data[$field]);
if (!is_array($this->cObj->data[$field])) {
$this->cObj->data[$field] = [];
}
}
}
/**
* Return value from somewhere inside a FlexForm structure
*
* @param array $T3FlexForm_array FlexForm data
* @param string $fieldName Field name to extract. Can be given like "test/el/2/test/el/field_templateObject" where each part will dig a level deeper in the FlexForm data.
* @param string $sheet Sheet pointer, eg. "sDEF
* @param string $lang Language pointer, eg. "lDEF
* @param string $value Value pointer, eg. "vDEF
* @return string|null The content.
*/
public function pi_getFFvalue($T3FlexForm_array, $fieldName, $sheet = 'sDEF', $lang = 'lDEF', $value = 'vDEF')
{
$sheetArray = is_array($T3FlexForm_array) ? $T3FlexForm_array['data'][$sheet][$lang] : '';
if (is_array($sheetArray)) {
return $this->pi_getFFvalueFromSheetArray($sheetArray, explode('/', $fieldName), $value);
}
return null;
}
/**
* Returns part of $sheetArray pointed to by the keys in $fieldNameArray
*
* @param array $sheetArray Multidimensiona array, typically FlexForm contents
* @param array $fieldNameArr Array where each value points to a key in the FlexForms content - the input array will have the value returned pointed to by these keys. All integer keys will not take their integer counterparts, but rather traverse the current position in the array an return element number X (whether this is right behavior is not settled yet...)
* @param string $value Value for outermost key, typ. "vDEF" depending on language.
* @return mixed The value, typ. string.
* @internal
* @see pi_getFFvalue()
*/
public function pi_getFFvalueFromSheetArray($sheetArray, $fieldNameArr, $value)
{
$tempArr = $sheetArray;
foreach ($fieldNameArr as $k => $v) {
if (MathUtility::canBeInterpretedAsInteger($v)) {
if (is_array($tempArr)) {
$c = 0;
foreach ($tempArr as $values) {
if ($c == $v) {
$tempArr = $values;
break;
}
$c++;
}
}
} else {
$tempArr = $tempArr[$v];
}
}
return $tempArr[$value];
}
/**
* Returns the currently configured "site language" if a site is configured (= resolved) in the current request.
*
* @internal
*/
protected function getCurrentSiteLanguage(): ?SiteLanguage
{
$request = $GLOBALS['TYPO3_REQUEST'] ?? null;
return $request
&& $request instanceof ServerRequestInterface
&& $request->getAttribute('language') instanceof SiteLanguage
? $request->getAttribute('language')
: null;
}
}