/**
  * Schreibt die ganzen CSV Zeilen in eine Datei
  *
  * @param string $sDir
  * @param string $sPrefix
  * @param array $aData
  * @param string $sFileName	| gibt es einen festen dateinamen?
  *
  * @return string | Name der Datei
  */
 public function writeCsv($sDir, $sPrefix = '', $aData = array(), $sFileName = '')
 {
     if (empty($aData)) {
         $aData = $this->getCsvLines();
     }
     if (!$sFileName) {
         if ($sPrefix) {
             $sPrefix = $sPrefix . '_';
         }
         $sFileName = $sPrefix . date('dmy-Hi') . '.csv';
     }
     $sCsvLines = implode(chr(13) . chr(10), $aData);
     if (t3lib_div::writeFile($sDir . $sFileName, $sCsvLines)) {
         return $sFileName;
     } else {
         return false;
     }
 }
 /**
  * Generates the sprites for t3skin.
  *
  * @return	string		HTML content
  */
 public function createSpritesForT3Skin()
 {
     /** @var $generator t3lib_SpriteManager_SpriteGenerator */
     $generator = t3lib_div::makeInstance('t3lib_SpriteManager_SpriteGenerator', 't3skin');
     $this->unlinkT3SkinFiles();
     $data = $generator->setSpriteFolder(TYPO3_mainDir . 'sysext/t3skin/images/sprites/')->setCSSFolder(TYPO3_mainDir . 'sysext/t3skin/stylesheets/sprites/')->setOmmitSpriteNameInIconName(TRUE)->setIncludeTimestampInCSS(TRUE)->generateSpriteFromFolder(array(TYPO3_mainDir . 'sysext/t3skin/images/icons/'));
     $version = Tx_Extdeveval_Compatibility::convertVersionNumberToInteger(TYPO3_version);
     // IE6 fallback sprites have been removed with TYPO3 4.6
     if ($version < 4006000) {
         $gifSpritesPath = PATH_typo3 . 'sysext/t3skin/stylesheets/ie6/z_t3-icons-gifSprites.css';
         if (FALSE === rename($data['cssGif'], $gifSpritesPath)) {
             throw new tx_extdeveval_exception('The file "' . $data['cssGif'] . '" could not be renamed to "' . $gifSpritesPath . '"');
         }
     }
     $stddbPath = PATH_site . 't3lib/stddb/tables.php';
     $stddbContents = file_get_contents($stddbPath);
     $newContent = '$GLOBALS[\'TBE_STYLES\'][\'spriteIconApi\'][\'coreSpriteImageNames\'] = array(' . LF . TAB . '\'' . implode('\',' . LF . TAB . '\'', $data['iconNames']) . '\'' . LF . ');' . LF;
     $stddbContents = preg_replace('/\\$GLOBALS\\[\'TBE_STYLES\'\\]\\[\'spriteIconApi\'\\]\\[\'coreSpriteImageNames\'\\] = array\\([\\s\',\\w-]*\\);/', $newContent, $stddbContents);
     if (FALSE === t3lib_div::writeFile($stddbPath, $stddbContents)) {
         throw new tx_extdeveval_exception('Could not write file "' . $stddbPath . '"');
     }
     $output = 'Sprites successfully regenerated';
     return $output;
 }
    /**
     * The main processing method if this class
     *
     * @return	string		Information of the template status or the taken actions as HTML string
     */
    function main()
    {
        global $SOBE, $BE_USER, $LANG, $BACK_PATH, $TCA_DESCR, $TCA, $CLIENT, $TYPO3_CONF_VARS;
        global $tmpl, $tplRow, $theConstants;
        $edit = $this->pObj->edit;
        $e = $this->pObj->e;
        t3lib_div::loadTCA('sys_template');
        // **************************
        // Checking for more than one template an if, set a menu...
        // **************************
        $manyTemplatesMenu = $this->pObj->templateMenu();
        $template_uid = 0;
        if ($manyTemplatesMenu) {
            $template_uid = $this->pObj->MOD_SETTINGS['templatesOnPage'];
        }
        // **************************
        // Initialize
        // **************************
        $existTemplate = $this->initialize_editor($this->pObj->id, $template_uid);
        // initialize
        if ($existTemplate) {
            $saveId = $tplRow['_ORIG_uid'] ? $tplRow['_ORIG_uid'] : $tplRow['uid'];
        }
        // **************************
        // Create extension template
        // **************************
        $newId = $this->pObj->createTemplate($this->pObj->id, $saveId);
        if ($newId) {
            // switch to new template
            t3lib_utility_Http::redirect('index.php?id=' . $this->pObj->id . '&SET[templatesOnPage]=' . $newId);
        }
        if ($existTemplate) {
            // Update template ?
            $POST = t3lib_div::_POST();
            if ($POST['submit'] || t3lib_div::testInt($POST['submit_x']) && t3lib_div::testInt($POST['submit_y']) || $POST['saveclose'] || t3lib_div::testInt($POST['saveclose_x']) && t3lib_div::testInt($POST['saveclose_y'])) {
                // Set the data to be saved
                $recData = array();
                $alternativeFileName = array();
                $resList = $tplRow['resources'];
                $tmp_upload_name = '';
                $tmp_newresource_name = '';
                // Set this to blank
                if (is_array($POST['data'])) {
                    foreach ($POST['data'] as $field => $val) {
                        switch ($field) {
                            case 'constants':
                            case 'config':
                            case 'title':
                            case 'sitetitle':
                            case 'description':
                                $recData['sys_template'][$saveId][$field] = $val;
                                break;
                            case 'resources':
                                $tmp_upload_name = t3lib_div::upload_to_tempfile($_FILES['resources']['tmp_name']);
                                // If there is an uploaded file, move it for the sake of safe_mode.
                                if ($tmp_upload_name) {
                                    if ($tmp_upload_name != 'none' && $_FILES['resources']['name']) {
                                        $alternativeFileName[$tmp_upload_name] = trim($_FILES['resources']['name']);
                                        $resList = $tmp_upload_name . ',' . $resList;
                                    }
                                }
                                break;
                            case 'new_resource':
                                $newName = trim(t3lib_div::_GP('new_resource'));
                                if ($newName) {
                                    $newName .= '.' . t3lib_div::_GP('new_resource_ext');
                                    $tmp_newresource_name = t3lib_div::tempnam('new_resource_');
                                    $alternativeFileName[$tmp_newresource_name] = $newName;
                                    $resList = $tmp_newresource_name . ',' . $resList;
                                }
                                break;
                            case 'makecopy_resource':
                                if (is_array($val)) {
                                    $resList = ',' . $resList . ',';
                                    foreach ($val as $k => $file) {
                                        $tmp_name = PATH_site . $TCA['sys_template']['columns']['resources']['config']['uploadfolder'] . '/' . $file;
                                        $resList = $tmp_name . ',' . $resList;
                                    }
                                }
                                break;
                            case 'remove_resource':
                                if (is_array($val)) {
                                    $resList = ',' . $resList . ',';
                                    foreach ($val as $k => $file) {
                                        $resList = str_replace(',' . $file . ',', ',', $resList);
                                    }
                                }
                                break;
                            case 'totop_resource':
                                if (is_array($val)) {
                                    $resList = ',' . $resList . ',';
                                    foreach ($val as $k => $file) {
                                        $resList = str_replace(',' . $file . ',', ',', $resList);
                                        $resList = ',' . $file . $resList;
                                    }
                                }
                                break;
                        }
                    }
                }
                $resList = implode(',', t3lib_div::trimExplode(',', $resList, 1));
                if (strcmp($resList, $tplRow['resources'])) {
                    $recData['sys_template'][$saveId]['resources'] = $resList;
                }
                if (count($recData)) {
                    // Create new  tce-object
                    $tce = t3lib_div::makeInstance('t3lib_TCEmain');
                    $tce->stripslashes_values = 0;
                    $tce->alternativeFileName = $alternativeFileName;
                    // Initialize
                    $tce->start($recData, array());
                    // Saved the stuff
                    $tce->process_datamap();
                    // Clear the cache (note: currently only admin-users can clear the cache in tce_main.php)
                    $tce->clear_cacheCmd('all');
                    // tce were processed successfully
                    $this->tce_processed = true;
                    // re-read the template ...
                    $this->initialize_editor($this->pObj->id, $template_uid);
                }
                // Unlink any uploaded/new temp files there was:
                t3lib_div::unlink_tempfile($tmp_upload_name);
                t3lib_div::unlink_tempfile($tmp_newresource_name);
                // If files has been edited:
                if (is_array($edit)) {
                    if ($edit['filename'] && $tplRow['resources'] && t3lib_div::inList($tplRow['resources'], $edit['filename'])) {
                        // Check if there are resources, and that the file is in the resourcelist.
                        $path = PATH_site . $TCA['sys_template']['columns']['resources']['config']['uploadfolder'] . '/' . $edit['filename'];
                        $fI = t3lib_div::split_fileref($edit['filename']);
                        if (@is_file($path) && t3lib_div::getFileAbsFileName($path) && t3lib_div::inList($this->pObj->textExtensions, $fI['fileext'])) {
                            // checks that have already been done.. Just to make sure
                            // @TODO: Check if the hardcorded value already has a config member, otherwise create one
                            if (filesize($path) < 30720) {
                                // checks that have already been done.. Just to make sure
                                t3lib_div::writeFile($path, $edit['file']);
                                $theOutput .= $this->pObj->doc->spacer(10);
                                $theOutput .= $this->pObj->doc->section('<font color=red>' . $GLOBALS['LANG']->getLL('fileChanged') . '</font>', sprintf($GLOBALS['LANG']->getLL('resourceUpdated'), $edit['filename']), 0, 0, 0, 1);
                                // Clear cache - the file has probably affected the template setup
                                // @TODO: Check if the edited file really had something to do with cached data and prevent this clearing if possible!
                                $tce = t3lib_div::makeInstance('t3lib_TCEmain');
                                $tce->stripslashes_values = 0;
                                $tce->start(array(), array());
                                $tce->clear_cacheCmd('all');
                            }
                        }
                    }
                }
            }
            // hook	Post updating template/TCE processing
            if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postTCEProcessingHook'])) {
                $postTCEProcessingHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postTCEProcessingHook'];
                if (is_array($postTCEProcessingHook)) {
                    $hookParameters = array('POST' => $POST, 'tce' => $tce);
                    foreach ($postTCEProcessingHook as $hookFunction) {
                        t3lib_div::callUserFunction($hookFunction, $hookParameters, $this);
                    }
                }
            }
            $theOutput .= $this->pObj->doc->spacer(5);
            $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('templateInformation'), t3lib_iconWorks::getSpriteIconForRecord('sys_template', $tplRow) . '<strong>' . htmlspecialchars($tplRow['title']) . '</strong>' . htmlspecialchars(trim($tplRow['sitetitle']) ? ' - (' . $tplRow['sitetitle'] . ')' : ''), 0, 1);
            if ($manyTemplatesMenu) {
                $theOutput .= $this->pObj->doc->section('', $manyTemplatesMenu);
                $theOutput .= $this->pObj->doc->divider(5);
            }
            #$numberOfRows= t3lib_div::intInRange($this->pObj->MOD_SETTINGS["ts_template_editor_TArows"],0,150);
            #if (!$numberOfRows)
            $numberOfRows = 35;
            // If abort pressed, nothing should be edited:
            if ($POST['abort'] || t3lib_div::testInt($POST['abort_x']) && t3lib_div::testInt($POST['abort_y']) || $POST['saveclose'] || t3lib_div::testInt($POST['saveclose_x']) && t3lib_div::testInt($POST['saveclose_y'])) {
                unset($e);
            }
            if ($e['title']) {
                $outCode = '<input type="Text" name="data[title]" value="' . htmlspecialchars($tplRow['title']) . '"' . $this->pObj->doc->formWidth() . '>';
                $outCode .= '<input type="Hidden" name="e[title]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('title'), $outCode);
            }
            if ($e['sitetitle']) {
                $outCode = '<input type="Text" name="data[sitetitle]" value="' . htmlspecialchars($tplRow['sitetitle']) . '"' . $this->pObj->doc->formWidth() . '>';
                $outCode .= '<input type="Hidden" name="e[sitetitle]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('sitetitle'), $outCode);
            }
            if ($e['description']) {
                $outCode = '<textarea name="data[description]" rows="5" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, '', '') . '>' . t3lib_div::formatForTextarea($tplRow['description']) . '</textarea>';
                $outCode .= '<input type="Hidden" name="e[description]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('description'), $outCode);
            }
            if ($e['resources']) {
                // Upload
                $outCode = '<input type="File" name="resources"' . $this->pObj->doc->formWidth() . ' size="50">';
                $outCode .= '<input type="Hidden" name="data[resources]" value="1">';
                $outCode .= '<input type="Hidden" name="e[resources]" value="1">';
                $outCode .= '<BR>' . $GLOBALS['LANG']->getLL('allowedExtensions') . ' <strong>' . $TCA['sys_template']['columns']['resources']['config']['allowed'] . '</strong>';
                $outCode .= '<BR>' . $GLOBALS['LANG']->getLL('maxFilesize') . ' <strong>' . t3lib_div::formatSize($TCA['sys_template']['columns']['resources']['config']['max_size'] * 1024) . '</strong>';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('uploadResource'), $outCode);
                // New
                $opt = explode(',', $this->pObj->textExtensions);
                $optTags = '';
                foreach ($opt as $extVal) {
                    $optTags .= '<option value="' . $extVal . '">.' . $extVal . '</option>';
                }
                $outCode = '<input type="text" name="new_resource"' . $this->pObj->doc->formWidth(20) . '>
					<select name="new_resource_ext">' . $optTags . '</select>';
                $outCode .= '<input type="Hidden" name="data[new_resource]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('newTextResource'), $outCode);
                // Make copy
                $rL = $this->resourceListForCopy($this->pObj->id, $template_uid);
                if ($rL) {
                    $theOutput .= $this->pObj->doc->spacer(20);
                    $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('copyResource'), $rL);
                }
                // Update resource list
                $rL = $this->procesResources($tplRow['resources'], 1);
                if ($rL) {
                    $theOutput .= $this->pObj->doc->spacer(20);
                    $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('updateResourceList'), $rL);
                }
            }
            if ($e['constants']) {
                $outCode = '<textarea name="data[constants]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, 'width:98%;height:70%', 'off') . ' class="fixed-font">' . t3lib_div::formatForTextarea($tplRow['constants']) . '</textarea>';
                $outCode .= '<input type="Hidden" name="e[constants]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('constants'), '');
                $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
            }
            if ($e['file']) {
                $path = PATH_site . $TCA['sys_template']['columns']['resources']['config']['uploadfolder'] . '/' . $e[file];
                $fI = t3lib_div::split_fileref($e[file]);
                if (@is_file($path) && t3lib_div::inList($this->pObj->textExtensions, $fI['fileext'])) {
                    if (filesize($path) < $TCA['sys_template']['columns']['resources']['config']['max_size'] * 1024) {
                        $fileContent = t3lib_div::getUrl($path);
                        $outCode = $GLOBALS['LANG']->getLL('file') . ' <strong>' . $e[file] . '</strong><BR>';
                        $outCode .= '<textarea name="edit[file]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, 'width:98%;height:70%', 'off') . ' class="fixed-font">' . t3lib_div::formatForTextarea($fileContent) . '</textarea>';
                        $outCode .= '<input type="Hidden" name="edit[filename]" value="' . $e[file] . '">';
                        $outCode .= '<input type="Hidden" name="e[file]" value="' . htmlspecialchars($e[file]) . '">';
                        $theOutput .= $this->pObj->doc->spacer(15);
                        $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('editResource'), '');
                        $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
                    } else {
                        $theOutput .= $this->pObj->doc->spacer(15);
                        $fileToBig = sprintf($GLOBALS['LANG']->getLL('filesizeExceeded'), $TCA['sys_template']['columns']['resources']['config']['max_size']);
                        $filesizeNotAllowed = sprintf($GLOBALS['LANG']->getLL('notAllowed'), $TCA['sys_template']['columns']['resources']['config']['max_size']);
                        $theOutput .= $this->pObj->doc->section('<font color=red>' . $fileToBig . '</font>', $filesizeNotAllowed, 0, 0, 0, 1);
                    }
                }
            }
            if ($e['config']) {
                $outCode = '<textarea name="data[config]" rows="' . $numberOfRows . '" wrap="off" class="fixed-font enable-tab"' . $this->pObj->doc->formWidthText(48, "width:98%;height:70%", "off") . ' class="fixed-font">' . t3lib_div::formatForTextarea($tplRow["config"]) . '</textarea>';
                if (t3lib_extMgm::isLoaded('tsconfig_help')) {
                    $url = $BACK_PATH . 'wizard_tsconfig.php?mode=tsref';
                    $params = array('formName' => 'editForm', 'itemName' => 'data[config]');
                    $outCode .= '<a href="#" onClick="vHWin=window.open(\'' . $url . t3lib_div::implodeArrayForUrl('', array('P' => $params)) . '\',\'popUp' . $md5ID . '\',\'height=500,width=780,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;">' . t3lib_iconWorks::getSpriteIcon('actions-system-typoscript-documentation-open', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:tsRef', true))) . '</a>';
                }
                $outCode .= '<input type="Hidden" name="e[config]" value="1">';
                $theOutput .= $this->pObj->doc->spacer(15);
                $theOutput .= $this->pObj->doc->section($GLOBALS['LANG']->getLL('setup'), '');
                $theOutput .= $this->pObj->doc->sectionEnd() . $outCode;
            }
            // Processing:
            $outCode = '';
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('title'), htmlspecialchars($tplRow['title']), 'title');
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('sitetitle'), htmlspecialchars($tplRow['sitetitle']), 'sitetitle');
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('description'), nl2br(htmlspecialchars($tplRow['description'])), 'description');
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('resources'), $this->procesResources($tplRow['resources']), 'resources');
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('constants'), sprintf($GLOBALS['LANG']->getLL('editToView'), trim($tplRow[constants]) ? count(explode(LF, $tplRow[constants])) : 0), 'constants');
            $outCode .= $this->tableRow($GLOBALS['LANG']->getLL('setup'), sprintf($GLOBALS['LANG']->getLL('editToView'), trim($tplRow[config]) ? count(explode(LF, $tplRow[config])) : 0), 'config');
            $outCode = '<br /><br /><table class="t3-table-info">' . $outCode . '</table>';
            // Edit all icon:
            $outCode .= '<br /><a href="#" onClick="' . t3lib_BEfunc::editOnClick(rawurlencode('&createExtension=0') . '&amp;edit[sys_template][' . $tplRow['uid'] . ']=edit', $BACK_PATH, '') . '"><strong>' . t3lib_iconWorks::getSpriteIcon('actions-document-open', array('title' => $GLOBALS['LANG']->getLL('editTemplateRecord'))) . $GLOBALS['LANG']->getLL('editTemplateRecord') . '</strong></a>';
            $theOutput .= $this->pObj->doc->section('', $outCode);
            // hook	after compiling the output
            if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postOutputProcessingHook'])) {
                $postOutputProcessingHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/tstemplate_info/class.tx_tstemplateinfo.php']['postOutputProcessingHook'];
                if (is_array($postOutputProcessingHook)) {
                    $hookParameters = array('theOutput' => &$theOutput, 'POST' => $POST, 'e' => $e, 'tplRow' => $tplRow, 'numberOfRows' => $numberOfRows);
                    foreach ($postOutputProcessingHook as $hookFunction) {
                        t3lib_div::callUserFunction($hookFunction, $hookParameters, $this);
                    }
                }
            }
        } else {
            $theOutput .= $this->pObj->noTemplate(1);
        }
        return $theOutput;
    }
示例#4
0
	/**
	 * Save the config to file
	 * 
	 * @param array $formVars
	 * @return void
	 */
	function saveJqConf($formVars)
	{
		if ($this->createFolder()) {
			t3lib_div::writeFile($this->configDir.'t3jquery.cfg', serialize($formVars));
		}
	}
 /**
  * Install translations for all selected languages for an extension
  *
  * @param string $extKey		The extension key to install the translations for
  * @param string $lang		Language code of translation to fetch
  * @param string $mirrorURL		Mirror URL to fetch data from
  * @return mixed	true on success, error string on fauilure
  */
 function updateTranslation($extKey, $lang, $mirrorURL)
 {
     $l10n = $this->fetchTranslation($extKey, $lang, $mirrorURL);
     if (is_array($l10n)) {
         $file = PATH_site . 'typo3temp/' . $extKey . '-l10n-' . $lang . '.zip';
         $path = 'l10n/' . $lang . '/';
         if (!is_dir(PATH_typo3conf . $path)) {
             t3lib_div::mkdir_deep(PATH_typo3conf, $path);
         }
         t3lib_div::writeFile($file, $l10n[0]);
         if (tx_em_Tools::unzip($file, PATH_typo3conf . $path)) {
             return TRUE;
         }
     }
     return FALSE;
 }
示例#6
0
 /**
  * Creates an empty dummy file with a unique file name in the calling
  * extension's upload directory.
  *
  * @param string $fileName
  *        path of the dummy file to create, relative to the calling
  *        extension's upload directory, must not be empty
  * @param string $content
  *        string content for the file to create, may be empty
  *
  * @return string
  *         the absolute path of the created dummy file, will not be empty
  *
  * @throws t3lib_exception
  */
 public function createDummyFile($fileName = 'test.txt', $content = '')
 {
     $this->createDummyUploadFolder();
     $uniqueFileName = $this->getUniqueFileOrFolderPath($fileName);
     if (!t3lib_div::writeFile($uniqueFileName, $content)) {
         throw new t3lib_exception('The file ' . $uniqueFileName . ' could not be created.', 1334439291);
     }
     $this->addToDummyFileList($uniqueFileName);
     return $uniqueFileName;
 }
 /**
  * this method calls the main methods from the handler classes
  * merges the results with the data from the skin, and cache it
  *
  * @return void
  */
 protected function rebuildCache()
 {
     // ask the handlerClass to kindly rebuild our data
     $this->handler->generate();
     // get all Icons registered from skins, merge with core-Icon-List
     $availableSkinIcons = (array) $GLOBALS['TBE_STYLES']['spriteIconApi']['coreSpriteImageNames'];
     foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinName => $skinData) {
         $availableSkinIcons = array_merge($availableSkinIcons, (array) $skinData['availableSpriteIcons']);
     }
     // merge icon names whith them provided by the skin,
     // registered from "complete sprites" and the ones detected
     // by the handlerclass
     $this->iconNames = array_merge($availableSkinIcons, (array) $GLOBALS['TBE_STYLES']['spritemanager']['spriteIconsAvailable'], $this->handler->getAvailableIconNames());
     // serialize found icons, and cache them to file
     $cacheString = addslashes(serialize($this->iconNames));
     $fileContent = '<?php $GLOBALS[\'TBE_STYLES\'][\'spriteIconApi\'][\'iconsAvailable\'] = unserialize(stripslashes(\'' . $cacheString . '\')); ?>';
     // delete old cache files
     $oldFiles = t3lib_div::getFilesInDir(PATH_site . self::$tempPath, 'inc', 1);
     foreach ($oldFiles as $file) {
         @unlink($file);
     }
     // and write the new one
     t3lib_div::writeFile($this->tempFileName, $fileContent);
 }
 /**
  * Transformation handler: 'ts_images' / direction: "db"
  * Processing images inserted in the RTE.
  * This is used when content goes from the RTE to the database.
  * Images inserted in the RTE has an absolute URL applied to the src attribute. This URL is converted to a relative URL
  * If it turns out that the URL is from another website than the current the image is read from that external URL and moved to the local server.
  * Also "magic" images are processed here.
  *
  * @param	string		The content from RTE going to Database
  * @return	string		Processed content
  */
 function TS_images_db($value)
 {
     // Split content by <img> tags and traverse the resulting array for processing:
     $imgSplit = $this->splitTags('img', $value);
     foreach ($imgSplit as $k => $v) {
         if ($k % 2) {
             // image found, do processing:
             // Init
             $attribArray = $this->get_tag_attributes_classic($v, 1);
             $siteUrl = $this->siteUrl();
             $sitePath = str_replace(t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
             $absRef = trim($attribArray['src']);
             // It's always a absolute URL coming from the RTE into the Database.
             // make path absolute if it is relative and we have a site path wich is not '/'
             $pI = pathinfo($absRef);
             if ($sitePath and !$pI['scheme'] && t3lib_div::isFirstPartOfStr($absRef, $sitePath)) {
                 // if site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
                 $absRef = substr($absRef, strlen($sitePath));
                 $absRef = $siteUrl . $absRef;
             }
             // External image from another URL? In that case, fetch image (unless disabled feature).
             if (!t3lib_div::isFirstPartOfStr($absRef, $siteUrl) && !$this->procOptions['dontFetchExtPictures']) {
                 $externalFile = $this->getUrl($absRef);
                 // Get it
                 if ($externalFile) {
                     $pU = parse_url($absRef);
                     $pI = pathinfo($pU['path']);
                     if (t3lib_div::inList('gif,png,jpeg,jpg', strtolower($pI['extension']))) {
                         $filename = t3lib_div::shortMD5($absRef) . '.' . $pI['extension'];
                         $origFilePath = PATH_site . $this->rteImageStorageDir() . 'RTEmagicP_' . $filename;
                         $C_origFilePath = PATH_site . $this->rteImageStorageDir() . 'RTEmagicC_' . $filename . '.' . $pI['extension'];
                         if (!@is_file($origFilePath)) {
                             t3lib_div::writeFile($origFilePath, $externalFile);
                             t3lib_div::writeFile($C_origFilePath, $externalFile);
                         }
                         $absRef = $siteUrl . $this->rteImageStorageDir() . 'RTEmagicC_' . $filename . '.' . $pI['extension'];
                         $attribArray['src'] = $absRef;
                         $params = t3lib_div::implodeAttributes($attribArray, 1);
                         $imgSplit[$k] = '<img ' . $params . ' />';
                     }
                 }
             }
             // Check image as local file (siteURL equals the one of the image)
             if (strpos($absRef, 'http://') === FALSE and strpos($absRef, 'https://') === FALSE and strpos($absRef, 'ftp://') === FALSE) {
                 //XCLASS changed from: if (t3lib_div::isFirstPartOfStr($absRef,$siteUrl))	{
                 $path = rawurldecode(substr($absRef, strlen($siteUrl)));
                 // Rel-path, rawurldecoded for special characters.
                 $path = $absRef;
                 //XCLASS added
                 $filepath = t3lib_div::getFileAbsFileName($path);
                 // Abs filepath, locked to relative path of this project.
                 // Check file existence (in relative dir to this installation!)
                 if ($filepath && @is_file($filepath)) {
                     // If "magic image":
                     $pathPre = $this->rteImageStorageDir() . 'RTEmagicC_';
                     if (t3lib_div::isFirstPartOfStr($path, $pathPre)) {
                         // Find original file:
                         $pI = pathinfo(substr($path, strlen($pathPre)));
                         $filename = substr($pI['basename'], 0, -strlen('.' . $pI['extension']));
                         $origFilePath = PATH_site . $this->rteImageStorageDir() . 'RTEmagicP_' . $filename;
                         if (@is_file($origFilePath)) {
                             $imgObj = t3lib_div::makeInstance('t3lib_stdGraphic');
                             $imgObj->init();
                             $imgObj->mayScaleUp = 0;
                             $imgObj->tempPath = PATH_site . $imgObj->tempPath;
                             $curInfo = $imgObj->getImageDimensions($filepath);
                             // Image dimensions of the current image
                             $curWH = $this->getWHFromAttribs($attribArray);
                             // Image dimensions as set in the image tag
                             // Compare dimensions:
                             if ($curWH[0] != $curInfo[0] || $curWH[1] != $curInfo[1]) {
                                 $origImgInfo = $imgObj->getImageDimensions($origFilePath);
                                 // Image dimensions of the current image
                                 $cW = $curWH[0];
                                 $cH = $curWH[1];
                                 $cH = 1000;
                                 // Make the image based on the width solely...
                                 $imgI = $imgObj->imageMagickConvert($origFilePath, $pI['extension'], $cW . 'm', $cH . 'm');
                                 if ($imgI[3]) {
                                     $fI = pathinfo($imgI[3]);
                                     @copy($imgI[3], $filepath);
                                     // Override the child file
                                     // Removing width and heigth form style attribute
                                     $attribArray['style'] = preg_replace('/((?:^|)\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
                                     $attribArray['width'] = $imgI[0];
                                     $attribArray['height'] = $imgI[1];
                                     $params = t3lib_div::implodeAttributes($attribArray, 1);
                                     $imgSplit[$k] = '<img ' . $params . ' />';
                                 }
                             }
                         }
                     } elseif ($this->procOptions['plainImageMode']) {
                         // If "plain image" has been configured:
                         // Image dimensions as set in the image tag, if any
                         $curWH = $this->getWHFromAttribs($attribArray);
                         if ($curWH[0]) {
                             $attribArray['width'] = $curWH[0];
                         }
                         if ($curWH[1]) {
                             $attribArray['height'] = $curWH[1];
                         }
                         // Removing width and heigth form style attribute
                         $attribArray['style'] = preg_replace('/((?:^|)\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
                         // Finding dimensions of image file:
                         $fI = @getimagesize($filepath);
                         // Perform corrections to aspect ratio based on configuration:
                         switch ((string) $this->procOptions['plainImageMode']) {
                             case 'lockDimensions':
                                 $attribArray['width'] = $fI[0];
                                 $attribArray['height'] = $fI[1];
                                 break;
                             case 'lockRatioWhenSmaller':
                                 // If the ratio has to be smaller, then first set the width...:
                                 if ($attribArray['width'] > $fI[0]) {
                                     $attribArray['width'] = $fI[0];
                                 }
                             case 'lockRatio':
                                 if ($fI[0] > 0) {
                                     $attribArray['height'] = round($attribArray['width'] * ($fI[1] / $fI[0]));
                                 }
                                 break;
                         }
                         // Compile the image tag again:
                         $params = t3lib_div::implodeAttributes($attribArray, 1);
                         $imgSplit[$k] = '<img ' . $params . ' />';
                     }
                 } else {
                     // Remove image if it was not found in a proper position on the server!
                     // Commented out; removing the image tag might not be that logical...
                     #$imgSplit[$k]='';
                 }
             }
             // Convert abs to rel url
             if ($imgSplit[$k]) {
                 $attribArray = $this->get_tag_attributes_classic($imgSplit[$k], 1);
                 $absRef = trim($attribArray['src']);
                 if (t3lib_div::isFirstPartOfStr($absRef, $siteUrl)) {
                     $attribArray['src'] = $this->relBackPath . substr($absRef, strlen($siteUrl));
                     if (!isset($attribArray['alt'])) {
                         $attribArray['alt'] = '';
                     }
                     // Must have alt-attribute for XHTML compliance.
                     $imgSplit[$k] = '<img ' . t3lib_div::implodeAttributes($attribArray, 1, 1) . ' />';
                 }
             }
         }
     }
     return implode('', $imgSplit);
 }
 /**
  * @test
  */
 function addMethodFromTemplateToNewClass()
 {
     $templateClassFileObject = $this->parser->parseFile(t3lib_extmgm::extPath('php_parser_api') . 'Resources/Private/Templates/MethodTemplates.php');
     $getPropertyMethod = $templateClassFileObject->getFirstClass()->getMethod('getPropertyName');
     $newClassFileObject = new Tx_PhpParser_Domain_Model_File();
     $newClassName = 'Tx_PhpParser_Test_NewClassWithTemplateMethod';
     $newClass = new Tx_PhpParser_Domain_Model_Class($newClassName);
     $newClass->addMethod($getPropertyMethod);
     $newClassFileObject->addClass($newClass);
     $newClassFilePath = $this->testDir . 'NewClassWithTemplateMethod.php';
     t3lib_div::writeFile($newClassFilePath, "<?php\n\n" . $this->printer->renderFileObject($newClassFileObject) . "\n?>");
     $this->assertTrue(file_exists($newClassFilePath));
     require_once $newClassFilePath;
     $this->assertTrue(class_exists($newClassName));
     $this->compareClasses($newClassFileObject, $newClassFilePath);
 }
示例#10
0
	/**
	 * Renders the display of DS/TO creation directly from a file
	 *
	 * @return	void
	 */
	function renderFile()	{
		global $TYPO3_DB;

		if (@is_file($this->displayFile) && t3lib_div::getFileAbsFileName($this->displayFile))		{

				// Converting GPvars into a "cmd" value:
			$cmd = '';
			$msg = array();
			if (t3lib_div::_GP('_load_ds_xml'))	{	// Loading DS from XML or TO uid
				$cmd = 'load_ds_xml';
			} elseif (t3lib_div::_GP('_clear'))	{	// Resetting mapping/DS
				$cmd = 'clear';
			} elseif (t3lib_div::_GP('_saveDSandTO'))	{	// Saving DS and TO to records.
				if (!strlen(trim($this->_saveDSandTO_title))) {
					$cmd = 'saveScreen';
					$flashMessage = t3lib_div::makeInstance(
						't3lib_FlashMessage',
						$GLOBALS['LANG']->getLL('errorNoToTitleDefined'),
						'',
						t3lib_FlashMessage::ERROR
					);
					$msg[] = $flashMessage->render();
				} else {
					$cmd = 'saveDSandTO';
				}
			} elseif (t3lib_div::_GP('_updateDSandTO'))	{	// Updating DS and TO
				$cmd = 'updateDSandTO';
			} elseif (t3lib_div::_GP('_showXMLDS'))	{	// Showing current DS as XML
				$cmd = 'showXMLDS';
			} elseif (t3lib_div::_GP('_preview'))	{	// Previewing mappings
				$cmd = 'preview';
			} elseif (t3lib_div::_GP('_save_data_mapping'))	{	// Saving mapping to Session
				$cmd = 'save_data_mapping';
			} elseif (t3lib_div::_GP('_updateDS')) {
				$cmd = 'updateDS';
			} elseif (t3lib_div::_GP('DS_element_DELETE'))	{
				$cmd = 'DS_element_DELETE';
			} elseif (t3lib_div::_GP('_saveScreen'))	{
				$cmd = 'saveScreen';
			} elseif (t3lib_div::_GP('_loadScreen'))	{
				$cmd = 'loadScreen';
			} elseif (t3lib_div::_GP('_save'))	{
				$cmd = 'saveUpdatedDSandTO';
			} elseif (t3lib_div::_GP('_saveExit'))	{
				$cmd = 'saveUpdatedDSandTOandExit';
			}

				// Init settings:
			$this->editDataStruct=1;	// Edit DS...
			$content='';

				// Checking Storage Folder PID:
			if (!count($this->storageFolders))	{
				$msg[] = t3lib_iconWorks::getSpriteIcon('status-dialog-error') . '<strong>'.$GLOBALS['LANG']->getLL('error').'</strong> '.$GLOBALS['LANG']->getLL('errorNoStorageFolder');
			}

				// Session data
			$this->sessionKey = $this->MCONF['name'] . '_mappingInfo:' . $this->_load_ds_xml_to;
			if ($cmd=='clear')	{	// Reset session data:
				$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
				$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
			} else {	// Get session data:
				$sesDat = $GLOBALS['BE_USER']->getSessionData($this->sessionKey);
			}
			if ($this->_load_ds_xml_to) {
				$toREC = t3lib_BEfunc::getRecordWSOL('tx_templavoila_tmplobj', $this->_load_ds_xml_to);
				if ($this->staticDS) {
					$dsREC['dataprot'] = t3lib_div::getURL(t3lib_div::getFileAbsFileName($toREC['datastructure']));
				} else {
					$dsREC = t3lib_BEfunc::getRecordWSOL('tx_templavoila_datastructure', $toREC['datastructure']);
				}
			}

				// Loading DS from either XML or a Template Object (containing reference to DS)
			if ($cmd=='load_ds_xml' && ($this->_load_ds_xml_content || $this->_load_ds_xml_to))	{
				$to_uid = $this->_load_ds_xml_to;
				if ($to_uid)	{
					$tM = unserialize($toREC['templatemapping']);
					$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
					$sesDat['currentMappingInfo'] = $tM['MappingInfo'];
					$sesDat['currentMappingInfo_head'] = $tM['MappingInfo_head'];
					$ds = t3lib_div::xml2array($dsREC['dataprot']);
					$sesDat['dataStruct'] = $sesDat['autoDS'] = $ds; // Just set $ds, not only its ROOT! Otherwise <meta> will be lost.
					$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
				} else {
					$ds = t3lib_div::xml2array($this->_load_ds_xml_content);
					$sesDat = array('displayFile' => $this->displayFile, 'TO' => $this->_load_ds_xml_to, 'DS' => $this->displayUid);
					$sesDat['dataStruct'] = $sesDat['autoDS'] = $ds;
					$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
				}
			}


				// Setting Data Structure to value from session data - unless it does not exist in which case a default structure is created.
			$dataStruct = is_array($sesDat['autoDS']) ? $sesDat['autoDS'] : array(
				'meta' => array(
					'langDisable' => '1',
				),
				'ROOT' => array (
					'tx_templavoila' => array (
						'title' => 'ROOT',
						'description' => $GLOBALS['LANG']->getLL('rootDescription'),
					),
					'type' => 'array',
					'el' => array()
				)
			);

				// Setting Current Mapping information to session variable content OR blank if none exists.
			$currentMappingInfo = is_array($sesDat['currentMappingInfo']) ? $sesDat['currentMappingInfo'] : array();
			$this->cleanUpMappingInfoAccordingToDS($currentMappingInfo,$dataStruct);	// This will clean up the Current Mapping info to match the Data Structure.

				// CMD switch:
			switch($cmd)	{
					// Saving incoming Mapping Data to session data:
				case 'save_data_mapping':
					$inputData = t3lib_div::_GP('dataMappingForm',1);
					if (is_array($inputData))	{
						$sesDat['currentMappingInfo'] = $currentMappingInfo = $this->array_merge_recursive_overrule($currentMappingInfo,$inputData);
						$sesDat['dataStruct'] = $dataStruct;
						$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
					}
				break;
					// Saving incoming Data Structure settings to session data:
				case 'updateDS':
					$inDS = t3lib_div::_GP('autoDS',1);
					if (is_array($inDS))	{
						$sesDat['dataStruct'] = $sesDat['autoDS'] = $dataStruct = $this->array_merge_recursive_overrule($dataStruct,$inDS);
						$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
					}
				break;
					// If DS element is requested for deletion, remove it and update session data:
				case 'DS_element_DELETE':
					$ref = explode('][',substr($this->DS_element_DELETE,1,-1));
					$this->unsetArrayPath($dataStruct,$ref);
					$sesDat['dataStruct'] = $sesDat['autoDS'] = $dataStruct;
					$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
				break;
			}

				// Creating $templatemapping array with cached mapping content:
			if (t3lib_div::inList('showXMLDS,saveDSandTO,updateDSandTO,saveUpdatedDSandTO,saveUpdatedDSandTOandExit', $cmd)) {

					// Template mapping prepared:
				$templatemapping=array();
				$templatemapping['MappingInfo'] = $currentMappingInfo;
				if (isset($sesDat['currentMappingInfo_head'])) {
					$templatemapping['MappingInfo_head'] = $sesDat['currentMappingInfo_head'];
				}

					// Getting cached data:
				reset($dataStruct);
				$fileContent = t3lib_div::getUrl($this->displayFile);
				$htmlParse = t3lib_div::makeInstance('t3lib_parsehtml');
				$relPathFix = dirname(substr($this->displayFile,strlen(PATH_site))).'/';
				$fileContent = $htmlParse->prefixResourcePath($relPathFix,$fileContent);
				$this->markupObj = t3lib_div::makeInstance('tx_templavoila_htmlmarkup');
				$contentSplittedByMapping = $this->markupObj->splitContentToMappingInfo($fileContent,$currentMappingInfo);
				$templatemapping['MappingData_cached'] = $contentSplittedByMapping['sub']['ROOT'];

				list($html_header) =  $this->markupObj->htmlParse->getAllParts($htmlParse->splitIntoBlock('head',$fileContent),1,0);
				$this->markupObj->tags = $this->head_markUpTags;	// Set up the markupObject to process only header-section tags:

				if (isset($templatemapping['MappingInfo_head'])) {
					$h_currentMappingInfo=array();
					$currentMappingInfo_head = $templatemapping['MappingInfo_head'];
					if (is_array($currentMappingInfo_head['headElementPaths']))	{
						foreach($currentMappingInfo_head['headElementPaths'] as $kk => $vv)	{
							$h_currentMappingInfo['el_'.$kk]['MAP_EL'] = $vv;
						}
					}

					$contentSplittedByMapping = $this->markupObj->splitContentToMappingInfo($html_header,$h_currentMappingInfo);
					$templatemapping['MappingData_head_cached'] = $contentSplittedByMapping;

						// Get <body> tag:
					$reg='';
					preg_match('/<body[^>]*>/i',$fileContent,$reg);
					$templatemapping['BodyTag_cached'] = $currentMappingInfo_head['addBodyTag'] ? $reg[0] : '';
				}

				if ($cmd != 'showXMLDS') {
					// Set default flags to <meta> tag
					if (!isset($dataStruct['meta'])) {
						// Make sure <meta> goes at the beginning of data structure.
						// This is not critical for typo3 but simply convinient to
						// people who used to see it at the beginning.
						$dataStruct = array_merge(array('meta'=>array()), $dataStruct);
					}
					if ($this->_saveDSandTO_type == 1) {
						// If we save a page template, set langDisable to 1 as per localization guide
						if (!isset($dataStruct['meta']['langDisable'])) {
							$dataStruct['meta']['langDisable'] = '1';
						}
					}
					else {
						// FCE defaults to inheritance
						if (!isset($dataStruct['meta']['langDisable'])) {
							$dataStruct['meta']['langDisable'] = '0';
							$dataStruct['meta']['langChildren'] = '1';
						}
					}
				}
			}

				// CMD switch:
			switch($cmd)	{
					// If it is requested to save the current DS and mapping information to a DS and TO record, then...:
				case 'saveDSandTO':
					$newID = '';
						// Init TCEmain object and store:
					$tce = t3lib_div::makeInstance("t3lib_TCEmain");
					$tce->stripslashes_values=0;


					// DS:

						// Modifying data structure with conversion of preset values for field types to actual settings:
					$storeDataStruct = $dataStruct;
					if (is_array($storeDataStruct['ROOT']['el'])) {
						$this->eTypes->substEtypeWithRealStuff($storeDataStruct['ROOT']['el'],$contentSplittedByMapping['sub']['ROOT'],$dataArr['tx_templavoila_datastructure']['NEW']['scope']);
					}
					$dataProtXML = t3lib_div::array2xml_cs($storeDataStruct,'T3DataStructure', array('useCDATA' => 1));

					if ($this->staticDS) {
						$title = preg_replace('|[/,\."\']+|', '_', $this->_saveDSandTO_title) . ' (' . ($this->_saveDSandTO_type == 1 ? 'page' : 'fce') . ').xml';
						$path = t3lib_div::getFileAbsFileName($this->_saveDSandTO_type == 2 ? $this->extConf['staticDS.']['path_fce'] : $this->extConf['staticDS.']['path_page']) . $title;
						t3lib_div::writeFile($path, $dataProtXML);
						$newID = substr($path, strlen(PATH_site));
					} else {
						$dataArr=array();
						$dataArr['tx_templavoila_datastructure']['NEW']['pid'] = intval($this->_saveDSandTO_pid);
						$dataArr['tx_templavoila_datastructure']['NEW']['title'] = $this->_saveDSandTO_title;
						$dataArr['tx_templavoila_datastructure']['NEW']['scope'] = $this->_saveDSandTO_type;
						$dataArr['tx_templavoila_datastructure']['NEW']['dataprot'] = $dataProtXML;

							// start data processing
						$tce->start($dataArr,array());
						$tce->process_datamap();
						$newID = intval($tce->substNEWwithIDs['NEW']);
					}

						// If that succeeded, create the TO as well:
					if ($newID)	{
						$dataArr=array();
						$dataArr['tx_templavoila_tmplobj']['NEW']['pid'] = intval($this->_saveDSandTO_pid);
						$dataArr['tx_templavoila_tmplobj']['NEW']['title'] = $this->_saveDSandTO_title . ' [Template]';
						$dataArr['tx_templavoila_tmplobj']['NEW']['datastructure'] = $newID;
						$dataArr['tx_templavoila_tmplobj']['NEW']['fileref'] = substr($this->displayFile, strlen(PATH_site));
						$dataArr['tx_templavoila_tmplobj']['NEW']['templatemapping'] = serialize($templatemapping);
						$dataArr['tx_templavoila_tmplobj']['NEW']['fileref_mtime'] = @filemtime($this->displayFile);
						$dataArr['tx_templavoila_tmplobj']['NEW']['fileref_md5'] = @md5_file($this->displayFile);

							// Init TCEmain object and store:
						$tce->start($dataArr,array());
						$tce->process_datamap();
						$newToID = intval($tce->substNEWwithIDs['NEW']);
						if ($newToID) {
							$msg[] = t3lib_iconWorks::getSpriteIcon('status-dialog-ok') .
								sprintf($GLOBALS['LANG']->getLL('msgDSTOSaved'),
								$dataArr['tx_templavoila_tmplobj']['NEW']['datastructure'],
								$tce->substNEWwithIDs['NEW'], $this->_saveDSandTO_pid);
						} else {
							$msg[] = t3lib_iconWorks::getSpriteIcon('status-dialog-warning') . '<strong>'.$GLOBALS['LANG']->getLL('error').':</strong> '.sprintf($GLOBALS['LANG']->getLL('errorTONotSaved'), $dataArr['tx_templavoila_tmplobj']['NEW']['datastructure']);
						}
					} else {
						$msg[] = t3lib_iconWorks::getSpriteIcon('status-dialog-warning') . ' border="0" align="top" class="absmiddle" alt="" /><strong>'.$GLOBALS['LANG']->getLL('error').':</strong> '.$GLOBALS['LANG']->getLL('errorTONotCreated');
					}

					unset($tce);
					if ($newID && $newToID) {
							//redirect to edit view
						$redirectUrl = 'index.php?file=' . rawurlencode($this->displayFile) . '&_load_ds_xml=1&_load_ds_xml_to=' . $newToID . '&uid=' . rawurlencode($newID) . '&returnUrl=' . rawurlencode('../mod2/index.php?id=' . intval($this->_saveDSandTO_pid));
						header('Location:' . t3lib_div::locationHeaderUrl($redirectUrl));
						exit;
					} else {
							// Clear cached header info because saveDSandTO always resets headers
						$sesDat['currentMappingInfo_head'] = '';
						$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
					}
				break;
					// Updating DS and TO records:
				case 'updateDSandTO':
				case 'saveUpdatedDSandTO':
				case 'saveUpdatedDSandTOandExit':

					if ($cmd == 'updateDSandTO') {
							// Looking up the records by their uids:
						$toREC = t3lib_BEfunc::getRecordWSOL('tx_templavoila_tmplobj',$this->_saveDSandTO_TOuid);
					} else {
						$toREC = t3lib_BEfunc::getRecordWSOL('tx_templavoila_tmplobj',$this->_load_ds_xml_to);
					}
					if ($this->staticDS) {
						$dsREC['uid'] = $toREC['datastructure'];
					} else {
						$dsREC = t3lib_BEfunc::getRecordWSOL('tx_templavoila_datastructure', $toREC['datastructure']);
					}

						// If they are found, continue:
					if ($toREC['uid'] && $dsREC['uid'])	{
							// Init TCEmain object and store:
						$tce = t3lib_div::makeInstance('t3lib_TCEmain');
						$tce->stripslashes_values=0;

							// Modifying data structure with conversion of preset values for field types to actual settings:
						$storeDataStruct=$dataStruct;
						if (is_array($storeDataStruct['ROOT']['el'])) {
							$this->eTypes->substEtypeWithRealStuff($storeDataStruct['ROOT']['el'],$contentSplittedByMapping['sub']['ROOT'],$dsREC['scope']);
						}
						$dataProtXML = t3lib_div::array2xml_cs($storeDataStruct,'T3DataStructure', array('useCDATA' => 1));

							// DS:
						if ($this->staticDS) {
							$path = PATH_site . $dsREC['uid'];
							t3lib_div::writeFile($path, $dataProtXML);
						} else {
							$dataArr=array();
							$dataArr['tx_templavoila_datastructure'][$dsREC['uid']]['dataprot'] = $dataProtXML;

								// process data
							$tce->start($dataArr,array());
							$tce->process_datamap();
						}

							// TO:
						$TOuid = t3lib_BEfunc::wsMapId('tx_templavoila_tmplobj',$toREC['uid']);
						$dataArr=array();
						$dataArr['tx_templavoila_tmplobj'][$TOuid]['fileref']=substr($this->displayFile,strlen(PATH_site));
						$dataArr['tx_templavoila_tmplobj'][$TOuid]['templatemapping']=serialize($templatemapping);
						$dataArr['tx_templavoila_tmplobj'][$TOuid]['fileref_mtime'] = @filemtime($this->displayFile);
						$dataArr['tx_templavoila_tmplobj'][$TOuid]['fileref_md5'] = @md5_file($this->displayFile);


						$tce->start($dataArr,array());
						$tce->process_datamap();

						unset($tce);

						$msg[] = t3lib_iconWorks::getSpriteIcon('status-dialog-notification') . sprintf($GLOBALS['LANG']->getLL('msgDSTOUpdated'), $dsREC['uid'], $toREC['uid']);

						if ($cmd == 'updateDSandTO') {
							if (!$this->_load_ds_xml_to) {
									//new created was saved to existing DS/TO, redirect to edit view
								$redirectUrl = 'index.php?file=' . rawurlencode($this->displayFile) . '&_load_ds_xml=1&_load_ds_xml_to=' . $toREC['uid'] . '&uid=' . rawurlencode($dsREC['uid']) . '&returnUrl=' . rawurlencode('../mod2/index.php?id=' . intval($this->_saveDSandTO_pid));
								header('Location:' . t3lib_div::locationHeaderUrl($redirectUrl));
								exit;
							} else {
									// Clear cached header info because updateDSandTO always resets headers
								$sesDat['currentMappingInfo_head'] = '';
								$GLOBALS['BE_USER']->setAndSaveSessionData($this->sessionKey, $sesDat);
							}
						} elseif ($cmd == 'saveUpdatedDSandTOandExit') {
							header ('Location:' . t3lib_div::locationHeaderUrl($this->returnUrl));
						}
					}
				break;
			}


				// Header:
			$tRows = array();
			$relFilePath = substr($this->displayFile, strlen(PATH_site));
			$onCl = 'return top.openUrlInWindow(\'' . t3lib_div::getIndpEnv('TYPO3_SITE_URL') . $relFilePath . '\',\'FileView\');';
			$tRows[]='
				<tr>
					<td class="bgColor5" rowspan="2">' . $this->cshItem('xMOD_tx_templavoila', 'mapping_file', $this->doc->backPath, '|') . '</td>
					<td class="bgColor5" rowspan="2"><strong>' . $GLOBALS['LANG']->getLL('templateFile') . ':</strong></td>
					<td class="bgColor4"><a href="#" onclick="' . htmlspecialchars($onCl) . '">' . htmlspecialchars($relFilePath) . '</a></td>
				</tr>
 				<tr>
					<td class="bgColor4">
						<a href="#" onclick ="openValidator(\'' .  $this->sessionKey . '\');return false;">
						' . t3lib_iconWorks::getSpriteIcon('extensions-templavoila-htmlvalidate') . '
							' . $GLOBALS['LANG']->getLL('validateTpl') . '
						</a>
					</td>
				</tr>
				<tr>
					<td class="bgColor5">&nbsp;</td>
					<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('templateObject') . ':</strong></td>
					<td class="bgColor4">' . ($toREC ? htmlspecialchars($GLOBALS['LANG']->sL($toREC['title'])) : $GLOBALS['LANG']->getLL('mappingNEW')) . '</td>
				</tr>';
			if ($this->staticDS) {
				$onClick = 'return top.openUrlInWindow(\'' . t3lib_div::getIndpEnv('TYPO3_SITE_URL') . $toREC['datastructure'] . '\',\'FileView\');';
				$tRows[]='
				<tr>
					<td class="bgColor5">&nbsp;</td>
					<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('renderDSO_XML') . ':</strong></td>
					<td class="bgColor4"><a href="#" onclick="' . htmlspecialchars($onClick) . '">'.htmlspecialchars($toREC['datastructure']).'</a></td>
				</tr>';
			} else {
				$tRows[]='
				<tr>
					<td class="bgColor5">&nbsp;</td>
					<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('renderTO_dsRecord') . ':</strong></td>
					<td class="bgColor4">' . ($dsREC ? htmlspecialchars($GLOBALS['LANG']->sL($dsREC['title'])) : $GLOBALS['LANG']->getLL('mappingNEW')) . '</td>
				</tr>';
			}

				// Write header of page:
			$content.='

				<!--
					Create Data Structure Header:
				-->
				<table border="0" cellpadding="2" cellspacing="1" id="c-toHeader">
					'.implode('',$tRows).'
				</table><br />
			';


				// Messages:
			if (is_array($msg))	{
				$content.='

					<!--
						Messages:
					-->
					'.implode('<br />',$msg).'
				';
			}


				// Generate selector box options:
				// Storage Folders for elements:
			$sf_opt=array();
			$res = $TYPO3_DB->exec_SELECTquery (
				'*',
				'pages',
				'uid IN ('.$this->storageFolders_pidList.')'.t3lib_BEfunc::deleteClause('pages'),
				'',
				'title'
			);
			while(false !== ($row = $TYPO3_DB->sql_fetch_assoc($res)))	{
				$sf_opt[]='<option value="'.htmlspecialchars($row['uid']).'">'.htmlspecialchars($row['title'].' (UID:'.$row['uid'].')').'</option>';
			}

				// Template Object records:
			$opt=array();
			$opt[]='<option value="0"></option>';
			if ($this->staticDS) {
				$res = $TYPO3_DB->exec_SELECTquery (
					'*, CASE WHEN LOCATE(' . $GLOBALS['TYPO3_DB']->fullQuoteStr('(fce)', 'tx_templavoila_tmplobj') . ', datastructure)>0 THEN 2 ELSE 1 END AS scope',
					'tx_templavoila_tmplobj',
					'pid IN ('.$this->storageFolders_pidList.') AND datastructure!=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('', 'tx_templavoila_tmplobj') .
						t3lib_BEfunc::deleteClause('tx_templavoila_tmplobj').
						t3lib_BEfunc::versioningPlaceholderClause('tx_templavoila_tmplobj'),
					'',
					'scope,title'
				);

			} else {
				$res = $TYPO3_DB->exec_SELECTquery (
					'tx_templavoila_tmplobj.*,tx_templavoila_datastructure.scope',
					'tx_templavoila_tmplobj LEFT JOIN tx_templavoila_datastructure ON tx_templavoila_datastructure.uid=tx_templavoila_tmplobj.datastructure',
					'tx_templavoila_tmplobj.pid IN ('.$this->storageFolders_pidList.') AND tx_templavoila_tmplobj.datastructure>0 '.
						t3lib_BEfunc::deleteClause('tx_templavoila_tmplobj').
						t3lib_BEfunc::versioningPlaceholderClause('tx_templavoila_tmplobj'),
					'',
					'tx_templavoila_datastructure.scope, tx_templavoila_tmplobj.pid, tx_templavoila_tmplobj.title'
				);

			}
			$storageFolderPid = 0;
			$optGroupOpen = false;
			while(false !== ($row = $TYPO3_DB->sql_fetch_assoc($res)))	{
				$scope = $row['scope'];
				unset($row['scope']);
				t3lib_BEfunc::workspaceOL('tx_templavoila_tmplobj',$row);
				if ($storageFolderPid != $row['pid']) {
					 $storageFolderPid = $row['pid'];
					 if ($optGroupOpen) {
						$opt[] = '</optgroup>';
					 }
					 $opt[] = '<optgroup label="' . htmlspecialchars($this->storageFolders[$storageFolderPid] . ' (PID: ' . $storageFolderPid . ')') . '">';
					 $optGroupOpen = true;
				}
				$opt[]= '<option value="' .htmlspecialchars($row['uid']).'" ' .
					($scope == 1 ? 'class="pagetemplate"">' : 'class="fce">') .
					 htmlspecialchars($GLOBALS['LANG']->sL($row['title']) . ' (UID:' . $row['uid'] . ')').'</option>';
			}
			if ($optGroupOpen) {
				$opt[] = '</optgroup>';
			}

				// Module Interface output begin:
			switch($cmd)	{
					// Show XML DS
				case 'showXMLDS':
					require_once(PATH_t3lib.'class.t3lib_syntaxhl.php');

						// Make instance of syntax highlight class:
					$hlObj = t3lib_div::makeInstance('t3lib_syntaxhl');

					$storeDataStruct=$dataStruct;
					if (is_array($storeDataStruct['ROOT']['el']))
						$this->eTypes->substEtypeWithRealStuff($storeDataStruct['ROOT']['el'],$contentSplittedByMapping['sub']['ROOT']);
					$dataStructureXML = t3lib_div::array2xml_cs($storeDataStruct,'T3DataStructure', array('useCDATA' => 1));

					$content.='
						<input type="submit" name="_DO_NOTHING" value="Go back" title="' . $GLOBALS['LANG']->getLL('buttonGoBack') . '" />
						<h3>'.$GLOBALS['LANG']->getLL('titleXmlConfiguration').':</h3>
						'.$this->cshItem('xMOD_tx_templavoila','mapping_file_showXMLDS',$this->doc->backPath,'|<br/>').'
						<pre>'.$hlObj->highLight_DS($dataStructureXML).'</pre>';
				break;
				case 'loadScreen':

					$content.='
						<h3>'.$GLOBALS['LANG']->getLL('titleLoadDSXml').'</h3>
						'.$this->cshItem('xMOD_tx_templavoila','mapping_file_loadDSXML',$this->doc->backPath,'|<br/>').'
						<p>'.$GLOBALS['LANG']->getLL('selectTOrecrdToLoadDSFrom').':</p>
						<select name="_load_ds_xml_to">'.implode('',$opt).'</select>
						<br />
						<p>'.$GLOBALS['LANG']->getLL('pasteDSXml').':</p>
						<textarea rows="15" name="_load_ds_xml_content" wrap="off"'.$GLOBALS['TBE_TEMPLATE']->formWidthText(48,'width:98%;','off').'></textarea>
						<br />
						<input type="submit" name="_load_ds_xml" value="'.$GLOBALS['LANG']->getLL('loadDSXml').'" />
						<input type="submit" name="_" value="' . $GLOBALS['LANG']->getLL('buttonCancel') . '" />
						';
				break;
				case 'saveScreen':

					$content.='
						<h3>' . $GLOBALS['LANG']->getLL('createDSTO') . ':</h3>
						'.$this->cshItem('xMOD_tx_templavoila','mapping_file_createDSTO',$this->doc->backPath,'|<br/>').'
						<table border="0" cellpadding="2" cellspacing="2" class="dso_table">
							<tr>
								<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('titleDSTO') . ':</strong></td>
								<td class="bgColor4"><input type="text" name="_saveDSandTO_title" /></td>
							</tr>
							<tr>
								<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('templateType') . ':</strong></td>
								<td class="bgColor4">
									<select name="_saveDSandTO_type">
										<option value="1">' . $GLOBALS['LANG']->getLL('pageTemplate') . '</option>
										<option value="2">' . $GLOBALS['LANG']->getLL('contentElement') . '</option>
										<option value="0">' . $GLOBALS['LANG']->getLL('undefined') . '</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('storeInPID') . ':</strong></td>
								<td class="bgColor4">
									<select name="_saveDSandTO_pid">
										'.implode('
										',$sf_opt).'
									</select>
								</td>
							</tr>
						</table>

						<input type="submit" name="_saveDSandTO" value="' . $GLOBALS['LANG']->getLL('createDSTOshort') . '" />
						<input type="submit" name="_" value="' . $GLOBALS['LANG']->getLL('buttonCancel') . '" />



						<h3>' . $GLOBALS['LANG']->getLL('updateDSTO') . ':</h3>
						<table border="0" cellpadding="2" cellspacing="2">
							<tr>
								<td class="bgColor5"><strong>' . $GLOBALS['LANG']->getLL('selectTO') . ':</strong></td>
								<td class="bgColor4">
									<select name="_saveDSandTO_TOuid">
										'.implode('
										',$opt).'
									</select>
								</td>
							</tr>
						</table>

						<input type="submit" name="_updateDSandTO" value="UPDATE TO (and DS)" onclick="return confirm(' . $GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->getLL('saveDSTOconfirm')) . ');" />
						<input type="submit" name="_" value="' . $GLOBALS['LANG']->getLL('buttonCancel') . '" />
						';
				break;
				default:
						// Creating menu:
					$menuItems = array();
					$menuItems[]='<input type="submit" name="_showXMLDS" value="' . $GLOBALS['LANG']->getLL('buttonShowXML') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_showXML') . '" />';
					$menuItems[]='<input type="submit" name="_clear" value="' . $GLOBALS['LANG']->getLL('buttonClearAll') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_clearAll') . '" /> ';
					$menuItems[]='<input type="submit" name="_preview" value="' . $GLOBALS['LANG']->getLL('buttonPreview') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_preview') . '" />';
					if (is_array($toREC) && is_array($dsREC)) {
						$menuItems[]='<input type="submit" name="_save" value="' . $GLOBALS['LANG']->getLL('buttonSave') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_save') . '" />';
						$menuItems[]='<input type="submit" name="_saveExit" value="' . $GLOBALS['LANG']->getLL('buttonSaveExit') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_saveExit') . '" />';
					}
					$menuItems[]='<input type="submit" name="_saveScreen" value="' . $GLOBALS['LANG']->getLL('buttonSaveAs') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_saveAs') . '" />';
					$menuItems[]='<input type="submit" name="_loadScreen" value="' . $GLOBALS['LANG']->getLL('buttonLoad') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_load') . '" />';
					$menuItems[]='<input type="submit" name="_DO_NOTHING" value="' . $GLOBALS['LANG']->getLL('buttonRefresh') . '" title="' . $GLOBALS['LANG']->getLL('buttonTitle_refresh') . '" />';

					$menuContent = '

						<!--
							Menu for creation Data Structures / Template Objects
						-->
						<table border="0" cellpadding="2" cellspacing="2" id="c-toMenu">
							<tr class="bgColor5">
								<td>'.implode('</td>
								<td>',$menuItems).'</td>
							</tr>
						</table>
					';

					$content.='

					<!--
						Data Structure creation table:
					-->
					<h3>' . $this->cshItem('xMOD_tx_templavoila','mapping_file',$this->doc->backPath,'|') . $GLOBALS['LANG']->getLL('buildingDS') . ':</h3>' .
						$this->renderTemplateMapper($this->displayFile,$this->displayPath,$dataStruct,$currentMappingInfo,$menuContent);
				break;
			}
		}

		$this->content.=$this->doc->section('',$content,0,1);
	}
示例#11
0
 /**
  * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
  * Accepts an additional subdirectory in the file path!
  *
  * @param	string		Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
  * @param	string		Content string to write
  * @return	string		Returns false on success, otherwise an error string telling about the problem.
  */
 function writeFileToTypo3tempDir($filepath, $content)
 {
     // Parse filepath into directory and basename:
     $fI = pathinfo($filepath);
     $fI['dirname'] .= '/';
     // Check parts:
     if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
         if (defined('PATH_site')) {
             $dirName = PATH_site . 'typo3temp/';
             // Setting main temporary directory name (standard)
             if (@is_dir($dirName)) {
                 if (t3lib_div::isFirstPartOfStr($fI['dirname'], $dirName)) {
                     // Checking if the "subdir" is found:
                     $subdir = substr($fI['dirname'], strlen($dirName));
                     if ($subdir) {
                         if (ereg('^[[:alnum:]_]+\\/$', $subdir)) {
                             $dirName .= $subdir;
                             if (!@is_dir($dirName)) {
                                 t3lib_div::mkdir($dirName);
                             }
                         } else {
                             return 'Subdir, "' . $subdir . '", was NOT on the form "[a-z]/"';
                         }
                     }
                     // Checking dir-name again (sub-dir might have been created):
                     if (@is_dir($dirName)) {
                         if ($filepath == $dirName . $fI['basename']) {
                             t3lib_div::writeFile($filepath, $content);
                             if (!@is_file($filepath)) {
                                 return 'File not written to disk! Write permission error in filesystem?';
                             }
                         } else {
                             return 'Calculated filelocation didn\'t match input $filepath!';
                         }
                     } else {
                         return '"' . $dirName . '" is not a directory!';
                     }
                 } else {
                     return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
                 }
             } else {
                 return 'PATH_site + "typo3temp/" was not a directory!';
             }
         } else {
             return 'PATH_site constant was NOT defined!';
         }
     } else {
         return 'Input filepath "' . $filepath . '" was generally invalid!';
     }
 }
    /**
     * Renders the template selector.
     *
     * @param	integer		Position id. Can be positive and negative depending of where the new page is going: Negative always points to a position AFTER the page having the abs. value of the positionId. Positive numbers means to create as the first subpage to another page.
     * @param	string		$templateType: The template type, 'tmplobj' or 't3d'
     * @return	string		HTML output containing a table with the template selector
     */
    function renderTemplateSelector($positionPid, $templateType = 'tmplobj')
    {
        global $LANG, $TYPO3_DB;
        $storageFolderPID = $this->apiObj->getStorageFolderPid($positionPid);
        $tmplHTML = array();
        $defaultIcon = $this->doc->backPath . '../' . t3lib_extMgm::siteRelPath($this->extKey) . 'res1/default_previewicon.gif';
        // look for TCEFORM.pages.tx_templavoila_ds.removeItems / TCEFORM.pages.tx_templavoila_to.removeItems
        $disallowedPageTemplateItems = $this->getDisallowedTSconfigItemsByFieldName($positionPid, 'tx_templavoila_ds');
        $disallowedDesignTemplateItems = $this->getDisallowedTSconfigItemsByFieldName($positionPid, 'tx_templavoila_to');
        switch ($templateType) {
            case 'tmplobj':
                // Create the "Default template" entry
                //Fetch Default TO
                $fakeRow = array('uid' => abs($positionPid));
                $defaultTO = $this->pObj->apiObj->getContentTree_fetchPageTemplateObject($fakeRow);
                // Create the "Default template" entry
                if ($defaultTO['previewicon']) {
                    $previewIconFilename = @is_file(PATH_site . 'uploads/tx_templavoila/' . $defaultTO['previewicon']) ? $GLOBALS['BACK_PATH'] . '../' . 'uploads/tx_templavoila/' . $defaultTO['previewicon'] : $defaultIcon;
                } else {
                    $previewIconFilename = $defaultIcon;
                }
                $previewIcon = '<input type="image" class="c-inputButton" name="i0" value="0" src="' . $previewIconFilename . '" title="" />';
                $description = $defaultTO['description'] ? htmlspecialchars($defaultTO['description']) : $LANG->getLL('template_descriptiondefault', 1);
                $tmplHTML[] = '<table style="float:left; width: 100%;" valign="top">
				<tr>
					<td colspan="2" nowrap="nowrap">
						<h3 class="bgColor3-20">' . htmlspecialchars($LANG->getLL('template_titleInherit')) . '</h3>
					</td>
				</tr><tr>
					<td valign="top">' . $previewIcon . '</td>
					<td width="120" valign="top">
						<p><h4>' . htmlspecialchars($LANG->sL($defaultTO['title'])) . '</h4>' . $LANG->sL($description) . '</p>
					</td>
				</tr>
				</table>';
                $dsRepo = t3lib_div::makeInstance('tx_templavoila_datastructureRepository');
                $toRepo = t3lib_div::makeInstance('tx_templavoila_templateRepository');
                $dsList = $dsRepo->getDatastructuresByStoragePidAndScope($storageFolderPID, tx_templavoila_datastructure::SCOPE_PAGE);
                foreach ($dsList as $dsObj) {
                    if (t3lib_div::inList($disallowedPageTemplateItems, $dsObj->getKey()) || !$dsObj->isPermittedForUser()) {
                        continue;
                    }
                    $toList = $toRepo->getTemplatesByDatastructure($dsObj, $storageFolderPID);
                    foreach ($toList as $toObj) {
                        if ($toObj->getKey() === $defaultTO['uid'] || !$toObj->isPermittedForUser() || t3lib_div::inList($disallowedDesignTemplateItems, $toObj->getKey())) {
                            continue;
                        }
                        $tmpFilename = $toObj->getIcon();
                        $previewIconFilename = @is_file(PATH_site . substr($tmpFilename, 3)) ? $GLOBALS['BACK_PATH'] . $tmpFilename : $defaultIcon;
                        // Note: we cannot use value of image input element because MSIE replaces this value with mouse coordinates! Thus on click we set value to a hidden field. See http://bugs.typo3.org/view.php?id=3376
                        $previewIcon = '<input type="image" class="c-inputButton" name="i' . $row['uid'] . '" onclick="document.getElementById(\'data_tx_templavoila_to\').value=' . $toObj->getKey() . '" src="' . $previewIconFilename . '" title="" />';
                        $description = $toObj->getDescription() ? htmlspecialchars($toObj->getDescription()) : $LANG->getLL('template_nodescriptionavailable');
                        $tmplHTML[] = '<table style="width: 100%;" valign="top"><tr><td colspan="2" nowrap="nowrap"><h3 class="bgColor3-20">' . htmlspecialchars($toObj->getLabel()) . '</h3></td></tr>' . '<tr><td valign="top">' . $previewIcon . '</td><td width="120" valign="top"><p>' . $LANG->sL($description) . '</p></td></tr></table>';
                    }
                }
                $tmplHTML[] = '<input type="hidden" id="data_tx_templavoila_to" name="data[tx_templavoila_to]" value="0" />';
                break;
            case 't3d':
                if (t3lib_extMgm::isLoaded('impexp')) {
                    // Read template files from a certain folder. I suggest this is configurable in some way. But here it is hardcoded for initial tests.
                    $templateFolder = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . '/export/templates/';
                    $files = t3lib_div::getFilesInDir($templateFolder, 't3d,xml', 1, 1);
                    // Traverse the files found:
                    foreach ($files as $absPath) {
                        // Initialize the import object:
                        $import = $this->getImportObject();
                        if ($import->loadFile($absPath)) {
                            if (is_array($import->dat['header']['pagetree'])) {
                                // This means there are pages in the file, we like that...:
                                // Page tree:
                                reset($import->dat['header']['pagetree']);
                                $pageTree = current($import->dat['header']['pagetree']);
                                // Thumbnail icon:
                                if (is_array($import->dat['header']['thumbnail'])) {
                                    $pI = pathinfo($import->dat['header']['thumbnail']['filename']);
                                    if (t3lib_div::inList('gif,jpg,png,jpeg', strtolower($pI['extension']))) {
                                        // Construct filename and write it:
                                        $fileName = PATH_site . 'typo3temp/importthumb_' . t3lib_div::shortMD5($absPath) . '.' . $pI['extension'];
                                        t3lib_div::writeFile($fileName, $import->dat['header']['thumbnail']['content']);
                                        // Check that the image really is an image and not a malicious PHP script...
                                        if (getimagesize($fileName)) {
                                            // Create icon tag:
                                            $iconTag = '<img src="' . $this->doc->backPath . '../' . substr($fileName, strlen(PATH_site)) . '" ' . $import->dat['header']['thumbnail']['imgInfo'][3] . ' vspace="5" style="border: solid black 1px;" alt="" />';
                                        } else {
                                            t3lib_div::unlink_tempfile($fileName);
                                            $iconTag = '';
                                        }
                                    }
                                }
                                $aTagB = '<a href="' . htmlspecialchars(t3lib_div::linkThisScript(array('templateFile' => $absPath))) . '">';
                                $aTagE = '</a>';
                                $tmplHTML[] = '<table style="float:left; width: 100%;" valign="top"><tr><td colspan="2" nowrap="nowrap">
					<h3 class="bgColor3-20">' . $aTagB . htmlspecialchars($import->dat['header']['meta']['title'] ? $import->dat['header']['meta']['title'] : basename($absPath)) . $aTagE . '</h3></td></tr>
					<tr><td valign="top">' . $aTagB . $iconTag . $aTagE . '</td><td valign="top"><p>' . htmlspecialchars($import->dat['header']['meta']['description']) . '</p>
						<em>Levels: ' . (count($pageTree) > 1 ? 'Deep structure' : 'Single page') . '<br/>
						File: ' . basename($absPath) . '</em></td></tr></table>';
                            }
                        }
                    }
                }
                break;
        }
        if (is_array($tmplHTML) && count($tmplHTML)) {
            $counter = 0;
            $content .= '<table>';
            foreach ($tmplHTML as $single) {
                $content .= ($counter ? '' : '<tr>') . '<td valign="top">' . $single . '</td>' . ($counter ? '</tr>' : '');
                $counter++;
                if ($counter > 1) {
                    $counter = 0;
                }
            }
            $content .= '</table>';
        }
        return $content;
    }
    /**
     * Renders the template selector.
     *
     * @param	integer		Position id. Can be positive and negative depending of where the new page is going: Negative always points to a position AFTER the page having the abs. value of the positionId. Positive numbers means to create as the first subpage to another page.
     * @param	string		$templateType: The template type, 'tmplobj' or 't3d'
     * @return	string		HTML output containing a table with the template selector
     */
    function renderTemplateSelector($positionPid, $templateType = 'tmplobj')
    {
        global $LANG, $TYPO3_DB;
        $storageFolderPID = $this->apiObj->getStorageFolderPid($positionPid);
        $tmplHTML = array();
        switch ($templateType) {
            case 'tmplobj':
                // Create the "Default template" entry
                $previewIconFilename = $GLOBALS['BACK_PATH'] . '../' . t3lib_extMgm::siteRelPath($this->extKey) . 'res1/default_previewicon.gif';
                $previewIcon = '<input type="image" class="c-inputButton" name="i0" value="0" src="' . $previewIconFilename . '" title="" />';
                $description = htmlspecialchars($LANG->getLL('template_descriptiondefault'));
                $tmplHTML[] = '<table style="float:left; width: 100%;" valign="top"><tr><td colspan="2" nowrap="nowrap">
					<h3 class="bgColor3-20">' . htmlspecialchars($LANG->getLL('template_titledefault')) . '</h3></td></tr>
					<tr><td valign="top">' . $previewIcon . '</td><td width="120" valign="top"><p>' . $description . '</p></td></tr></table>';
                $tTO = 'tx_templavoila_tmplobj';
                $tDS = 'tx_templavoila_datastructure';
                $where = $tTO . '.parent=0 AND ' . $tTO . '.pid=' . intval($storageFolderPID) . ' AND ' . $tDS . '.scope=1' . $this->buildRecordWhere($tTO) . $this->buildRecordWhere($tDS) . t3lib_befunc::deleteClause($tTO) . t3lib_befunc::deleteClause($tDS) . t3lib_BEfunc::versioningPlaceholderClause($tTO) . t3lib_BEfunc::versioningPlaceholderClause($tDS);
                $res = $TYPO3_DB->exec_SELECTquery($tTO . '.*', $tTO . ' LEFT JOIN ' . $tDS . ' ON ' . $tTO . '.datastructure = ' . $tDS . '.uid', $where);
                while (false !== ($row = $TYPO3_DB->sql_fetch_assoc($res))) {
                    // Check if preview icon exists, otherwise use default icon:
                    $tmpFilename = 'uploads/tx_templavoila/' . $row['previewicon'];
                    $previewIconFilename = @is_file(PATH_site . $tmpFilename) ? $GLOBALS['BACK_PATH'] . '../' . $tmpFilename : $GLOBALS['BACK_PATH'] . '../' . t3lib_extMgm::siteRelPath($this->extKey) . 'res1/default_previewicon.gif';
                    // Note: we cannot use value of image input element because MSIE replaces this value with mouse coordinates! Thus on click we set value to a hidden field. See http://bugs.typo3.org/view.php?id=3376
                    $previewIcon = '<input type="image" class="c-inputButton" name="i' . $row['uid'] . '" onclick="document.getElementById(\'data_tx_templavoila_to\').value=' . $row['uid'] . '" src="' . $previewIconFilename . '" title="" />';
                    $description = $row['description'] ? htmlspecialchars($row['description']) : $LANG->getLL('template_nodescriptionavailable');
                    $tmplHTML[] = '<table style="width: 100%;" valign="top"><tr><td colspan="2" nowrap="nowrap"><h3 class="bgColor3-20">' . htmlspecialchars($row['title']) . '</h3></td></tr>' . '<tr><td valign="top">' . $previewIcon . '</td><td width="120" valign="top"><p>' . $description . '</p></td></tr></table>';
                }
                $tmplHTML[] = '<input type="hidden" id="data_tx_templavoila_to" name="data[tx_templavoila_to]" value="0" />';
                break;
            case 't3d':
                if (t3lib_extMgm::isLoaded('impexp')) {
                    // Read template files from a certain folder. I suggest this is configurable in some way. But here it is hardcoded for initial tests.
                    $templateFolder = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . '/export/templates/';
                    $files = t3lib_div::getFilesInDir($templateFolder, 't3d,xml', 1, 1);
                    // Traverse the files found:
                    foreach ($files as $absPath) {
                        // Initialize the import object:
                        $import = $this->getImportObject();
                        if ($import->loadFile($absPath)) {
                            if (is_array($import->dat['header']['pagetree'])) {
                                // This means there are pages in the file, we like that...:
                                // Page tree:
                                reset($import->dat['header']['pagetree']);
                                $pageTree = current($import->dat['header']['pagetree']);
                                // Thumbnail icon:
                                if (is_array($import->dat['header']['thumbnail'])) {
                                    $pI = pathinfo($import->dat['header']['thumbnail']['filename']);
                                    if (t3lib_div::inList('gif,jpg,png,jpeg', strtolower($pI['extension']))) {
                                        // Construct filename and write it:
                                        $fileName = PATH_site . 'typo3temp/importthumb_' . t3lib_div::shortMD5($absPath) . '.' . $pI['extension'];
                                        t3lib_div::writeFile($fileName, $import->dat['header']['thumbnail']['content']);
                                        // Check that the image really is an image and not a malicious PHP script...
                                        if (getimagesize($fileName)) {
                                            // Create icon tag:
                                            $iconTag = '<img src="' . $this->doc->backPath . '../' . substr($fileName, strlen(PATH_site)) . '" ' . $import->dat['header']['thumbnail']['imgInfo'][3] . ' vspace="5" style="border: solid black 1px;" alt="" />';
                                        } else {
                                            t3lib_div::unlink_tempfile($fileName);
                                            $iconTag = '';
                                        }
                                    }
                                }
                                $aTagB = '<a href="' . htmlspecialchars(t3lib_div::linkThisScript(array('templateFile' => $absPath))) . '">';
                                $aTagE = '</a>';
                                $tmplHTML[] = '<table style="float:left; width: 100%;" valign="top"><tr><td colspan="2" nowrap="nowrap">
					<h3 class="bgColor3-20">' . $aTagB . htmlspecialchars($import->dat['header']['meta']['title'] ? $import->dat['header']['meta']['title'] : basename($absPath)) . $aTagE . '</h3></td></tr>
					<tr><td valign="top">' . $aTagB . $iconTag . $aTagE . '</td><td valign="top"><p>' . htmlspecialchars($import->dat['header']['meta']['description']) . '</p>
						<em>Levels: ' . (count($pageTree) > 1 ? 'Deep structure' : 'Single page') . '<br/>
						File: ' . basename($absPath) . '</em></td></tr></table>';
                            }
                        }
                    }
                }
                break;
        }
        if (is_array($tmplHTML) && count($tmplHTML)) {
            $counter = 0;
            $content .= '<table>';
            foreach ($tmplHTML as $single) {
                $content .= ($counter ? '' : '<tr>') . '<td valign="top">' . $single . '</td>' . ($counter ? '</tr>' : '');
                $counter++;
                if ($counter > 1) {
                    $counter = 0;
                }
            }
            $content .= '</table>';
        }
        return $content;
    }
 /**
  * Produce a diff (using the "diff" application) between two strings
  * The function will write the two input strings to temporary files, then execute the diff program, delete the temp files and return the result.
  *
  * @param	string		String 1
  * @param	string		String 2
  * @return	array		The result from the exec() function call.
  * @access private
  */
 function getDiff($str1, $str2)
 {
     // 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;
     $res = array();
     t3lib_utility_Command::exec($cmd, $res);
     unlink($file1);
     unlink($file2);
     return $res;
 }
示例#15
0
 /**
  * Builds an initial class file to test parsing and modifiying of existing classes
  *
  * This class file is generated based on the CodeTemplates
  * @param string $modelName
  */
 function generateInitialModelClassFile($modelName)
 {
     $domainObject = $this->buildDomainObject($modelName);
     $classFileContent = $this->codeGenerator->generateDomainObjectCode($domainObject, $this->extension);
     $modelClassDir = 'Classes/Domain/Model/';
     $result = t3lib_div::mkdir_deep($this->extension->getExtensionDir(), $modelClassDir);
     $absModelClassDir = $this->extension->getExtensionDir() . $modelClassDir;
     $this->assertTrue(is_dir($absModelClassDir), 'Directory ' . $absModelClassDir . ' was not created');
     $modelClassPath = $absModelClassDir . $domainObject->getName() . '.php';
     t3lib_div::writeFile($modelClassPath, $classFileContent);
 }
 /**
  * Interface function. This will be called from the sprite manager to
  * refresh all caches.
  *
  * @return void
  */
 public function generate()
 {
     // generate Icons for all TCA tables
     $this->buildTcaSpriteIcons();
     // generate IconData for single Icons registered
     $this->buildExtensionSpriteIcons();
     // include registered Sprites
     $this->loadRegisteredSprites();
     // cache results in the CSS file
     t3lib_div::writeFile($this->cssTcaFile, $this->styleSheetData);
 }
 protected function processCSSfiles()
 {
     // fetch all remaining css contents
     $this->getCSSfiles();
     // minify, compress and merging
     foreach ($this->css as $relation => $cssByRelation) {
         foreach ($cssByRelation as $media => $cssByMedia) {
             $mergedContent = '';
             $firstFreeIndex = -1;
             foreach ($cssByMedia as $index => $cssProperties) {
                 $newFile = '';
                 // file should be minified
                 if ($this->extConfig['css.']['minify.']['enable'] === '1' && !$cssProperties['minify-ignore']) {
                     $newFile = $this->minifyCSSfile($cssProperties);
                 }
                 // file should be merged
                 if ($this->extConfig['css.']['merge.']['enable'] === '1' && !$cssProperties['merge-ignore']) {
                     if ($firstFreeIndex < 0) {
                         $firstFreeIndex = $index;
                     }
                     // add content
                     $mergedContent .= $cssProperties['content'] . LF;
                     // remove file from array
                     unset($this->css[$relation][$media][$index]);
                     // we doesn't need to compress or add a new file to the array,
                     // because the last one will finally not be needed anymore
                     continue;
                 }
                 // file should be compressed instead?
                 if ($this->extConfig['css.']['compress.']['enable'] === '1' && function_exists('gzcompress') && !$cssProperties['compress-ignore']) {
                     $newFile = $this->compressCSSfile($cssProperties);
                 }
                 // minification or compression was used
                 if ($newFile !== '') {
                     $this->css[$relation][$media][$index]['file'] = $newFile;
                     $this->css[$relation][$media][$index]['content'] = $cssProperties['content'];
                     $this->css[$relation][$media][$index]['basename'] = $cssProperties['basename'];
                 }
             }
             // save merged content inside a new file
             if ($this->extConfig['css.']['merge.']['enable'] === '1' && $mergedContent !== '') {
                 if ($this->extConfig['css.']['uniqueCharset.']['enable'] === '1') {
                     $mergedContent = $this->uniqueCharset($mergedContent);
                 }
                 // Change from scriptmergerbless begin
                 $SplitCSS = new SplitCSS($this->extConfig);
                 $cssData = $SplitCSS->init($mergedContent);
                 foreach ($cssData as $mergedContent) {
                     // Change from scriptmergerbless end
                     if ($this->extConfig['css.']['uniqueCharset.']['enable'] === '1') {
                         $mergedContent = $this->uniqueCharset($mergedContent);
                     }
                     // create property array
                     $properties = array('content' => $mergedContent, 'basename' => 'head-' . md5($mergedContent) . '.merged');
                     // write merged file in any case
                     $newFile = $this->tempDirectories['merged'] . $properties['basename'] . '.css';
                     if (!file_exists($newFile)) {
                         t3lib_div::writeFile($newFile, $properties['content']);
                     }
                     // file should be compressed
                     if ($this->extConfig['css.']['compress.']['enable'] === '1' && function_exists('gzcompress')) {
                         $newFile = $this->compressCSSfile($properties);
                     }
                     // add new entry
                     $this->css[$relation][$media][$firstFreeIndex]['file'] = $newFile;
                     $this->css[$relation][$media][$firstFreeIndex]['content'] = $properties['content'];
                     $this->css[$relation][$media][$firstFreeIndex]['basename'] = $properties['basename'];
                     $firstFreeIndex++;
                     // Change from scriptmergerbless begin
                 }
                 // Change from scriptmergerbless end
             }
         }
     }
     // write the conditional comments and possibly merged css files back to the document
     $this->writeCSStoDocument();
 }
 /**
  * CLI engine
  *
  * @param	array		Command line arguments
  * @return	string
  */
 function cli_main($argv)
 {
     // Force user to admin state and set workspace to "Live":
     $GLOBALS['BE_USER']->user['admin'] = 1;
     $GLOBALS['BE_USER']->setWorkspace(0);
     // Print help
     $analysisType = (string) $this->cli_args['_DEFAULT'][1];
     if (!$analysisType) {
         $this->cli_validateArgs();
         $this->cli_help();
         exit;
     }
     // Analysis type:
     switch ((string) $analysisType) {
         case 'setBElock':
             if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                 $this->cli_echo("A lockfile already exists. Overwriting it... \n");
             }
             $lockFileContent = $this->cli_argValue('--redirect');
             t3lib_div::writeFile(PATH_typo3conf . 'LOCK_BACKEND', $lockFileContent);
             $this->cli_echo("Wrote lock-file to '" . PATH_typo3conf . "LOCK_BACKEND' with content '" . $lockFileContent . "'");
             break;
         case 'clearBElock':
             if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                 unlink(PATH_typo3conf . 'LOCK_BACKEND');
                 if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
                     $this->cli_echo("ERROR: Could not remove lock file '" . PATH_typo3conf . "LOCK_BACKEND'!!\n", 1);
                 } else {
                     $this->cli_echo("Removed lock file '" . PATH_typo3conf . "LOCK_BACKEND'\n");
                 }
             } else {
                 $this->cli_echo("No lock file '" . PATH_typo3conf . "LOCK_BACKEND' was found; hence no lock can be removed.'\n");
             }
             break;
         default:
             $this->cli_echo("Unknown toolkey, '" . $analysisType . "'");
             break;
     }
     $this->cli_echo(LF);
 }
 /**
  * Filling in the field array
  * $this->exclude_array is used to filter fields if needed.
  *
  * @param	string		Table name
  * @param	integer		Record ID
  * @param	array		Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
  * @param	array		$incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
  * @param	integer		The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
  * @param	string		$status = 'new' or 'update'
  * @param	integer		$tscPID: TSconfig PID
  * @return	array		Field Array
  */
 function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
 {
     global $TCA;
     // Initialize:
     t3lib_div::loadTCA($table);
     $originalLanguageRecord = NULL;
     $originalLanguage_diffStorage = NULL;
     $diffStorageFlag = FALSE;
     // Setting 'currentRecord' and 'checkValueRecord':
     if (strstr($id, 'NEW')) {
         $currentRecord = $checkValueRecord = $fieldArray;
         // must have the 'current' array - not the values after processing below...
         // IF $incomingFieldArray is an array, overlay it.
         // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
         if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
             $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
         }
     } else {
         $currentRecord = $checkValueRecord = $this->recordInfo($table, $id, '*');
         // We must use the current values as basis for this!
         t3lib_BEfunc::fixVersioningPid($table, $currentRecord);
         // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
         // Get original language record if available:
         if (is_array($currentRecord) && $TCA[$table]['ctrl']['transOrigDiffSourceField'] && $TCA[$table]['ctrl']['languageField'] && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0 && $TCA[$table]['ctrl']['transOrigPointerField'] && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0) {
             $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
             $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']], '*');
             t3lib_BEfunc::workspaceOL($lookUpTable, $originalLanguageRecord);
             $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
         }
     }
     $this->checkValue_currentRecord = $checkValueRecord;
     /*
     			   In the following all incoming value-fields are tested:
     			   - Are the user allowed to change the field?
     			   - Is the field uid/pid (which are already set)
     			   - perms-fields for pages-table, then do special things...
     			   - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
     
     			   If everything is OK, the field is entered into $fieldArray[]
     */
     foreach ($incomingFieldArray as $field => $fieldValue) {
         if (!in_array($table . '-' . $field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) {
             // The field must be editable.
             // Checking if a value for language can be changed:
             $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);
             if (!$languageDeny) {
                 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
                 if ($this->stripslashes_values) {
                     if (is_array($fieldValue)) {
                         t3lib_div::stripSlashesOnArray($fieldValue);
                     } else {
                         $fieldValue = stripslashes($fieldValue);
                     }
                 }
                 switch ($field) {
                     case 'uid':
                     case 'pid':
                         // Nothing happens, already set
                         break;
                     case 'perms_userid':
                     case 'perms_groupid':
                     case 'perms_user':
                     case 'perms_group':
                     case 'perms_everybody':
                         // Permissions can be edited by the owner or the administrator
                         if ($table == 'pages' && ($this->admin || $status == 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
                             $value = intval($fieldValue);
                             switch ($field) {
                                 case 'perms_userid':
                                     $fieldArray[$field] = $value;
                                     break;
                                 case 'perms_groupid':
                                     $fieldArray[$field] = $value;
                                     break;
                                 default:
                                     if ($value >= 0 && $value < pow(2, 5)) {
                                         $fieldArray[$field] = $value;
                                     }
                                     break;
                             }
                         }
                         break;
                     case 't3ver_oid':
                     case 't3ver_id':
                     case 't3ver_wsid':
                     case 't3ver_state':
                     case 't3ver_swapmode':
                     case 't3ver_count':
                     case 't3ver_stage':
                     case 't3ver_tstamp':
                         // t3ver_label is not here because it CAN be edited as a regular field!
                         break;
                     default:
                         if (isset($TCA[$table]['columns'][$field])) {
                             // Evaluating the value
                             $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
                             if (isset($res['value'])) {
                                 $fieldArray[$field] = $res['value'];
                             }
                             // Add the value of the original record to the diff-storage content:
                             if ($this->updateModeL10NdiffData && $TCA[$table]['ctrl']['transOrigDiffSourceField']) {
                                 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
                                 $diffStorageFlag = TRUE;
                             }
                             // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
                             // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied. That should be true for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
                             // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
                             // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
                             if ($this->autoVersioningUpdate === TRUE) {
                                 if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
                                     foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
                                         $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
                                     }
                                 }
                             }
                         } elseif ($TCA[$table]['ctrl']['origUid'] === $field) {
                             // Allow value for original UID to pass by...
                             $fieldArray[$field] = $fieldValue;
                         }
                         break;
                 }
             }
             // Checking language.
         }
         // Check exclude fields / disabled fields...
     }
     // Add diff-storage information:
     if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']])) {
         // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
         $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
     }
     // Checking for RTE-transformations of fields:
     $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table, $currentRecord);
     $theTypeString = t3lib_BEfunc::getTCAtypeValue($table, $currentRecord);
     if (is_array($types_fieldConfig)) {
         foreach ($types_fieldConfig as $vconf) {
             // Write file configuration:
             $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'], array_merge($currentRecord, $fieldArray));
             // inserted array_merge($currentRecord,$fieldArray) 170502
             // RTE transformations:
             if (!$this->dontProcessTransformations) {
                 if (isset($fieldArray[$vconf['field']])) {
                     // Look for transformation flag:
                     switch ((string) $incomingFieldArray['_TRANSFORM_' . $vconf['field']]) {
                         case 'RTE':
                             $RTEsetup = $this->BE_USER->getTSConfig('RTE', t3lib_BEfunc::getPagesTSconfig($tscPID));
                             $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
                             // Set alternative relative path for RTE images/links:
                             $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
                             // Get RTE object, draw form and set flag:
                             $RTEobj = t3lib_BEfunc::RTEgetObj();
                             if (is_object($RTEobj)) {
                                 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db', $fieldArray[$vconf['field']], $table, $vconf['field'], $currentRecord, $vconf['spec'], $thisConfig, $RTErelPath, $currentRecord['pid']);
                             } else {
                                 debug('NO RTE OBJECT FOUND!');
                             }
                             break;
                     }
                 }
             }
             // Write file configuration:
             if (is_array($eFile)) {
                 $mixedRec = array_merge($currentRecord, $fieldArray);
                 $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
                 $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
                 /* @var $parseHTML t3lib_parsehtml_proc */
                 $parseHTML->init('', '');
                 $eFileMarker = $eFile['markerField'] && trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
                 $insertContent = str_replace($eFileMarker, '', $mixedRec[$eFile['contentField']]);
                 // must replace the marker if present in content!
                 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, LF . $insertContent . LF, 1, 1);
                 t3lib_div::writeFile($eFile['editFile'], $SW_fileNewContent);
                 // Write status:
                 if (!strstr($id, 'NEW') && $eFile['statusField']) {
                     $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($id), array($eFile['statusField'] => $eFile['relEditFile'] . ' updated ' . date('d-m-Y H:i:s') . ', bytes ' . strlen($mixedRec[$eFile['contentField']])));
                 }
             } elseif ($eFile && is_string($eFile)) {
                 $this->log($table, $id, 2, 0, 1, "Write-file error: '%s'", 13, array($eFile), $realPid);
             }
         }
     }
     // Return fieldArray
     return $fieldArray;
 }
 /**
  * Writing/update the content of textfiles (action=9)
  *
  * @param	array		$cmds['data'] is the new content. $cmds['target'] is the target (file or dir)
  * @param	string		$id: ID of the item
  * @return	boolean		Returns true on success
  */
 function func_edit($cmds, $id)
 {
     if (!$this->isInit) {
         return FALSE;
     }
     $theTarget = tx_dam::file_absolutePath($cmds['target']);
     $content = $cmds['content'] ? $cmds['content'] : $cmds['data'];
     $extList = $GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'];
     $type = filetype($theTarget);
     if (!($type == 'file')) {
         // $type MUST BE file
         $this->writelog(9, 2, 123, 'Target "%s" was not a file!', array($theTarget), 'edit', $id);
         return;
     }
     $fileInfo = t3lib_div::split_fileref($theTarget);
     // Fetches info about path, name, extention of $theTarget
     if (!$this->checkPathAgainstMounts($fileInfo['path'])) {
         $this->writelog(9, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($fileInfo['path']), 'edit', $id);
         return;
     }
     if (!$this->actionPerms['editFile']) {
         $this->writelog(9, 1, 104, 'You are not allowed to edit files!', '', 'edit', $id);
         return;
     }
     if (!$this->checkIfAllowed($fileInfo['fileext'], $fileInfo['path'], $fileInfo['file'])) {
         $this->writelog(9, 1, 103, 'Fileextension "%s" was not allowed!', array($fileInfo['fileext']), 'edit', $id);
         return;
     }
     if (!t3lib_div::inList($extList, $fileInfo['fileext'])) {
         $this->writelog(9, 1, 102, 'Fileextension "%s" is not a textfile format! (%s)', array($fileInfo['fileext'], $extList), 'edit', $id);
         return;
     }
     if (!t3lib_div::writeFile($theTarget, $content)) {
         $this->writelog(9, 1, 100, 'File "%s" was not saved! Write-permission problem in "%s"?', array($theTarget, $fileInfo['path']), 'edit', $id);
         return;
     }
     clearstatcache();
     $this->writelog(9, 0, 1, 'File saved to "%s", bytes: %s, MD5: %s ', array($fileInfo['file'], @filesize($theTarget), md5($content)), 'edit', $id);
     return true;
 }
示例#21
0
        // If the page is not rendered allready, which will happen if a hidden page is 'published'
        // Images file
        //			$temp_publish_row = $TSFE->getSearchCache();
        //			$temp_publish_imagesOnPage= unserialize($temp_publish_row['tempFile_data']);
        //			$temp_publish_imagesTotal = array_merge($temp_publish_imagesTotal, $temp_publish_imagesOnPage);
        // Store the data for this page:
        $temp_publish_array[$temp_fileName] = array($temp_publish_id, $temp_publish_imagesOnPage, $TSFE->content);
    }
    $TT->pull();
}
//debug($temp_publish_imagesTotal);
//debug(array_unique($temp_publish_imagesTotal));
// ***************************
// Publishing, writing files
// ***************************
$publishDir = $TYPO3_CONF_VARS['FE']['publish_dir'];
if ($publishDir && @is_dir($publishDir)) {
    $publishDir = rtrim($publishDir, '/') . '/';
    debug('Publishing in: ' . $publishDir, 'Publish');
    foreach ($temp_publish_array as $key => $val) {
        $file = $publishDir . $key;
        t3lib_div::writeFile($file, $val[2]);
        debug('Writing: ' . $file, 'Publish');
    }
    //	debug($temp_publish_array);
} else {
    debug('No publish_dir specified...');
}
$TT->pull();
// Restoring the TSFE object
$TSFE = $temp_publish_TSFE;
 /**
  * Processing of the submitted form; Will create and write the XLIFF file and tell the new file name.
  *
  * @param string $xmlFile Absolute path to the locallang.xml file to convert
  * @param string $newFilename The new file name to write to (absolute path, .xlf ending)
  * @param string $langKey The language key
  * @return string HTML text string message
  */
 protected function renderSaveDone($xmlFile, $newFileName, $langKey)
 {
     // Initialize variables:
     $xml = array();
     $LOCAL_LANG = $this->getLLarray($xmlFile);
     $xml[] = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
     $xml[] = '<xliff version="1.0">';
     $xml[] = '	<file source-language="en"' . ($langKey !== 'default' ? ' target-language="' . $langKey . '"' : '') . ' datatype="plaintext" original="messages" date="' . gmdate('Y-m-d\\TH:i:s\\Z') . '"' . ' product-name="' . $this->extension . '">';
     $xml[] = '		<header/>';
     $xml[] = '		<body>';
     $version = Tx_Extdeveval_Compatibility::convertVersionNumberToInteger(TYPO3_version);
     foreach ($LOCAL_LANG[$langKey] as $key => $data) {
         $source = $version < 4006000 ? $LOCAL_LANG['default'][$key] : $data[0]['source'];
         $target = $version < 4006000 ? $data : $data[0]['target'];
         if ($langKey === 'default') {
             $xml[] = '			<trans-unit id="' . $key . '" xml:space="preserve">';
             $xml[] = '				<source>' . htmlspecialchars($source) . '</source>';
             $xml[] = '			</trans-unit>';
         } else {
             $xml[] = '			<trans-unit id="' . $key . '" xml:space="preserve" approved="yes">';
             $xml[] = '				<source>' . htmlspecialchars($source) . '</source>';
             $xml[] = '				<target>' . htmlspecialchars($target) . '</target>';
             $xml[] = '			</trans-unit>';
         }
     }
     $xml[] = '		</body>';
     $xml[] = '	</file>';
     $xml[] = '</xliff>';
     if (!file_exists($newFileName)) {
         # debug(array($XML));
         t3lib_div::writeFile($newFileName, implode(LF, $xml));
         return 'File written to disk: ' . $newFileName;
     }
 }
	/**
	 *
	 * @param	array	$conf
	 */
	protected function getDsRecords($conf) {
		$updateMessage = '';
		$writeDsIds = array();
		$writeIds = t3lib_div::_GP('staticDSwizard');
		$options = t3lib_div::_GP('staticDSwizardoptions');
		$checkAll = t3lib_div::_GP('sdw-checkall');

		if (count($writeIds)) {
			$writeDsIds = array_keys($writeIds);
		}
		$rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
			'*',
			'tx_templavoila_datastructure',
			'deleted=0',
			'',
			'scope, title'
		);
		$out = '<table id="staticDSwizard_getdsrecords"><thead>
			<tr class="bgColor5">
				<td style="vertical-align:middle;">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.uid') . '</td>
				<td style="vertical-align:middle;">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.pid') . '</td>
				<td style="vertical-align:middle;">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.title') . '</td>
				<td style="vertical-align:middle;">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.scope') . '</td>
				<td style="vertical-align:middle;">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.usage') . '</td>
			<td>
				<label for="sdw-checkall">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.selectall') . '</label>
				<input type="checkbox" class="checkbox" id="sdw-checkall" name="sdw-checkall" onclick="$$(\'.staticDScheck\').each(function(e){e.checked=$(\'sdw-checkall\').checked;});" value="1" ' . ($checkAll
				? 'checked="checked"' : '') . ' /></td>
		</tr></thead><tbody>';
		foreach ($rows as $row) {
			$dirPath = t3lib_div::getFileAbsFileName($row['scope'] == 2 ? $conf['path_fce'] : $conf['path_page']);
			$dirPath = $dirPath . (substr($dirPath, -1) == '/' ? '' : '/');
			$title = preg_replace('|[/,\."\']+|', '_', $row['title']);
			$path = $dirPath . $title . ' (' . ($row['scope'] == 1 ? 'page' : 'fce') . ').xml';
			$outPath = substr($path, strlen(PATH_site));

			$usage = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
				'count(*)',
				'tx_templavoila_tmplobj',
				'datastructure=' . (int)$row['uid'] . t3lib_BEfunc::BEenableFields('tx_templavoila_tmplobj')
			);
			if (count($writeDsIds) && in_array($row['uid'], $writeDsIds)) {
				t3lib_div::writeFile($path, $row['dataprot']);
				if ($row['previewicon']) {
					copy(t3lib_div::getFileAbsFileName('uploads/tx_templavoila/' . $row['previewicon']), $dirPath . $title . ' (' . ($row['scope'] == 1
							? 'page' : 'fce') . ').gif');
				}
				if ($options['updateRecords']) {
					// remove DS records
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
						'tx_templavoila_datastructure',
						'uid="' . $row['uid'] . '"',
						array('deleted' => 1)
					);
					// update TO records
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
						'tx_templavoila_tmplobj',
						'datastructure="' . $row['uid'] . '"',
						array('datastructure' => $outPath)
					);
					// update page records
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
						'pages',
						'tx_templavoila_ds="' . $row['uid'] . '"',
						array('tx_templavoila_ds' => $outPath)
					);
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
						'pages',
						'tx_templavoila_next_ds="' . $row['uid'] . '"',
						array('tx_templavoila_next_ds' => $outPath)
					);
					// update tt_content records
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
						'tt_content',
						'tx_templavoila_ds="' . $row['uid'] . '"',
						array('tx_templavoila_ds' => $outPath)
					);
					// delete DS records
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_templavoila_datastructure', 'uid=' . $row['uid'], array('deleted' => 1));
					$updateMessage = $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.updated');
					$this->step = 3;
				}


			}
			$out .= '<tr class="bgColor' . ($row['scope'] == 1 ? 3 : 6) . '">
			<td style="text-align: center;padding: 0,3px;">' . $row['uid'] . '</td>
			<td style="text-align: center;padding: 0,3px;">' . $row['pid'] . '</td>
			<td style="padding: 0,3px;">' . htmlspecialchars($row['title']) . '</td>
			<td style="padding: 0,3px;">' . ($row['scope'] == 1 ? 'Page' : 'FCE') . '</td>
			<td style="text-align: center;padding: 0,3px;">' . $usage[0]['count(*)'] . '</td>';
			if (count($writeDsIds) && in_array($row['uid'], $writeDsIds)) {
				$out .= '<td class="nobr" style="text-align: right;padding: 0,3px;">written to "' . $outPath . '"</td>';
			} else {
				$out .= '<td class="nobr" style="text-align: right;padding: 0,3px;"><input type="checkbox" class="checkbox staticDScheck" name="staticDSwizard[' . $row['uid'] . ']" value="1" /></td>';
			}
			$out .= '</tr>';
		}
		$out .= '</tbody></table>';

		if ($conf['enable']) {
			if ($updateMessage) {
				$out .= '<p>' . $updateMessage . '</p><p><strong>' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.clearcache') . '</strong></p>';
			} else {
				$out .= '<h4>' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.description2.1') . '</h4>';
				$out .= '<p>
				<input type="checkbox" class="checkbox" name="staticDSwizardoptions[updateRecords]" id="sdw-updateRecords" value="1" />
				<label for="sdw-updateRecords">' . $GLOBALS['LANG']->sL('LLL:EXT:templavoila/res1/language/template_conf.xml:staticDS.wizard.updaterecords') . '</label><br />
				</p>';
			}
		}
		return $out;
	}
示例#24
0
    /**
     * [Describe function...]
     *
     * @return	[type]		...
     */
    function main()
    {
        $arrayBrowser = t3lib_div::makeInstance('t3lib_arrayBrowser');
        $this->content = $this->doc->header($GLOBALS['LANG']->getLL('configuration', true));
        $this->content .= $this->doc->spacer(5);
        $this->content .= '<div id="lowlevel-config">
						<label for="search_field">' . $GLOBALS['LANG']->getLL('enterSearchPhrase', true) . '</label>
						<input type="text" id="search_field" name="search_field" value="' . htmlspecialchars($search_field) . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(20) . ' />
						<input type="submit" name="search" id="search" value="' . $GLOBALS['LANG']->getLL('search', true) . '" />';
        $this->content .= t3lib_BEfunc::getFuncCheck(0, 'SET[regexsearch]', $this->MOD_SETTINGS['regexsearch'], '', '', 'id="checkRegexsearch"') . '<label for="checkRegexsearch">' . $GLOBALS['LANG']->getLL('useRegExp', true) . '</label>';
        $this->content .= t3lib_BEfunc::getFuncCheck(0, 'SET[fixedLgd]', $this->MOD_SETTINGS['fixedLgd'], '', '', 'id="checkFixedLgd"') . '<label for="checkFixedLgd">' . $GLOBALS['LANG']->getLL('cropLines', true) . '</label>
						</div>';
        $this->content .= $this->doc->spacer(5);
        switch ($this->MOD_SETTINGS['function']) {
            case 0:
                $theVar = $GLOBALS['TYPO3_CONF_VARS'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TYPO3_CONF_VARS';
                break;
            case 1:
                foreach ($GLOBALS['TCA'] as $table => $config) {
                    t3lib_div::loadTCA($table);
                }
                $theVar = $GLOBALS['TCA'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TCA';
                break;
            case 2:
                $theVar = $GLOBALS['TCA_DESCR'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TCA_DESCR';
                break;
            case 3:
                $theVar = $GLOBALS['TYPO3_LOADED_EXT'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TYPO3_LOADED_EXT';
                break;
            case 4:
                $theVar = $GLOBALS['T3_SERVICES'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$T3_SERVICES';
                break;
            case 5:
                $theVar = $GLOBALS['TBE_MODULES'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TBE_MODULES';
                break;
            case 6:
                $theVar = $GLOBALS['TBE_MODULES_EXT'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TBE_MODULES_EXT';
                break;
            case 7:
                $theVar = $GLOBALS['TBE_STYLES'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TBE_STYLES';
                break;
            case 8:
                $theVar = $GLOBALS['BE_USER']->uc;
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$BE_USER->uc';
                break;
            case 9:
                $theVar = $GLOBALS['TYPO3_USER_SETTINGS'];
                t3lib_div::naturalKeySortRecursive($theVar);
                $arrayBrowser->varName = '$TYPO3_USER_SETTINGS';
                break;
            default:
                $theVar = array();
                break;
        }
        // Update node:
        $update = 0;
        $node = t3lib_div::_GET('node');
        if (is_array($node)) {
            // If any plus-signs were clicked, it's registred.
            $this->MOD_SETTINGS['node_' . $this->MOD_SETTINGS['function']] = $arrayBrowser->depthKeys($node, $this->MOD_SETTINGS['node_' . $this->MOD_SETTINGS['function']]);
            $update = 1;
        }
        if ($update) {
            $GLOBALS['BE_USER']->pushModuleData($this->MCONF['name'], $this->MOD_SETTINGS);
        }
        $arrayBrowser->depthKeys = $this->MOD_SETTINGS['node_' . $this->MOD_SETTINGS['function']];
        $arrayBrowser->regexMode = $this->MOD_SETTINGS['regexsearch'];
        $arrayBrowser->fixedLgd = $this->MOD_SETTINGS['fixedLgd'];
        $arrayBrowser->searchKeysToo = TRUE;
        $search_field = t3lib_div::_GP('search_field');
        if (t3lib_div::_POST('search') && trim($search_field)) {
            // If any POST-vars are send, update the condition array
            $arrayBrowser->depthKeys = $arrayBrowser->getSearchKeys($theVar, '', $search_field, array());
        }
        $tree = $arrayBrowser->tree($theVar, '', '');
        $label = $this->MOD_MENU['function'][$this->MOD_SETTINGS['function']];
        $this->content .= $this->doc->sectionEnd();
        // Variable name:
        if (t3lib_div::_GP('varname')) {
            $line = t3lib_div::_GP('_') ? t3lib_div::_GP('_') : t3lib_div::_GP('varname');
            if (t3lib_div::_GP('writetoexttables')) {
                // Write the line to extTables.php
                // change value to $GLOBALS
                $length = strpos($line, '[');
                $var = substr($line, 0, $length);
                $changedLine = '$GLOBALS[\'' . substr($line, 1, $length - 1) . '\']' . substr($line, $length);
                // insert line  in extTables.php
                $extTables = t3lib_div::getURL(PATH_typo3conf . TYPO3_extTableDef_script);
                $extTables = '<?php' . preg_replace('/<\\?php|\\?>/is', '', $extTables) . $changedLine . LF . '?>';
                $success = t3lib_div::writeFile(PATH_typo3conf . TYPO3_extTableDef_script, $extTables);
                if ($success) {
                    // show flash message
                    $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', '', sprintf($GLOBALS['LANG']->getLL('writeMessage', TRUE), TYPO3_extTableDef_script, '<br />', '<strong>' . $changedLine . '</strong>'), t3lib_FlashMessage::OK);
                } else {
                    // Error: show flash message
                    $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', '', sprintf($GLOBALS['LANG']->getLL('writeMessageFailed', TRUE), TYPO3_extTableDef_script), t3lib_FlashMessage::ERROR);
                }
                $this->content .= $flashMessage->render();
            }
            $this->content .= '<div id="lowlevel-config-var">
				<strong>' . $GLOBALS['LANG']->getLL('variable', TRUE) . '</strong><br />
				<input type="text" name="_" value="' . trim(htmlspecialchars($line)) . '" size="120" /><br/>';
            if (TYPO3_extTableDef_script !== '' && ($this->MOD_SETTINGS['function'] === '1' || $this->MOD_SETTINGS['function'] === '4')) {
                // write only for $TCA and TBE_STYLES if  TYPO3_extTableDef_script is defined
                $this->content .= '<br /><input type="submit" name="writetoexttables" value="' . $GLOBALS['LANG']->getLL('writeValue', TRUE) . '" /></div>';
            } else {
                $this->content .= $GLOBALS['LANG']->getLL('copyPaste', TRUE) . LF . '</div>';
            }
        }
        $this->content .= '<br /><table border="0" cellpadding="0" cellspacing="0" class="t3-tree t3-tree-config">';
        $this->content .= '<tr>
					<th class="t3-row-header t3-tree-config-header">' . $label . '</th>
				</tr>
				<tr>
					<td>' . $tree . '</td>
				</tr>
			</table>
		';
        // Setting up the buttons and markers for docheader
        $docHeaderButtons = $this->getButtons();
        $markers = array('CSH' => $docHeaderButtons['csh'], 'FUNC_MENU' => $this->getFuncMenu(), 'CONTENT' => $this->content);
        // Build the <body> for the module
        $this->content = $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
        // Renders the module page
        $this->content = $this->doc->render('Configuration', $this->content);
    }
示例#25
0
    /**
     * Import part of module
     *
     * @param	array		Content of POST VAR tx_impexp[]..
     * @return	void		Setting content in $this->content
     */
    function importData($inData)
    {
        global $TCA, $LANG, $BE_USER;
        $access = is_array($this->pageinfo) ? 1 : 0;
        if ($this->id && $access || $BE_USER->user['admin'] && !$this->id) {
            if ($BE_USER->user['admin'] && !$this->id) {
                $this->pageinfo = array('title' => '[root-level]', 'uid' => 0, 'pid' => 0);
            }
            if ($inData['new_import']) {
                unset($inData['import_mode']);
            }
            $import = t3lib_div::makeInstance('tx_impexp');
            $import->init(0, 'import');
            $import->update = $inData['do_update'];
            $import->import_mode = $inData['import_mode'];
            $import->enableLogging = $inData['enableLogging'];
            $import->global_ignore_pid = $inData['global_ignore_pid'];
            $import->force_all_UIDS = $inData['force_all_UIDS'];
            $import->showDiff = !$inData['notShowDiff'];
            $import->allowPHPScripts = $inData['allowPHPScripts'];
            $import->softrefInputValues = $inData['softrefInputValues'];
            // OUTPUT creation:
            $menuItems = array();
            // Make input selector:
            $path = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'];
            // must have trailing slash.
            $filesInDir = t3lib_div::getFilesInDir(PATH_site . $path, 't3d,xml', 1, 1);
            $userPath = $this->userSaveFolder();
            //Files from User-Dir
            $filesInUserDir = t3lib_div::getFilesInDir($userPath, 't3d,xml', 1, 1);
            $filesInDir = array_merge($filesInUserDir, $filesInDir);
            if (is_dir(PATH_site . $path . 'export/')) {
                $filesInDir = array_merge($filesInDir, t3lib_div::getFilesInDir(PATH_site . $path . 'export/', 't3d,xml', 1, 1));
            }
            $tempFolder = $this->userTempFolder();
            if ($tempFolder) {
                $temp_filesInDir = t3lib_div::getFilesInDir($tempFolder, 't3d,xml', 1, 1);
                $filesInDir = array_merge($filesInDir, $temp_filesInDir);
            }
            // Configuration
            $row = array();
            $opt = array('');
            foreach ($filesInDir as $file) {
                $opt[$file] = substr($file, strlen(PATH_site));
            }
            $row[] = '<tr class="bgColor5">
					<td colspan="2"><strong>' . $LANG->getLL('importdata_selectFileToImport', 1) . '</strong></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_file', 1) . '</strong>' . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'importFile', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>' . $this->renderSelectBox('tx_impexp[file]', $inData['file'], $opt) . '<br />' . sprintf($LANG->getLL('importdata_fromPathS', 1), $path) . (!$import->compress ? '<br /><span class="typo3-red">' . $LANG->getLL('importdata_noteNoDecompressorAvailable', 1) . '</span>' : '') . '</td>
				</tr>';
            $row[] = '<tr class="bgColor5">
					<td colspan="2"><strong>' . $LANG->getLL('importdata_importOptions', 1) . '</strong></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_update', 1) . '</strong>' . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'update', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[do_update]" id="checkDo_update" value="1"' . ($inData['do_update'] ? ' checked="checked"' : '') . ' />
					<label for="checkDo_update">' . $LANG->getLL('importdata_updateRecords', 1) . '</label><br/>
				<em>(' . $LANG->getLL('importdata_thisOptionRequiresThat', 1) . ')</em>' . ($inData['do_update'] ? '	<hr/>
					<input type="checkbox" name="tx_impexp[global_ignore_pid]" id="checkGlobal_ignore_pid" value="1"' . ($inData['global_ignore_pid'] ? ' checked="checked"' : '') . ' />
					<label for="checkGlobal_ignore_pid">' . $LANG->getLL('importdata_ignorePidDifferencesGlobally', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_ifYouSetThis', 1) . ')</em>
					' : '') . '</td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_options', 1) . '</strong>' . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'options', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[notShowDiff]" id="checkNotShowDiff" value="1"' . ($inData['notShowDiff'] ? ' checked="checked"' : '') . ' />
					<label for="checkNotShowDiff">' . $LANG->getLL('importdata_doNotShowDifferences', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_greenValuesAreFrom', 1) . ')</em>
					<br/><br/>

					' . ($GLOBALS['BE_USER']->isAdmin() ? '
					<input type="checkbox" name="tx_impexp[allowPHPScripts]" id="checkAllowPHPScripts" value="1"' . ($inData['allowPHPScripts'] ? ' checked="checked"' : '') . ' />
					<label for="checkAllowPHPScripts">' . $LANG->getLL('importdata_allowToWriteBanned', 1) . '</label><br/>' : '') . (!$inData['do_update'] && $GLOBALS['BE_USER']->isAdmin() ? '
					<br/>
					<input type="checkbox" name="tx_impexp[force_all_UIDS]" id="checkForce_all_UIDS" value="1"' . ($inData['force_all_UIDS'] ? ' checked="checked"' : '') . ' />
					<label for="checkForce_all_UIDS"><span class="typo3-red">' . $LANG->getLL('importdata_force_all_UIDS', 1) . '</span></label><br/>
					<em>(' . $LANG->getLL('importdata_force_all_UIDS_descr', 1) . ')</em>' : '') . '
				</td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_action', 1) . '</strong>' . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'action', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>' . (!$inData['import_file'] ? '<input type="submit" value="' . $LANG->getLL('importdata_preview', 1) . '" />' . ($inData['file'] ? ' - <input type="submit" value="' . ($inData['do_update'] ? $LANG->getLL('importdata_update_299e', 1) : $LANG->getLL('importdata_import', 1)) . '" name="tx_impexp[import_file]" onclick="return confirm(\'' . $LANG->getLL('importdata_areYouSure', 1) . '\');" />' : '') : '<input type="submit" name="tx_impexp[new_import]" value="' . $LANG->getLL('importdata_newImport', 1) . '" />') . '
					<input type="hidden" name="tx_impexp[action]" value="import" /></td>
				</tr>';
            $row[] = '<tr class="bgColor4">
				<td><strong>' . $LANG->getLL('importdata_enableLogging', 1) . '</strong>' . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'enableLogging', $GLOBALS['BACK_PATH'], '') . '</td>
				<td>
					<input type="checkbox" name="tx_impexp[enableLogging]" id="checkEnableLogging" value="1"' . ($inData['enableLogging'] ? ' checked="checked"' : '') . ' />
					<label for="checkEnableLogging">' . $LANG->getLL('importdata_writeIndividualDbActions', 1) . '</label><br/>
					<em>(' . $LANG->getLL('importdata_thisIsDisabledBy', 1) . ')</em>
				</td>
				</tr>';
            $menuItems[] = array('label' => $LANG->getLL('importdata_import', 1), 'content' => '
					<table border="0" cellpadding="1" cellspacing="1">
						' . implode('
						', $row) . '
					</table>
				');
            // Upload file:
            $tempFolder = $this->userTempFolder();
            if ($tempFolder) {
                $row = array();
                $row[] = '<tr class="bgColor5">
						<td colspan="2"><strong>' . $LANG->getLL('importdata_uploadFileFromLocal', 1) . '</strong></td>
					</tr>';
                $row[] = '<tr class="bgColor4">
						<td>' . $LANG->getLL('importdata_browse', 1) . t3lib_BEfunc::cshItem('xMOD_tx_impexp', 'upload', $GLOBALS['BACK_PATH'], '') . '</td>
						<td>

								<input type="file" name="upload_1"' . $this->doc->formWidth(35) . ' size="40" />
								<input type="hidden" name="file[upload][1][target]" value="' . htmlspecialchars($tempFolder) . '" />
								<input type="hidden" name="file[upload][1][data]" value="1" /><br />

								<input type="submit" name="_upload" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:file_upload.php.submit', 1) . '" />
								<input type="checkbox" name="overwriteExistingFiles" id="checkOverwriteExistingFiles" value="1" checked="checked" /> <label for="checkOverwriteExistingFiles">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.php:overwriteExistingFiles', 1) . '</label>
						</td>
					</tr>';
                if (t3lib_div::_POST('_upload')) {
                    $row[] = '<tr class="bgColor4">
							<td>' . $LANG->getLL('importdata_uploadStatus', 1) . '</td>
							<td>' . ($this->fileProcessor->internalUploadMap[1] ? $LANG->getLL('importdata_success', 1) . ' ' . substr($this->fileProcessor->internalUploadMap[1], strlen(PATH_site)) : '<span class="typo3-red">' . $LANG->getLL('importdata_failureNoFileUploaded', 1) . '</span>') . '</td>
						</tr>';
                }
                $menuItems[] = array('label' => $LANG->getLL('importdata_upload'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $row) . '
						</table>
					');
            }
            // Perform import or preview depending:
            $overviewContent = '';
            $extensionInstallationMessage = '';
            $emURL = '';
            $inFile = t3lib_div::getFileAbsFileName($inData['file']);
            if ($inFile && @is_file($inFile)) {
                $trow = array();
                if ($import->loadFile($inFile, 1)) {
                    // Check extension dependencies:
                    $extKeysToInstall = array();
                    if (is_array($import->dat['header']['extensionDependencies'])) {
                        foreach ($import->dat['header']['extensionDependencies'] as $extKey) {
                            if (!t3lib_extMgm::isLoaded($extKey)) {
                                $extKeysToInstall[] = $extKey;
                            }
                        }
                    }
                    if (count($extKeysToInstall)) {
                        $passParams = t3lib_div::_POST('tx_impexp');
                        unset($passParams['import_mode']);
                        unset($passParams['import_file']);
                        $thisScriptUrl = t3lib_div::getIndpEnv('REQUEST_URI') . '?M=xMOD_tximpexp&id=' . $this->id . t3lib_div::implodeArrayForUrl('tx_impexp', $passParams);
                        $emURL = $this->doc->backPath . 'mod/tools/em/index.php?CMD[requestInstallExtensions]=' . implode(',', $extKeysToInstall) . '&returnUrl=' . rawurlencode($thisScriptUrl);
                        $extensionInstallationMessage = 'Before you can install this T3D file you need to install the extensions "' . implode('", "', $extKeysToInstall) . '". Clicking Import will first take you to the Extension Manager so these dependencies can be resolved.';
                    }
                    if ($inData['import_file']) {
                        if (!count($extKeysToInstall)) {
                            $import->importData($this->id);
                            t3lib_BEfunc::setUpdateSignal('updatePageTree');
                        } else {
                            t3lib_utility_Http::redirect($emURL);
                        }
                    }
                    $import->display_import_pid_record = $this->pageinfo;
                    $overviewContent = $import->displayContentOverview();
                }
                // Meta data output:
                $trow[] = '<tr class="bgColor5">
						<td colspan="2"><strong>' . $LANG->getLL('importdata_metaData', 1) . '</strong></td>
					</tr>';
                $opt = array('');
                foreach ($filesInDir as $file) {
                    $opt[$file] = substr($file, strlen(PATH_site));
                }
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_title', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['title'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_description', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['description'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_notes', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['notes'])) . '</td>
					</tr>';
                $trow[] = '<tr class="bgColor4">
					<td><strong>' . $LANG->getLL('importdata_packager', 1) . '</strong></td>
					<td width="95%">' . nl2br(htmlspecialchars($import->dat['header']['meta']['packager_name'] . ' (' . $import->dat['header']['meta']['packager_username'] . ')')) . '<br/>
						' . $LANG->getLL('importdata_email', 1) . ' ' . $import->dat['header']['meta']['packager_email'] . '</td>
					</tr>';
                // Thumbnail icon:
                if (is_array($import->dat['header']['thumbnail'])) {
                    $pI = pathinfo($import->dat['header']['thumbnail']['filename']);
                    if (t3lib_div::inList('gif,jpg,png,jpeg', strtolower($pI['extension']))) {
                        // Construct filename and write it:
                        $fileName = PATH_site . 'typo3temp/importthumb.' . $pI['extension'];
                        t3lib_div::writeFile($fileName, $import->dat['header']['thumbnail']['content']);
                        // Check that the image really is an image and not a malicious PHP script...
                        if (getimagesize($fileName)) {
                            // Create icon tag:
                            $iconTag = '<img src="' . $this->doc->backPath . '../' . substr($fileName, strlen(PATH_site)) . '" ' . $import->dat['header']['thumbnail']['imgInfo'][3] . ' vspace="5" style="border: solid black 1px;" alt="" />';
                            $trow[] = '<tr class="bgColor4">
								<td><strong>' . $LANG->getLL('importdata_icon', 1) . '</strong></td>
								<td>' . $iconTag . '</td>
								</tr>';
                        } else {
                            t3lib_div::unlink_tempfile($fileName);
                        }
                    }
                }
                $menuItems[] = array('label' => $LANG->getLL('importdata_metaData_1387'), 'content' => '
						<table border="0" cellpadding="1" cellspacing="1">
							' . implode('
							', $trow) . '
						</table>
					');
            }
            // Print errors that might be:
            $errors = $import->printErrorLog();
            $menuItems[] = array('label' => $LANG->getLL('importdata_messages'), 'content' => $errors, 'stateIcon' => $errors ? 2 : 0);
            // Output tabs:
            $content = $this->doc->getDynTabMenu($menuItems, 'tx_impexp_import', -1);
            if ($extensionInstallationMessage) {
                $content = '<div style="border: 1px black solid; margin: 10px 10px 10px 10px; padding: 10px 10px 10px 10px;">' . $this->doc->icons(1) . htmlspecialchars($extensionInstallationMessage) . '</div>' . $content;
            }
            $this->content .= $this->doc->section('', $content, 0, 1);
            // Print overview:
            if ($overviewContent) {
                $this->content .= $this->doc->section($inData['import_file'] ? $LANG->getLL('importdata_structureHasBeenImported', 1) : $LANG->getLL('filterpage_structureToBeImported', 1), $overviewContent, 0, 1);
            }
        }
    }
 /**
  * action updatetyposcript
  *
  * @return void
  */
 public function updatetyposcriptAction()
 {
     $args = $this->request->getArguments();
     if (isset($args['config'])) {
         $tsfile = PATH_site . "typo3conf/ext/countrymanager/Configuration/TypoScript/AutomaticLanguageConfiguration/setup.txt";
         if (t3lib_div::writeFile($tsfile, $args['config'])) {
             $this->flashMessages->add('TypoScript successfully writen written. Make sure to add the static TS template "Typo3 Country Manager – Automatic Language Configuration" to your master-template.');
         } else {
             $this->flashMessages->add('TypoScript could not be written.');
         }
     }
     $countries = $this->countryLanguageRepository->findAll();
     $this->view->assign('content_fallback', $this->settings['sys_language_mode'] == 'content_fallback' ? true : false);
     if (isset($this->settings['defaultCountryUid'])) {
         $this->view->assign('defaultCountry', $this->countryLanguageRepository->findByUid(intval($this->settings['defaultCountryUid'])));
     }
     $this->view->assign('countries', $countries);
     //$this->view->assign('debug', $countries);
 }
示例#27
0
 /**
  * Index External URLs HTML content
  *
  * @param	string		URL, eg. "http://typo3.org/"
  * @return	void
  * @see indexRegularDocument()
  */
 function indexExternalUrl($externalUrl)
 {
     // Parse External URL:
     $qParts = parse_url($externalUrl);
     $fI = pathinfo($qParts['path']);
     $ext = strtolower($fI['extension']);
     // Get headers:
     $urlHeaders = $this->getUrlHeaders($externalUrl);
     if (stristr($urlHeaders['Content-Type'], 'text/html')) {
         $content = $this->indexExternalUrl_content = t3lib_div::getUrl($externalUrl);
         if (strlen($content)) {
             // Create temporary file:
             $tmpFile = t3lib_div::tempnam('EXTERNAL_URL');
             if ($tmpFile) {
                 t3lib_div::writeFile($tmpFile, $content);
                 // Index that file:
                 $this->indexRegularDocument($externalUrl, TRUE, $tmpFile, 'html');
                 // Using "TRUE" for second parameter to force indexing of external URLs (mtime doesn't make sense, does it?)
                 unlink($tmpFile);
             }
         }
     }
 }
示例#28
0
 /**
  * Writes a file from the import memory having $fileID to file name $fileName which must be an absolute path inside PATH_site
  *
  * @param	string		Absolute filename inside PATH_site to write to
  * @param	string		File ID from import memory
  * @param	boolean		Bypasses the checking against filemounts - only for RTE files!
  * @return	boolean		Returns true if it went well. Notice that the content of the file is read again, and md5 from import memory is validated.
  */
 function writeFileVerify($fileName, $fileID, $bypassMountCheck = FALSE)
 {
     $fileProcObj = $this->getFileProcObj();
     if ($fileProcObj->actionPerms['newFile']) {
         if ($fileProcObj->checkPathAgainstMounts($fileName) || $bypassMountCheck) {
             // Just for security, check again. Should actually not be necessary.
             $fI = t3lib_div::split_fileref($fileName);
             if ($fileProcObj->checkIfAllowed($fI['fileext'], $fI['path'], $fI['file']) || $this->allowPHPScripts && $GLOBALS['BE_USER']->isAdmin()) {
                 if (t3lib_div::getFileAbsFileName($fileName)) {
                     if ($this->dat['files'][$fileID]) {
                         t3lib_div::writeFile($fileName, $this->dat['files'][$fileID]['content']);
                         $this->fileIDMap[$fileID] = $fileName;
                         if (md5(t3lib_div::getUrl($fileName)) == $this->dat['files'][$fileID]['content_md5']) {
                             return TRUE;
                         } else {
                             $this->error('ERROR: File content "' . $fileName . '" was corrupted');
                         }
                     } else {
                         $this->error('ERROR: File ID "' . $fileID . '" could not be found');
                     }
                 } else {
                     $this->error('ERROR: Filename "' . $fileName . '" was not a valid relative file path!');
                 }
             } else {
                 $this->error('ERROR: Filename "' . $fileName . '" failed against extension check or deny-pattern!');
             }
         } else {
             $this->error('ERROR: Filename "' . $fileName . '" was not allowed in destination path!');
         }
     } else {
         $this->error('ERROR: You did not have sufficient permissions to write the file "' . $fileName . '"');
     }
 }
 /**
  * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
  *
  * @param	string		Query to execute
  * @return	pointer		Result pointer
  */
 function admin_query($query)
 {
     if (!$this->DBdir) {
         $this->errorStatus = 'XMLdatabase not connected';
         return FALSE;
     }
     $parsedQuery = $this->parseSQL($query);
     $table = $parsedQuery['TABLE'];
     if (is_array($parsedQuery)) {
         // Process query based on type:
         switch ($parsedQuery['type']) {
             case 'CREATETABLE':
                 if (!is_array($this->DBstructure['tables'][$table])) {
                     $newTableFile = 'TABLE_' . $table . '.xml';
                     if (!@is_file($this->DBdir . $newTableFile)) {
                         // Write table file:
                         t3lib_div::writeFile($this->DBdir . $newTableFile, '');
                         // Create file
                         if (@is_file($this->DBdir . $newTableFile)) {
                             // Set and write structure
                             if (!is_array($this->DBstructure['tables'])) {
                                 $this->DBstructure['tables'] = array();
                             }
                             $this->DBstructure['tables'][(string) $table] = $parsedQuery;
                             // I have some STRANGE behaviours with this variable - had to do this trick to make it work!
                             $this->xmlDB_writeStructure();
                             return TRUE;
                         } else {
                             $this->errorStatus = 'Table file "' . $this->DBdir . $newTableFile . '" could not be created! Cannot create table!';
                         }
                     } else {
                         $this->errorStatus = 'Table file "' . $this->DBdir . $newTableFile . '" already exists! Cannot create table!';
                     }
                 } else {
                     $this->errorStatus = 'Table "' . $table . '" already exists!';
                 }
                 break;
             case 'ALTERTABLE':
                 if (is_array($this->DBstructure['tables'][$table])) {
                     switch ($parsedQuery['action']) {
                         case 'ADD':
                             if (!is_array($this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['FIELD']])) {
                                 $this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['FIELD']]['definition'] = $parsedQuery['definition'];
                                 // Adding field in the end of list.
                                 $this->xmlDB_writeStructure();
                                 return TRUE;
                                 // TODO: Should traverse all data an add that field in arrays!
                             } else {
                                 $this->errorStatus = 'Field "' . $parsedQuery['FIELD'] . '" already exists!';
                             }
                             break;
                         case 'CHANGE':
                             if (is_array($this->DBstructure['tables'][$table]['FIELDS'])) {
                                 if (is_array($this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['FIELD']])) {
                                     $newFieldInfo = array();
                                     foreach ($this->DBstructure['tables'][$table]['FIELDS'] as $fieldName => $fieldDefinition) {
                                         if (!strcmp($fieldName, $parsedQuery['FIELD'])) {
                                             // New fieldname?
                                             if ($parsedQuery['newField']) {
                                                 if (!is_array($this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['newField']])) {
                                                     $fieldName = $parsedQuery['newField'];
                                                 } else {
                                                     $this->errorStatus = 'A field in the table was already named "' . $parsedQuery['newField'] . '"';
                                                     return FALSE;
                                                 }
                                             }
                                             // Set new field definition:
                                             $fieldDefinition['definition'] = $parsedQuery['definition'];
                                         }
                                         // Set the whole thing in new var:
                                         $newFieldInfo[$fieldName] = $fieldDefinition;
                                     }
                                     $this->DBstructure['tables'][$table]['FIELDS'] = $newFieldInfo;
                                     $this->xmlDB_writeStructure();
                                     return TRUE;
                                     // TODO: Should traverse all data an remove that field in arrays!
                                 } else {
                                     $this->errorStatus = 'Field "' . $parsedQuery['FIELD'] . '" does not exist!';
                                 }
                             } else {
                                 $this->errorStatus = 'There are not fields in the table - strange!';
                             }
                             break;
                         case 'DROP':
                             if (is_array($this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['FIELD']])) {
                                 unset($this->DBstructure['tables'][$table]['FIELDS'][$parsedQuery['FIELD']]);
                                 // Removing it...
                                 $this->xmlDB_writeStructure();
                                 return TRUE;
                                 // TODO: Should traverse all data an remove that field in arrays!
                             } else {
                                 $this->errorStatus = 'Field "' . $parsedQuery['FIELD'] . '" does not exist!';
                             }
                             break;
                     }
                 } else {
                     $this->errorStatus = 'Table "' . $table . '" does not exist!';
                 }
                 break;
             case 'DROPTABLE':
                 // TODO:
                 debug($parsedQuery);
                 break;
             default:
                 $this->errorStatus = 'Query type "' . $parsedQuery['type'] . '" was not supported!';
                 break;
         }
     } else {
         $this->errorStatus = 'SQL parse error: ' . $parsedQuery;
     }
     return FALSE;
 }
 /**
  * Search for commented INCLUDE_TYPOSCRIPT statements
  * and save the content between the BEGIN and the END line to the specified file
  *
  * @param	 string	template content
  * @param	 int		Counter for detecting endless loops
  * @return	 string	 template content with uncommented include statements
  * @author	 Fabrizio Branca <*****@*****.**>
  */
 function extractIncludes($string, $cycle_counter = 1, $extractedFileNames = array())
 {
     if ($cycle_counter > 10) {
         t3lib_div::sysLog('It appears like TypoScript code is looping over itself. Check your templates for "&lt;INCLUDE_TYPOSCRIPT: ..." tags', 'Core', 2);
         return "\n###\n### ERROR: Recursion!\n###\n";
     }
     $fileContent = array();
     $restContent = array();
     $fileName = NULL;
     $inIncludePart = FALSE;
     $lines = explode("\n", $string);
     $skipNextLineIfEmpty = FALSE;
     $openingCommentedIncludeStatement = NULL;
     foreach ($lines as $line) {
         // t3lib_TSparser::checkIncludeLines inserts an additional empty line, remove this again
         if ($skipNextLineIfEmpty) {
             if (trim($line) == '') {
                 continue;
             }
             $skipNextLineIfEmpty = FALSE;
         }
         if (!$inIncludePart) {
             // outside commented include statements
             // search for beginning commented include statements
             $matches = array();
             if (preg_match('/###\\s*<INCLUDE_TYPOSCRIPT:\\s*source\\s*=\\s*"\\s*FILE\\s*:\\s*(.*)\\s*">\\s*BEGIN/i', $line, $matches)) {
                 // save this line in case there is no ending tag
                 $openingCommentedIncludeStatement = trim($line);
                 $openingCommentedIncludeStatement = trim(preg_replace('/### Warning: .*###/', '', $openingCommentedIncludeStatement));
                 // found a commented include statement
                 $fileName = trim($matches[1]);
                 $inIncludePart = TRUE;
                 $expectedEndTag = '### <INCLUDE_TYPOSCRIPT: source="FILE:' . $fileName . '"> END';
                 // strip all whitespace characters to make comparision safer
                 $expectedEndTag = strtolower(preg_replace('/\\s/', '', $expectedEndTag));
             } else {
                 // if this is not a beginning commented include statement this line goes into the rest content
                 $restContent[] = $line;
             }
         } else {
             // inside commented include statements
             // search for the matching ending commented include statement
             $strippedLine = strtolower(preg_replace('/\\s/', '', $line));
             if (strpos($strippedLine, $expectedEndTag) !== FALSE) {
                 // found the matching ending include statement
                 $fileContentString = implode("\n", $fileContent);
                 // write the content to the file
                 $realFileName = t3lib_div::getFileAbsFileName($fileName);
                 // some file checks
                 if (empty($realFileName)) {
                     throw new Exception(sprintf('"%s" is not a valid file location.', $fileName));
                 }
                 if (!is_writable($realFileName)) {
                     throw new Exception(sprintf('"%s" is not writable.', $fileName));
                 }
                 if (in_array($realFileName, $extractedFileNames)) {
                     throw new Exception(sprintf('Recursive/multiple inclusion of file "%s"', $realFileName));
                 }
                 $extractedFileNames[] = $realFileName;
                 // recursive call to detected nested commented include statements
                 $fileContentString = self::extractIncludes($fileContentString, ++$cycle_counter, $extractedFileNames);
                 if (!t3lib_div::writeFile($realFileName, $fileContentString)) {
                     throw new Exception(sprintf('Could not write file "%s"', $realFileName));
                 }
                 // insert reference to the file in the rest content
                 $restContent[] = "<INCLUDE_TYPOSCRIPT: source=\"FILE:{$fileName}\">";
                 // reset variables (preparing for the next commented include statement)
                 $fileContent = array();
                 $fileName = NULL;
                 $inIncludePart = FALSE;
                 $openingCommentedIncludeStatement = NULL;
                 // t3lib_TSparser::checkIncludeLines inserts an additional empty line, remove this again
                 $skipNextLineIfEmpty = TRUE;
             } else {
                 // if this is not a ending commented include statement this line goes into the file content
                 $fileContent[] = $line;
             }
         }
     }
     // if we're still inside commented include statements copy the lines back to the rest content
     if ($inIncludePart) {
         $restContent[] = $openingCommentedIncludeStatement . ' ### Warning: Corresponding end line missing! ###';
         $restContent = array_merge($restContent, $fileContent);
     }
     $restContentString = implode("\n", $restContent);
     return $restContentString;
 }